From d9b20bcd0d6006eb365224b0509d44ef38611d46 Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 2 Aug 2026 19:59:10 +0200 Subject: feat: add validate feature Signed-off-by: Henry --- crates/cli/Cargo.toml | 1 + 1 file changed, 1 insertion(+) (limited to 'crates/cli/Cargo.toml') diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 7dbd4d2..17b56e6 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -37,6 +37,7 @@ tinywasm = { workspace = true, features = [ "parallel-parser", "parser", "std", + "validate", ] } wast = { workspace = true, optional = true } wat = { workspace = true, optional = true } -- 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 'crates/cli/Cargo.toml') 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 7b9b3ec681e68280399d9c67e01433c2d3acb6c2 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Mon, 24 Aug 2026 15:47:05 +0200 Subject: feat: add host typed reference / gc APIs (#54) - add Store-aware handles for references, GC objects, and exceptions - simplify host value conversion, rooting, and exception propagation - update examples, tests, and documentation - Remove deprecated APIs Signed-off-by: Henry --- ARCHITECTURE.md | 65 -- CHANGELOG.md | 55 +- CONTRIBUTING.md | 4 +- Cargo.toml | 2 +- README.md | 48 +- crates/cli/Cargo.toml | 1 + crates/cli/src/cmd/run.rs | 5 +- crates/cli/src/testsuite.rs | 17 +- crates/cli/src/wast_runner.rs | 145 ++-- crates/parser/src/conversion.rs | 7 +- crates/tinywasm/src/error.rs | 25 +- crates/tinywasm/src/func/context.rs | 66 +- crates/tinywasm/src/func/host.rs | 108 +-- crates/tinywasm/src/func/mod.rs | 120 ++- crates/tinywasm/src/func/resume.rs | 108 ++- crates/tinywasm/src/func/values.rs | 97 +-- crates/tinywasm/src/imports.rs | 11 +- crates/tinywasm/src/instance.rs | 32 +- crates/tinywasm/src/interpreter/executor.rs | 208 ++--- .../tinywasm/src/interpreter/stack/value_stack.rs | 137 +-- crates/tinywasm/src/interpreter/values.rs | 57 +- crates/tinywasm/src/lib.rs | 48 +- crates/tinywasm/src/reference.rs | 513 ------------ crates/tinywasm/src/reference/managed.rs | 236 ++++++ crates/tinywasm/src/reference/mod.rs | 13 + crates/tinywasm/src/reference/store.rs | 915 +++++++++++++++++++++ crates/tinywasm/src/reference/value.rs | 232 ++++++ crates/tinywasm/src/store/const_expr.rs | 125 +-- crates/tinywasm/src/store/exception.rs | 10 - crates/tinywasm/src/store/function.rs | 8 - crates/tinywasm/src/store/gc/mod.rs | 74 +- crates/tinywasm/src/store/gc/object.rs | 148 ++-- crates/tinywasm/src/store/gc/roots.rs | 58 ++ crates/tinywasm/src/store/global.rs | 12 +- crates/tinywasm/src/store/mod.rs | 353 ++++++-- crates/tinywasm/src/store/state.rs | 228 ++--- crates/tinywasm/src/store/table.rs | 3 + crates/tinywasm/tests/gc_refs.rs | 61 +- crates/tinywasm/tests/host_func_signature_check.rs | 141 +++- crates/tinywasm/tests/imported_table_init.rs | 7 +- crates/tinywasm/tests/internal_refs.rs | 33 +- crates/tinywasm/tests/managed_exceptions.rs | 142 ++++ crates/tinywasm/tests/memory.rs | 22 +- crates/tinywasm/tests/reference_roots.rs | 104 +++ crates/tinywasm/tests/resume_execution.rs | 16 +- crates/tinywasm/tests/store_ownership.rs | 8 +- crates/tinywasm/tests/typed_gc_access.rs | 49 ++ crates/tinywasm/tests/typed_globals.rs | 8 +- crates/types/src/archive.rs | 42 +- crates/types/src/instructions.rs | 7 +- crates/types/src/lib.rs | 43 +- crates/types/src/reference.rs | 166 +--- crates/types/src/types.rs | 24 + crates/types/src/value.rs | 299 +------ examples/archive.rs | 8 +- examples/basic.rs | 26 + examples/exceptions.rs | 28 + examples/funcref_callbacks.rs | 123 --- examples/gc.rs | 33 + examples/linking.rs | 12 +- examples/reentrance.rs | 5 +- examples/references.rs | 34 + examples/resumable.rs | 2 + examples/rust.rs | 226 +++++ examples/rust/README.md | 4 +- examples/simple.rs | 22 - examples/simple2.rs | 21 - examples/wasm-rust.rs | 224 ----- 68 files changed, 3643 insertions(+), 2591 deletions(-) delete mode 100644 ARCHITECTURE.md delete mode 100644 crates/tinywasm/src/reference.rs create mode 100644 crates/tinywasm/src/reference/managed.rs create mode 100644 crates/tinywasm/src/reference/mod.rs create mode 100644 crates/tinywasm/src/reference/store.rs create mode 100644 crates/tinywasm/src/reference/value.rs delete mode 100644 crates/tinywasm/src/store/exception.rs create mode 100644 crates/tinywasm/src/store/gc/roots.rs create mode 100644 crates/tinywasm/tests/managed_exceptions.rs create mode 100644 crates/tinywasm/tests/reference_roots.rs create mode 100644 crates/tinywasm/tests/typed_gc_access.rs create mode 100644 examples/basic.rs create mode 100644 examples/exceptions.rs delete mode 100644 examples/funcref_callbacks.rs create mode 100644 examples/gc.rs create mode 100644 examples/references.rs create mode 100644 examples/rust.rs delete mode 100644 examples/simple.rs delete mode 100644 examples/simple2.rs delete mode 100644 examples/wasm-rust.rs (limited to 'crates/cli/Cargo.toml') diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md deleted file mode 100644 index 62fa503..0000000 --- a/ARCHITECTURE.md +++ /dev/null @@ -1,65 +0,0 @@ -# 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 a contiguous `Vec`-backed linear memory. - -## Execution Pipeline - -TinyWasm does not execute WebAssembly instructions directly. Parsing lowers them into an internal bytecode designed to make execution simpler and cheaper: - -- structured control flow (`block`, `loop`, `if`, and `br*`) becomes jump-oriented instructions such as `Jump`, `JumpIfZero`, `BranchTable*`, `DropKeep*`, and `Return` -- operand widths are encoded in instruction variants, and branch stack reshaping is explicit -- instructions retain compact module-local indexes, which each instance maps to Store-wide runtime addresses -- when enabled, the optimizer applies local rewrites, including superinstruction fusion, specialized calls and returns, and redundant-instruction removal -- modules can be serialized as `.twasm` archives containing this lowered representation -- execution uses a single iterative dispatch loop over the resulting instruction stream - -## Value Stacks - -WebAssembly combines an operand stack with function-scoped locals. TinyWasm stores both in the same width-specific physical stacks: - -- `stack_32` for `i32`, `f32`, and reference values, including GC and exception references -- `stack_64` for `i64` and `f64` -- `stack_128` for `v128` - -The interpreter does not maintain a runtime type stack or tag individual stack slots. Lowered instructions encode the physical lane they operate on, while WebAssembly validation guarantees type correctness. Splitting values by width lets each value use its natural storage size, reducing stack memory and the data moved by common operations. - -Locals are stored directly in these stacks. Each `CallFrame` records a base for every lane, and lowered local instructions index from those bases. The value stacks and call stack can use either a fixed capacity or dynamic initial and maximum sizes. Dynamic stacks keep the initial allocation small, grow when needed, and retain a hard limit. - -## Interpreter Optimization - -Instruction dispatch is one of the interpreter's main costs. TinyWasm reduces it through superinstructions and by shaping the large Rust dispatch match based on benchmarks and assembly inspection. Most simple arithmetic remains directly in the interpreter loop. Small, frequently used stack, value, and global operations use `#[inline]` or `#[inline(always)]` where measurements show a benefit, while unlikely error paths use `core::hint::cold_path()`. - -Superinstructions also reduce value-stack traffic. They can read locals, globals, and constants directly, perform an operation, and write `set` or `tee` destinations without materializing intermediate operand-stack values. Examples include: - -- fused binary operations such as `BinOpLocalLocal*`, `BinOpLocalConst*`, and `BinOpStackGlobal*` -- fused conditional branches such as `JumpCmpLocalConst*`, `JumpCmpLocalLocal*`, and `JumpCmpStackConst*` - -The default runtime remains safe Rust throughout rather than relying on unchecked operations. - -## SIMD - -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. - -## Linear Memory - -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. - -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. - -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`. - -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. - -## Important Modules - -- [visit.rs](./crates/parser/src/visit.rs) - function-body operator lowering -- [optimize.rs](./crates/parser/src/optimize.rs) - peephole optimizer and superinstruction fusion -- [parallel.rs](./crates/parser/src/parallel.rs) - parallel function parsing -- [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) - linear memory storage diff --git a/CHANGELOG.md b/CHANGELOG.md index 5473ebc..bad8caf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,47 +9,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Added support for the WebAssembly function-references proposal -- Added basic support for the WebAssembly garbage-collection proposal -- Added support for the WebAssembly exception-handling proposal, including tags, `try_table`, `throw`, and `throw_ref` -- Added support for the WebAssembly compact-imports proposal -- 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. -- Added a `ResourceLimiter` trait, configurable through `engine::Config::with_resource_limiter`, to bound guest memory, table, and logical GC heap growth. +- Support for the typed function references, garbage collection, exception handling, and compact import section proposals. +- `ResourceLimiter` callbacks for memory and table allocation or growth +- A default `validate` Cargo feature & parser option to skip wasm validation +- Optional parse-time operand deduplication to reduce `.twasm` archive size ### 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. -- 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. +- Typed functions now support tuples up to arity 20 and `[u8; 16]` values for `v128`. +- Module types now use one recursive type space. Runtime function types are available through `Function::ty(&Store)`. +- Linear memory now uses contiguous `Vec`-backed storage. +- The minimum supported Rust version increased from 1.95 to 1.98. +- The internal instruction represetaions size was reduced from 16 to 8 bytes. ### Fixed -- Directly defined imports now reject handles from a different `Store`. +- Instantiation now rejects directly defined imports that contain handles from another `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 and operand lowering. -- Fixed Memory64 default limits and host-size handling, including 32-bit targets. +- Memory64 bulk-memory operations and optimized stores now use the correct value-stack lanes. +- `memory.init` now performs correct bounds checks and operand lowering. +- Memory64 now uses the correct default limits and host-size conversions, including on 32-bit targets. ### Breaking Changes -- `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 }`. -- 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. +- `Function::call` and `Function::call_resumable` now write to caller-provided result slices. Untyped host callbacks also receive a result slice and return `Result<()>`. +- Creating a `HostFunction` no longer requires a `Store`. Definitions require `Send + Sync` and can be reused across stores. Module instantiation now borrows `Imports` so the same imports can also be reused. +- `HostFunction::ty` and `WasmFunction::ty` were removed. Use `Function::ty(&Store)` for runtime types. +- Function and managed reference handles are tied to their originating `Store`. Managed references keep their referents live, so `WasmValue` is no longer `Copy`. Nullable typed references use `Option`, while bare typed references are non-null. +- The `Memory`, `Table`, `Global`, and `Tag` constructors were renamed from `new` to `try_new`. +- `Store::id` now returns `u32`, and `ModuleInstanceAddr` was renamed to `ModuleInstanceId`. +- Element types now use `RefType`, and module definitions use `TableDefinition { ty, init }`. `Table::grow` now returns `Result>`, matching `Memory::grow`. +- `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. +- The `.twasm` format changed. Regenerate archives created by earlier TinyWasm versions. ## [0.10.0] - 2026-07-24 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6cb7761..73186e7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -33,7 +33,7 @@ $ cargo test-wast ./wasm-testsuite/data/wasm-v1/{file}.wast $ cargo test-wasm-custom # Run a specific example (run without arguments to see available examples) -# The wasm test files required to run the `wasm-rust` examples are not +# The wasm test files required to run the `rust` example are not # included in the main repository. # To build these, you will need to install binaryen and wabt # and run `./examples/rust/build.sh`. @@ -48,7 +48,7 @@ Example usage: ```bash cargo install --locked samply -samply record -- cargo run --release --example wasm-rust -- tinywasm +samply record -- cargo run --release --example rust -- tinywasm ``` ## Commits diff --git a/Cargo.toml b/Cargo.toml index 764ae53..12fad7e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ wat = "1.257" criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support", "rayon"] } [[example]] -name = "wasm-rust" +name = "rust" test = false [[bench]] diff --git a/README.md b/README.md index 5355249..70578dd 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,17 @@ # `tinywasm` -[![docs.rs](https://img.shields.io/docsrs/tinywasm?logo=rust&style=flat-square)](https://docs.rs/tinywasm) [![Crates.io](https://img.shields.io/crates/v/tinywasm.svg?logo=rust&style=flat-square)](https://crates.io/crates/tinywasm) [![Crates.io](https://img.shields.io/crates/l/tinywasm.svg?style=flat-square)](./LICENSE-APACHE) +[![Documentation](https://img.shields.io/badge/docs-latest-blue?style=flat-square)](https://docs.rs/tinywasm/latest/tinywasm/) [![Build](https://img.shields.io/github/actions/workflow/status/explodingcamera/tinywasm/test.yaml?branch=next&style=flat-square&label=build)](https://github.com/explodingcamera/tinywasm/actions/workflows/test.yaml?query=branch%3Anext) [![Crates.io](https://img.shields.io/crates/v/tinywasm.svg?logo=rust&style=flat-square)](https://crates.io/crates/tinywasm) [![Crates.io](https://img.shields.io/crates/l/tinywasm.svg?style=flat-square)](./LICENSE-APACHE) ## Why `tinywasm`? -- **Tiny**: Small by design, while still passing the full WebAssembly 3.0 core testsuite. -- **Portable**: Runs anywhere Rust can target, supports `no_std`, has minimal dependencies, and can itself compile to WebAssembly. -- **Safe**: Written in safe Rust, with optional `unsafe` limited to the `simd-x86` feature. Its sandbox is designed to prevent untrusted Wasm from accessing host memory or escaping the runtime. +- **Tiny**: Small by design, while still passing the full WebAssembly 3.0 core test suite. +- **Portable**: Runs anywhere Rust can target, supports `no_std`, has minimal dependencies[^dependencies], and can itself compile to WebAssembly. +- **Safe by default**: Written entirely in safe Rust[^unsafe]. + +[^dependencies]: The two main external components are [`wasmparser`](https://crates.io/crates/wasmparser) for WebAssembly parsing and validation, and [`postcard`](https://crates.io/crates/postcard) for `.twasm` archives. + +[^unsafe]: The optional `simd-x86` feature is the only exception. It uses `unsafe` internally for selected x86 SIMD intrinsics. ## Installation @@ -42,38 +46,40 @@ assert_eq!(result, 3); See the [examples](./examples) directory and [documentation](https://docs.rs/tinywasm) for more information. -## Precompiled Modules - -TinyWasm modules can be compiled to the internal `twasm` bytecode format, which stores the optimized instruction representation for faster loading and reuse. - ## Cargo Features - **`std`:** Enables `std` and parsing from files and streams. Enabled by default. - **`log`:** Enables integration with the `log` crate. Enabled by default. - **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default. -- **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through `ParserOptions`. +- **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through [`ParserOptions`](https://docs.rs/tinywasm/latest/tinywasm/parser/struct.ParserOptions.html). - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default. -- **`canonicalize-nans`:** Canonicalizes NaN values. Enabled by default. +- **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results. Enabled by default. - **`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`). - **`simd-x86`:** Enables x86-specific SIMD intrinsics and uses `unsafe` internally. -With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`[^libm], making it usable in `no_std + alloc` environments. +With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`, making it usable in `no_std + alloc` environments. + +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. + +## Precompiled Modules + +TinyWasm can serialize a parsed module to its version-specific `.twasm` format. Loading an archive skips WebAssembly parsing, validation, and optimization. -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, table, and GC heap growth and can trap rejected requests. +Applications that only load `.twasm` can remove the parser and validator from their binary by only enabling the `archive` feature. Depending on the target and release profile, this can produce binaries smaller than 300 KB. -[^libm]: [rust-lang/rust#137578](https://github.com/rust-lang/rust/issues/137578) — tracking issue for floating-point math support in `no_std`. +## Untrusted Input -## Safety +WebAssembly [validation](https://webassembly.github.io/spec/core/valid/index.html) is enabled by default through the `validate` feature. Keep this feature enabled and leave `ParserOptions::validation` enabled for modules from untrusted sources. Without validation, parsing can produce modules that violate runtime assumptions and may panic during instantiation or execution. -TinyWasm only uses safe Rust by default. The optional `simd-x86` feature enables x86-specific SIMD intrinsics and uses `unsafe` internally. WebAssembly input is validated by default through the `validate` feature. Disabling validation should not let Wasm access host memory or escape the sandbox, but malformed input may panic or otherwise crash the process, so only disable it for trusted input. +Validation does not limit parsing or execution resources. Hosts that run untrusted code should also set input limits, configure stack and `ResourceLimiter` limits, and use fuel- or time-budgeted execution as needed. -The internal `twasm` bytecode format is not currently validated as an untrusted input format. Malformed `twasm` may panic, but should not compromise memory safety or allow sandbox escape. Only run trusted `twasm` bytecode, or generate it through TinyWasm from Wasm input. +Loading `.twasm` checks the archive header and encoding but does not run WebAssembly validation or verify TinyWasm's runtime invariants. Load archives only from trusted sources. For untrusted input, parse a WebAssembly binary with validation enabled. -## Supported Proposals +## WebAssembly Proposal Support -TinyWasm targets non-JavaScript core proposals through [phase 3](https://github.com/WebAssembly/proposals). JavaScript integrations and optional embedding or tooling APIs are not included here. +TinyWasm generally implements non-JavaScript core proposals at [phase 4](https://github.com/WebAssembly/proposals#phase-4---standardize-the-feature-wg) or later, with some proposals implemented earlier. The table shows current support and known exceptions. | Proposal | Status | `tinywasm` Version | | ---------------------------------------------------------------------------------------------------------------- | ------ | ------------------ | @@ -95,8 +101,8 @@ TinyWasm targets non-JavaScript core proposals through [phase 3](https://github. | [**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` | | [**Stack Switching**](https://github.com/WebAssembly/stack-switching) | 🌑 | - | -| [**Compact Import Section**](https://github.com/WebAssembly/compact-import-section) | 🌑 | - | | [**Threads**](https://github.com/WebAssembly/threads) | 🌑 | - | **Legend**\ @@ -106,11 +112,13 @@ TinyWasm targets non-JavaScript core proposals through [phase 3](https://github. ## See Also -If you need a more mature, production-tested, or performance-focused WebAssembly runtime today, consider one of these projects: +If you're looking for a WebAssembly runtime with JIT compilation, better performance or other advanced features, check out these other runtimes: - [wasmi](https://github.com/wasmi-labs/wasmi) - efficient and versatile WebAssembly interpreter for embedded systems - [wasm3](https://github.com/wasm3/wasm3) - a fast WebAssembly interpreter written in C - [wazero](https://wazero.io/) - a zero-dependency WebAssembly interpreter written in Go +- [wasmer](https://wasmer.io/) - a fast and secure WebAssembly runtime written in Rust +- [wasmtime](https://wasmtime.dev/) - a fast and secure WebAssembly runtime written in Rust ## License diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 1aae437..069a4e2 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -35,6 +35,7 @@ tinywasm = { workspace = true, features = [ "archive", "canonicalize-nans", "debug", + "guest-debug", "log", "parallel-parser", "parser", diff --git a/crates/cli/src/cmd/run.rs b/crates/cli/src/cmd/run.rs index 3d25641..52cd273 100644 --- a/crates/cli/src/cmd/run.rs +++ b/crates/cli/src/cmd/run.rs @@ -29,7 +29,8 @@ pub fn run(args: RunArgs) -> Result<()> { .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)?; + let mut results = vec![tinywasm::WasmValue::I32(0); func.ty(&store)?.results().len()]; + func.call(&mut store, ¶ms, &mut results)?; print_results(&results); Ok(()) } @@ -44,7 +45,7 @@ pub fn run(args: RunArgs) -> Result<()> { "module has no start function or `_start` export. Use `tinywasm inspect {module_path}` or `tinywasm run --invoke {module_path}`" ) })?; - start.call(&mut store, &[])?; + start.call(&mut store, &[], &mut [])?; Ok(()) } } diff --git a/crates/cli/src/testsuite.rs b/crates/cli/src/testsuite.rs index 032aa88..b23b2c8 100644 --- a/crates/cli/src/testsuite.rs +++ b/crates/cli/src/testsuite.rs @@ -7,9 +7,14 @@ 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 core::fmt::Debug for TestFailure { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + Display::fmt(self, f) + } +} + impl Display for TestFailure { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) @@ -89,13 +94,9 @@ impl TestSuite { } 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(()) - } + self.print_errors(); + println!("{self}"); + if self.runner.failed() { Err(TestFailure("failed one or more tests".into()).into()) } else { Ok(()) } } pub fn save_csv(&self, path: &str, version: &str) -> TestResult<()> { diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 023c959..3f905d4 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -7,10 +7,7 @@ use std::time::Duration; use anyhow::{Context, Result, anyhow, bail}; use log::{debug, error}; -use tinywasm::types::{ - AbstractHeapType as TinyAbstractHeapType, AnyRef, ExternRef, FuncRef, MemoryType, RefType, RefValue, TableType, - WasmType, WasmValue, -}; +use tinywasm::types::{MemoryType, RefType, RefValue, TableType, WasmType, WasmValue}; use tinywasm::{ExecProgress, Global, HostFunction, Imports, Memory, Module, ModuleInstance, Store, Table}; use wast::{QuoteWat, core::AbstractHeapType}; @@ -171,17 +168,18 @@ impl WastRunner { fn imports(store: &mut Store, modules: &HashMap) -> Result { let mut imports = Imports::new(); - let table = Table::new(store, TableType::new(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?; - let table64 = Table::new(store, TableType::new64(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?; - let memory = Memory::new(store, MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)))?; + let table = Table::try_new(store, TableType::new(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?; + let table64 = Table::try_new(store, TableType::new64(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?; + let memory = + Memory::try_new(store, MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)))?; let global_i32 = - Global::new(store, tinywasm::types::GlobalType::new(WasmType::I32, false), WasmValue::I32(666))?; + Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::I32, false), WasmValue::I32(666))?; let global_i64 = - Global::new(store, tinywasm::types::GlobalType::new(WasmType::I64, false), WasmValue::I64(666))?; + Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::I64, false), WasmValue::I64(666))?; let global_f32 = - Global::new(store, tinywasm::types::GlobalType::new(WasmType::F32, false), WasmValue::F32(666.6))?; + Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::F32, false), WasmValue::F32(666.6))?; let global_f64 = - Global::new(store, tinywasm::types::GlobalType::new(WasmType::F64, false), WasmValue::F64(666.6))?; + Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::F64, false), WasmValue::F64(666.6))?; imports .define("spectest", "memory", memory) @@ -227,6 +225,7 @@ impl WastRunner { let mut store = Store::default(); let mut module_registry = ModuleRegistry::default(); + let mut call_results = Vec::new(); println!("running {} tests for group: {}", directives.len(), file.name()); for (i, directive) in directives.into_iter().enumerate() { @@ -333,9 +332,10 @@ impl WastRunner { } AssertExhaustion { call, message, span } => { let module = module_registry.get_idx(call.module); - let args = convert_wastargs(call.args)?; - let res = - catch_unwind_silent(|| exec_fn_instance(module, &mut store, call.name, &args).map(|_| ())); + let args = convert_wastargs(&mut store, call.args)?; + let res = catch_unwind_silent(|| { + exec_fn_instance(module, &mut store, call.name, &args, &mut call_results) + }); let Ok(Err(tinywasm::Error::Trap(trap))) = res else { test_group.add_result( &format!("AssertExhaustion({i})"), @@ -368,9 +368,9 @@ impl WastRunner { wast::WastExecute::Invoke(invoke) => invoke, }; let module = module_registry.get_idx(invoke.module); - let args = - convert_wastargs(invoke.args).map_err(|err| tinywasm::Error::Other(err.to_string()))?; - exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ()) + let args = convert_wastargs(&mut store, invoke.args) + .map_err(|err| tinywasm::Error::Other(err.to_string()))?; + exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results) }); match res { Err(err) => test_group.add_result( @@ -415,9 +415,9 @@ impl WastRunner { wast::WastExecute::Invoke(invoke) => invoke, }; let module = module_registry.get_idx(invoke.module); - let args = - convert_wastargs(invoke.args).map_err(|err| tinywasm::Error::Other(err.to_string()))?; - exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ()) + let args = convert_wastargs(&mut store, invoke.args) + .map_err(|err| tinywasm::Error::Other(err.to_string()))?; + exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results) }); let result = match res { Err(err) => Err(anyhow!("test panicked: {}", try_downcast_panic(err))), @@ -469,9 +469,9 @@ impl WastRunner { Invoke(invoke) => { let name = invoke.name; let res: Result, _> = catch_unwind_silent(|| { - let args = convert_wastargs(invoke.args)?; + let args = convert_wastargs(&mut store, invoke.args)?; let module = module_registry.get_idx(invoke.module); - exec_fn_instance(module, &mut store, invoke.name, &args).map_err(|e| { + exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results).map_err(|e| { error!("failed to execute function: {e:?}"); e })?; @@ -504,7 +504,7 @@ impl WastRunner { ); continue; }; - let module_global = match module.global_get(&store, global) { + let module_global = match module.global_get(&mut store, global) { Ok(value) => value, Err(err) => { test_group.add_result( @@ -518,7 +518,7 @@ impl WastRunner { let expected = expected_alternatives .iter() .filter_map(|alts| alts.first()) - .find(|exp| exp.matches(&module_global, &store)); + .find(|exp| exp.matches(&module_global, &store, &module)); if expected.is_none() { test_group.add_result( &format!("AssertReturn(unsupported-{i})"), @@ -552,25 +552,28 @@ impl WastRunner { let invoke_name = invoke.name; let res: Result, _> = catch_unwind_silent(|| { - let args = convert_wastargs(invoke.args)?; - let module = module_registry.get_idx(invoke.module); - let outcomes = exec_fn_instance(module, &mut store, invoke.name, &args).map_err(|e| { - error!("failed to execute function: {e:?}"); - e - })?; - if !expected_alternatives.iter().any(|expected| expected.len() == outcomes.len()) { + let args = convert_wastargs(&mut store, invoke.args)?; + let module = module_registry + .get(invoke.module) + .ok_or_else(|| anyhow!("module instance was not found"))?; + exec_fn_instance(Some(module.id()), &mut store, invoke.name, &args, &mut call_results) + .map_err(|e| { + error!("failed to execute function: {e:?}"); + e + })?; + if !expected_alternatives.iter().any(|expected| expected.len() == call_results.len()) { return Err(anyhow!( "expected {} results, got {}", expected_alternatives.first().map_or(0, |v| v.len()), - outcomes.len() + call_results.len() )); } if expected_alternatives.iter().any(|expected| { - expected.len() == outcomes.len() - && outcomes + expected.len() == call_results.len() + && call_results .iter() .zip(expected.iter()) - .all(|(outcome, exp)| exp.matches(outcome, &store)) + .all(|(outcome, exp)| exp.matches(outcome, &store, &module)) }) { Ok(()) } else { @@ -715,12 +718,12 @@ fn exec_with_budget( func: &tinywasm::Function, store: &mut Store, args: &[WasmValue], -) -> Result, tinywasm::Error> { - let mut exec = func.call_resumable(store, args)?; + results: &mut [WasmValue], +) -> Result<(), tinywasm::Error> { + let mut exec = func.call_resumable(store, args, results)?; for _ in 0..TEST_MAX_SUSPENSIONS { - match exec.resume_with_time_budget(TEST_TIME_SLICE)? { - ExecProgress::Completed(values) => return Ok(values), - ExecProgress::Suspended => {} + if let ExecProgress::Completed(()) = exec.resume_with_time_budget(TEST_TIME_SLICE)? { + return Ok(()); } } Err(tinywasm::Error::Other(format!( @@ -741,7 +744,8 @@ fn exec_fn_instance( store: &mut Store, name: &str, args: &[WasmValue], -) -> Result, tinywasm::Error> { + results: &mut Vec, +) -> Result<(), tinywasm::Error> { let Some(instance) = instance else { return Err(tinywasm::Error::Other("no instance found".to_string())); }; @@ -749,7 +753,9 @@ fn exec_fn_instance( return Err(tinywasm::Error::Other("no instance found".to_string())); }; let func = instance.func_untyped(store, name)?; - exec_with_budget(&func, store, args) + results.clear(); + results.resize(func.ty(store)?.results().len(), WasmValue::I32(0)); + exec_with_budget(&func, store, args, results) } fn catch_unwind_silent(f: impl FnOnce() -> R) -> std::thread::Result { @@ -790,8 +796,8 @@ fn parse_quote_module(module: QuoteWat) -> Result<(Option, Module)> { Ok((name, parse_module_bytes(&bytes)?)) } -fn convert_wastargs(args: Vec) -> Result> { - args.into_iter().map(wastarg2tinywasmvalue).collect() +fn convert_wastargs(store: &mut Store, args: Vec) -> Result> { + args.into_iter().map(|arg| wastarg2tinywasmvalue(store, arg)).collect() } fn convert_wastret<'a>(args: impl Iterator>) -> Result>> { @@ -802,7 +808,7 @@ fn convert_wastret<'a>(args: impl Iterator>) -> Result< for prefix in alternatives { for choice in &choices { let mut candidate = prefix.clone(); - candidate.push(*choice); + candidate.push(choice.clone()); next.push(candidate); } } @@ -811,7 +817,7 @@ fn convert_wastret<'a>(args: impl Iterator>) -> Result< Ok(alternatives) } -fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result { +fn wastarg2tinywasmvalue(store: &mut Store, arg: wast::WastArg) -> Result { let wast::WastArg::Core(arg) = arg else { bail!("unsupported arg type: Component"); }; @@ -822,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(|| anyhow!("external reference address is too large"))?.into(), + RefExtern(v) => tinywasm::ExternRef::try_new(store, v)?.into(), RefNull(t) => match t { wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Func } => RefValue::Null.into(), wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Extern | AbstractHeapType::Any } => { @@ -832,10 +838,7 @@ fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result { bail!("unsupported arg type: refnull: {:?}", t); } }, - RefHost(value) => { - RefValue::Any(AnyRef::from_host(value).ok_or_else(|| anyhow!("host reference address is too large"))?) - .into() - } + RefHost(value) => RefValue::Any(tinywasm::ExternRef::try_new(store, value)?.to_any()).into(), }) } @@ -855,7 +858,7 @@ fn wast_v128_to_bytes(i: wast::core::V128Pattern) -> [u8; 16] { res.try_into().unwrap() } -#[derive(Clone, Copy)] +#[derive(Clone)] enum ExpectedValue { Exact(WasmValue), RefNull, @@ -866,24 +869,35 @@ enum ExpectedValue { RefI31, RefStruct, RefArray, + RefExternExact(u32), + RefFuncExact(u32), + RefHostExact(u32), } impl ExpectedValue { - fn matches(&self, value: &WasmValue, store: &Store) -> bool { + fn matches(&self, value: &WasmValue, store: &Store, module: &ModuleInstance) -> bool { match self { Self::Exact(expected) => value.eq_loose(expected), Self::RefNull => matches!(value, WasmValue::Ref(RefValue::Null)), Self::RefFunc => matches!(value, WasmValue::Ref(RefValue::Func(_))), Self::RefExtern => matches!(value, WasmValue::Ref(RefValue::Extern(_))), Self::RefAny => matches!(value, WasmValue::Ref(RefValue::Any(_))), - Self::RefEq => { - store.value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Eq))) - } + Self::RefEq => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_eq().is_some()), Self::RefI31 => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_i31().is_some()), - Self::RefStruct => store - .value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Struct))), - Self::RefArray => store - .value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Array))), + Self::RefStruct => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_struct().is_some()), + Self::RefArray => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_array().is_some()), + Self::RefExternExact(expected) => match value { + WasmValue::Ref(RefValue::Extern(value)) => value.key(store) == Ok(*expected), + _ => false, + }, + Self::RefHostExact(expected) => match value { + WasmValue::Ref(RefValue::Any(value)) => value.to_extern().key(store) == Ok(*expected), + _ => false, + }, + Self::RefFuncExact(expected) => module + .func_by_index(store, *expected) + .and_then(|function| function.as_func_ref(store)) + .is_ok_and(|expected| matches!(value, WasmValue::Ref(RefValue::Func(value)) if *value == expected)), } } } @@ -912,11 +926,9 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result ExpectedValue::Exact(WasmValue::I64(i)), V128(i) => ExpectedValue::Exact(WasmValue::V128(wast_v128_to_bytes(i))), RefNull(_) => ExpectedValue::RefNull, - RefExtern(Some(v)) => ExpectedValue::Exact( - ExternRef::try_new(v).ok_or_else(|| anyhow!("external reference address is too large"))?.into(), - ), + RefExtern(Some(v)) => ExpectedValue::RefExternExact(v), RefExtern(None) => ExpectedValue::RefExtern, - RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::Exact(FuncRef::new(n).into()), + RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::RefFuncExact(n), RefFunc(None) => ExpectedValue::RefFunc, RefFunc(v) => { bail!("unsupported arg type: reffunc: {:?}", v); @@ -926,10 +938,7 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result ExpectedValue::RefI31, RefStruct => ExpectedValue::RefStruct, RefArray => ExpectedValue::RefArray, - RefHost(value) => ExpectedValue::Exact( - RefValue::Any(AnyRef::from_host(value).ok_or_else(|| anyhow!("host reference address is too large"))?) - .into(), - ), + RefHost(value) => ExpectedValue::RefHostExact(value), a => { bail!("unsupported arg type {:?}", a); } diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 8f39398..6857a19 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -342,12 +342,9 @@ pub(crate) fn process_const_operators( } let instr = match op { - wasmparser::Operator::RefNull { hty } => { - convert_heap_type(hty, false)?; - ConstInstruction::Ref(RefValue::Null) - } + wasmparser::Operator::RefNull { hty } => ConstInstruction::RefNull(convert_heap_type(hty, true)?), wasmparser::Operator::RefFunc { function_index } => { - ConstInstruction::Ref(RefValue::Func(FuncRef::new(function_index))) + ConstInstruction::RefFunc(ModuleFuncIdx::new(function_index)) } wasmparser::Operator::RefI31 => ConstInstruction::RefI31, wasmparser::Operator::AnyConvertExtern => ConstInstruction::AnyConvertExtern, diff --git a/crates/tinywasm/src/error.rs b/crates/tinywasm/src/error.rs index 05e36aa..77856af 100644 --- a/crates/tinywasm/src/error.rs +++ b/crates/tinywasm/src/error.rs @@ -2,8 +2,10 @@ use alloc::boxed::Box; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::fmt::{Debug, Display}; +use tinywasm_types::FuncType; use tinywasm_types::archive::TwasmError; -use tinywasm_types::{ExnRef, FuncType}; + +use crate::{ExnRef, WasmValue}; #[cfg(feature = "parser")] pub use tinywasm_parser::ParseError; @@ -31,7 +33,7 @@ pub enum Error { /// The expected type expected: Box, /// The actual value - actual: Vec, + actual: Vec, }, /// An invalid label type was encountered @@ -105,9 +107,11 @@ impl Error { } } -/// A WebAssembly trap +/// An execution or runtime trap. +/// +/// This includes WebAssembly traps and TinyWasm runtime failures. /// -/// See +/// See #[non_exhaustive] #[cfg_attr(feature = "debug", derive(Debug))] pub enum Trap { @@ -123,7 +127,7 @@ pub enum Trap { offset: usize, /// The size of the access len: usize, - /// The maximum size of the memory + /// The current memory length in bytes. max: usize, }, @@ -133,7 +137,7 @@ pub enum Trap { offset: usize, /// The size of the access len: usize, - /// The maximum size of the memory + /// The current table length in elements. max: usize, }, @@ -146,9 +150,12 @@ pub enum Trap { /// Invalid Integer Conversion InvalidConversionToInt, - /// The store is not the one that the module instance was instantiated in + /// A Store-owned handle or reference was used with a different Store. InvalidStore, + /// A reference does not identify a live value of the expected kind. + InvalidReference, + /// Integer Overflow IntegerOverflow, @@ -158,7 +165,7 @@ pub enum Trap { /// Value stack overflow ValueStackOverflow, - /// The runtime could not allocate memory for a stack or linear memory operation. + /// An allocation or requested resource size could not be satisfied. OutOfMemory, /// An undefined element was encountered @@ -228,6 +235,7 @@ impl Trap { Self::IndirectCallTypeMismatch { .. } => "indirect call type mismatch", Self::HostFunction(_) => "host function trap", Self::InvalidStore => "invalid store", + Self::InvalidReference => "invalid reference", Self::Other(message) => message, } } @@ -337,6 +345,7 @@ impl Display for Trap { Self::NullI31Reference => write!(f, "null i31 reference"), Self::CastFailure => write!(f, "cast failure"), Self::InvalidStore => write!(f, "invalid store"), + Self::InvalidReference => write!(f, "invalid reference"), #[cfg(feature = "debug")] Self::IndirectCallTypeMismatch { expected, actual } => { write!(f, "indirect call type mismatch: expected={expected:?}, actual={actual:?}") diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs index 95a2cec..7e289f6 100644 --- a/crates/tinywasm/src/func/context.rs +++ b/crates/tinywasm/src/func/context.rs @@ -1,7 +1,6 @@ -use alloc::vec::Vec; -use tinywasm_types::{ModuleInstanceId, WasmValue}; +use tinywasm_types::ModuleInstanceId; -use crate::{Error, FromWasmValues, Function, FunctionTyped, IntoWasmValues, Result}; +use crate::{Error, FromWasmValues, FuncRef, Function, FunctionTyped, IntoWasmValues, Result, WasmValue}; /// The context of a host-function call #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] @@ -45,7 +44,7 @@ impl FuncContext<'_> { } /// Get the value of a global export. - pub fn global_get(&self, name: &str) -> Result { + pub fn global_get(&mut self, name: &str) -> Result { self.module().global_get(self.store, name) } @@ -84,17 +83,26 @@ impl FuncContext<'_> { /// 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> { + pub fn call_untyped(&mut self, func: &Function, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { if !self.store.execution_active { return Err(Error::other("FuncContext::call requires an active host-function invocation")); } - func.item.validate_store(self.store)?; - func.validate_params(self.store, args)?; + 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, call_stack_base, value_stack_base) + func.call_untyped(self.store, 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.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 }; + self.call_untyped(&function, args, results) } /// Call a typed function from within the current host-function invocation. @@ -112,20 +120,29 @@ 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()) { - 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 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_exact(&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, &func_instance, params.into_wasm_values(), call_stack_base, value_stack_base) } } @@ -142,10 +159,3 @@ impl core::ops::DerefMut for FuncContext<'_> { 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 index 27c5573..8f36761 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -1,8 +1,9 @@ use alloc::{boxed::Box, sync::Arc, vec::Vec}; -use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType, WasmValue}; +use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType}; use super::{FromWasmValues, FuncContext, IntoWasmValues, ToWasmTypes}; -use crate::{Function, FunctionInstance, Result, Store}; +use crate::store::FuncValueTypes; +use crate::{Function, FunctionInstance, Result, Store, WasmValue}; /// A reusable host function definition. #[derive(Clone)] @@ -11,12 +12,8 @@ pub struct HostFunction(Arc); 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, - 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 } + let addr = store.add_func(FunctionInstance { type_addr, kind: crate::store::FunctionKind::Host(self.clone()) }); + Function { item: crate::StoreItem::new(store.store_id(), addr), module_id: 0 } } /// Resolves the importing module's types without allocating a function instance. @@ -45,19 +42,26 @@ impl HostFunction { 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 }) + 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), + }; + } + 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)?, } + 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() }); + } + Ok(()) } /// Returns the allocation-free typed callback when one is available. @@ -79,8 +83,9 @@ impl HostFunction { /// /// # Errors /// - /// Returns an error if the signature uses a store-specific reference type - /// that is not registered in `store`. + /// Returns an error if the signature contains a concrete reference type. + /// Define the function through [`crate::Imports`] when concrete types must + /// be resolved against an importing module. /// /// ## Example /// @@ -93,7 +98,9 @@ impl HostFunction { /// 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)]); + /// let mut results = [WasmValue::I32(0)]; + /// function.call(&mut store, &[WasmValue::I32(41)], &mut results)?; + /// assert_eq!(results, [WasmValue::I32(42)]); /// # Ok(()) /// # } /// ``` @@ -104,13 +111,9 @@ impl HostFunction { .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()) + .any(|ty| matches!(ty, WasmType::Ref(ty) if ty.is_concrete())) { - return Err(crate::Error::other("host function signature contains a concrete type from another store")); + return Err(crate::Error::other("standalone host functions cannot use concrete reference types")); } let type_addr = store.register_host_type(&self.0.ty); Ok(self.instantiate_registered(store, type_addr)) @@ -136,11 +139,12 @@ impl HostFunction { /// # 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 add_one = HostFunction::from_untyped(&ty, |_ctx: FuncContext<'_>, args, results| { /// let WasmValue::I32(value) = args[0] else { /// return Err(tinywasm::Error::Other("expected i32".into())); /// }; - /// Ok(vec![WasmValue::I32(value + 1)]) + /// results[0] = WasmValue::I32(value + 1); + /// Ok(()) /// }); /// /// let mut imports = Imports::new(); @@ -153,7 +157,7 @@ impl HostFunction { /// ``` pub fn from_untyped( ty: &FuncType, - func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result> + Send + Sync + 'static, + 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)) })) } @@ -207,10 +211,10 @@ enum HostCallback { Typed(Box), } -type UntypedHostCallback = dyn Fn(FuncContext<'_>, &[WasmValue]) -> Result> + Send + Sync; +type UntypedHostCallback = dyn Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()> + Send + Sync; pub(crate) trait TypedHostCallback: Send + Sync { - fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue]) -> Result>; + 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,30 +229,30 @@ where 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)?; + fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { + let mut values = args.iter().cloned(); + let params = P::from_wasm_values_exact(&mut values)?; + let mut values = (self.func)(ctx, params)?.into_wasm_values(); + for result in results { + *result = values.next().ok_or_else(|| crate::Error::other("not enough typed function results"))?; + } if values.next().is_some() { - return Err(crate::Error::other("typed conversion did not consume all WebAssembly values")); + return Err(crate::Error::other("too many typed function results")); } - Ok((self.func)(ctx, params)?.into_wasm_values().collect()) + Ok(()) } 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); + let base = { + let params = store.state.get_canonical_func_type(type_addr).params(); + store.value_stack.base_before(params.iter().collect()) + }; + let params = { + let mut values = store.stack_value_iter(type_addr, FuncValueTypes::Params, base)?; + P::from_wasm_values_exact(&mut values) + }; store.value_stack.truncate_to_base(base); - let params = params?; - let result = (self.func)(FuncContext { store, module_id }, params)?; + let result = (self.func)(FuncContext { store, module_id }, params?)?; store.push_typed_values::(type_addr, result.into_wasm_values(), base) } } diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs index 34a1938..c29b3db 100644 --- a/crates/tinywasm/src/func/mod.rs +++ b/crates/tinywasm/src/func/mod.rs @@ -1,9 +1,11 @@ use crate::interpreter::stack::{CallFrame, StackBase}; use crate::reference::StoreItem; use crate::{Error, FunctionInstance, InterpreterRuntime, Result, Store}; -use alloc::{format, vec::Vec}; +use alloc::format; use core::hint::cold_path; -use tinywasm_types::{FuncAddr, FuncType, ModuleInstanceId, WasmValue}; +use tinywasm_types::{FuncAddr, FuncType, ModuleInstanceId}; + +use crate::{FuncRef, WasmValue}; mod context; mod host; @@ -12,11 +14,21 @@ 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 +fn write_typed_params(params: &mut [WasmValue], mut values: impl Iterator) -> Result<()> { + for param in params { + *param = values.next().ok_or_else(|| Error::other("not enough typed function parameters"))?; + } + if values.next().is_some() { + return Err(Error::other("too many typed function parameters")); + } + Ok(()) +} + +/// A handle to a function instance in a store. +/// +/// See #[derive(Clone)] #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] pub struct Function { @@ -25,6 +37,12 @@ pub struct Function { } 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())) + } + #[inline] /// Returns the function's address in its store. pub(crate) const fn addr(&self) -> FuncAddr { @@ -39,23 +57,24 @@ impl Function { Ok(store.state.get_func_type(self.addr())) } - /// Call a function (Invocation) + /// Calls the function and writes its results to `results`. /// - /// See + /// The initial result values are ignored. The result slice length must + /// match the function signature. #[inline] - pub fn call(&self, store: &mut Store, params: &[WasmValue]) -> Result> { - self.item.validate_store(store)?; - self.validate_params(store, params)?; + pub fn call(&self, store: &mut Store, params: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { + 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, 0, StackBase::default()); + let result = self.call_untyped(store, params, results, 0, StackBase::default()); store.exit_execution(); result } - fn validate_params(&self, store: &Store, params: &[WasmValue]) -> 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()); if func_ty.params().len() != params.len() { cold_path(); @@ -66,17 +85,29 @@ impl Function { ))); } - if !func_ty.params().iter().zip(params).all(|(ty, param)| store.state.value_matches_type(*param, *ty)) { + for param in params { + if matches!(param, WasmValue::Ref(_)) { + param.to_runtime(store)?; + } + } + + if !func_ty.params().iter().zip(params).all(|(ty, param)| store.value_matches_type(param, *ty)) { cold_path(); #[cfg(feature = "debug")] return Err(Error::Other(format!( "param type mismatch: expected {:?}, got {:?}", func_ty.params(), - params.iter().map(|v| v.ty()).collect::>() + params.iter().map(|v| v.ty()).collect::>() ))); #[cfg(not(feature = "debug"))] return Err(Error::Other("param type mismatch".into())); } + if func_ty.results().len() != result_count { + return Err(Error::Other(format!( + "result count mismatch: expected {}, got {result_count}", + func_ty.results().len() + ))); + } Ok(()) } @@ -85,35 +116,36 @@ impl Function { &self, store: &mut Store, params: &[WasmValue], + results: &mut [WasmValue], call_stack_base: u32, value_stack_base: StackBase, - ) -> Result> { + ) -> 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 { + match &instance.kind { crate::store::FunctionKind::Host(host) => { let host = host.clone(); - host.call_values(store, self.module_id, type_addr, params) + host.call_values(store, self.module_id, type_addr, params, results) } 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)?; + 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_types = store.state.get_canonical_func_type(type_addr).results(); - Ok(store.value_stack.pop_wasmvalues(&store.state, result_types)) + let result_type = store.state.get_canonical_func_type(type_addr).clone(); + store.pop_stack_values(result_type.results(), results) } - }; - if results_may_gc && let Ok(values) = &result { - store.state.pin_host_values(values); } - result } fn prepare_typed( @@ -157,7 +189,7 @@ impl Function { store.value_stack.truncate_to_base(value_stack_base); })?; } - store.take_typed_results(instance.type_addr, value_stack_base, instance.gc.results) + store.take_typed_results(instance.type_addr, value_stack_base) } } @@ -178,24 +210,24 @@ impl FunctionTyped { 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")) + 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_exact(&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()?; - 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 index 892aa05..6772eb8 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -1,9 +1,8 @@ -use alloc::vec::Vec; -use tinywasm_types::{FuncAddr, TypeAddr, WasmValue}; +use tinywasm_types::{FuncAddr, TypeAddr}; use super::{FromWasmValues, Function, FunctionTyped, IntoWasmValues}; use crate::interpreter::stack::{CallFrame, StackBase}; -use crate::{Error, InterpreterRuntime, Result, Store}; +use crate::{Error, InterpreterRuntime, Result, Store, WasmValue}; #[derive(Clone, PartialEq, Eq)] /// Progress for fuel-limited function execution. @@ -17,6 +16,12 @@ 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>, + results: &'store mut [WasmValue], +} + +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +struct ExecutionCore<'store> { store: &'store mut Store, state: FuncExecutionState, } @@ -29,15 +34,15 @@ enum FuncExecutionState { #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] enum CallResult { - Stack { type_addr: TypeAddr, pin_refs: bool }, - Values(Vec), + Stack { type_addr: TypeAddr }, + Written, } /// 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, + execution: ExecutionCore<'store>, + result: Option, } impl Function { @@ -50,30 +55,24 @@ impl Function { &self, store: &'store mut Store, params: &[WasmValue], + results: &'store mut [WasmValue], ) -> Result> { - self.item.validate_store(store)?; - self.validate_params(store, params)?; - let results_may_gc = store.state.get_func(self.addr()).gc.results; + 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.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)))) + 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) => { 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(), - )?; + 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); Ok(FuncExecutionState::Running { callframe, root_func_addr: self.addr() }) @@ -83,14 +82,11 @@ impl Function { 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 }) + Ok(FuncExecution { execution: ExecutionCore { store, state }, results }) } } -impl<'store> FuncExecution<'store> { +impl ExecutionCore<'_> { fn resume_raw( &mut self, run: impl FnOnce(&mut Store, CallFrame) -> Result, @@ -123,9 +119,8 @@ impl<'store> FuncExecution<'store> { 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 })) + Ok(ExecProgress::Completed(CallResult::Stack { type_addr: result_ty })) } crate::interpreter::ExecState::Suspended(callframe) => { let FuncExecutionState::Running { callframe: current, .. } = &mut self.state else { @@ -136,21 +131,20 @@ impl<'store> FuncExecution<'store> { } } } +} +impl FuncExecution<'_> { 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)) + ) -> 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)?; + Ok(ExecProgress::Completed(())) } - ExecProgress::Completed(CallResult::Values(values)) => Ok(ExecProgress::Completed(values)), + ExecProgress::Completed(CallResult::Written) => Ok(ExecProgress::Completed(())), ExecProgress::Suspended => Ok(ExecProgress::Suspended), } } @@ -161,13 +155,13 @@ impl<'store> FuncExecution<'store> { /// 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. + /// [`ExecProgress::Completed`] after writing the final values to the result + /// slice supplied to [`Function::call_resumable`]. /// /// Reentrant calls made by host functions through [`crate::FuncContext::call`] are /// currently blocking. They do not suspend and later resume the host /// function in the middle of the nested call. - pub fn resume_with_fuel(&mut self, fuel: u32) -> Result>> { + pub fn resume_with_fuel(&mut self, fuel: u32) -> Result> { self.resume(|store, callframe| InterpreterRuntime::exec_with_fuel(store, callframe, fuel)) } @@ -180,10 +174,7 @@ impl<'store> FuncExecution<'store> { /// /// 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>> { + 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)) } } @@ -215,9 +206,9 @@ impl FunctionTyped { 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 }); + let result = self.call(store, params)?; + let execution = ExecutionCore { store, state: FuncExecutionState::Completed(None) }; + return Ok(FuncExecutionTyped { execution, result: Some(result) }); } store.enter_execution()?; @@ -226,15 +217,12 @@ impl FunctionTyped { 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, - }))), + None => Ok(FuncExecutionState::Completed(Some(CallResult::Stack { type_addr: func.type_addr }))), } })(); store.exit_execution(); - let execution = FuncExecution { store, state: result? }; - Ok(FuncExecutionTyped { execution, marker: core::marker::PhantomData }) + let execution = ExecutionCore { store, state: result? }; + Ok(FuncExecutionTyped { execution, result: None }) } } @@ -243,18 +231,14 @@ impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> { &mut self, run: impl FnOnce(&mut Store, CallFrame) -> Result, ) -> Result> { + if let Some(result) = self.result.take() { + return Ok(ExecProgress::Completed(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::Completed(CallResult::Stack { type_addr }) => { + Ok(ExecProgress::Completed(self.execution.store.take_typed_results(type_addr, StackBase::default())?)) } + ExecProgress::Completed(CallResult::Written) => unreachable!("untyped result in typed execution"), ExecProgress::Suspended => Ok(ExecProgress::Suspended), } } diff --git a/crates/tinywasm/src/func/values.rs b/crates/tinywasm/src/func/values.rs index 319b493..19d0673 100644 --- a/crates/tinywasm/src/func/values.rs +++ b/crates/tinywasm/src/func/values.rs @@ -1,6 +1,8 @@ use crate::{Error, Result}; -use alloc::{borrow::Cow, vec::Vec}; -use tinywasm_types::{ExternRef, FuncRef, WasmType, WasmValue}; +use alloc::borrow::Cow; +use tinywasm_types::WasmType; + +use crate::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, StructRef, WasmValue}; /// Convert a Rust value or tuple into WebAssembly values. pub trait IntoWasmValues { @@ -12,6 +14,15 @@ pub trait IntoWasmValues { pub trait FromWasmValues: Sized { /// Read this value from a flattened WebAssembly value iterator. 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. @@ -117,70 +128,28 @@ impl_scalar_wasm_traits!( i64 => WasmType::I64, f32 => WasmType::F32, f64 => WasmType::F64, - FuncRef => WasmType::Ref(tinywasm_types::RefType::FUNCREF), - ExternRef => WasmType::Ref(tinywasm_types::RefType::EXTERNREF), + [u8; 16] => WasmType::V128, + FuncRef => WasmType::Ref(tinywasm_types::RefType::FUNCREF.with_nullability(false)), + AnyRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Any)), + EqRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Eq)), + I31Ref => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::I31)), + StructRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Struct)), + ArrayRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Array)), + ExternRef => WasmType::Ref(tinywasm_types::RefType::EXTERNREF.with_nullability(false)), + ExnRef => WasmType::Ref(tinywasm_types::RefType::EXNREF.with_nullability(false)), ); -impl_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_scalar_wasm_traits!( + Option => WasmType::Ref(tinywasm_types::RefType::FUNCREF), + Option => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Any)), + Option => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Eq)), + Option => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::I31)), + Option => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Struct)), + Option => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Array)), + Option => WasmType::Ref(tinywasm_types::RefType::EXTERNREF), + Option => WasmType::Ref(tinywasm_types::RefType::EXNREF), +); +impl_tuple_traits!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20); impl ToWasmTypes for () { const WASM_TYPES: Option<&'static [WasmType]> = Some(&[]); diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index eb2351b..6859bbf 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -66,17 +66,20 @@ impl_conv! { /// Ok(()) /// }); /// -/// let table = Table::new( +/// let table = Table::try_new( /// &mut store, /// TableType::new(tinywasm::types::RefType::FUNCREF, 10, Some(20)), /// tinywasm::types::RefValue::Null.into(), /// )?; -/// let memory = Memory::new( +/// let memory = Memory::try_new( /// &mut store, /// MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)), /// )?; -/// let global_i32 = -/// Global::new(&mut store, GlobalType::default().with_ty(WasmType::I32), WasmValue::I32(666))?; +/// let global_i32 = Global::try_new( +/// &mut store, +/// GlobalType::default().with_ty(WasmType::I32), +/// WasmValue::I32(666), +/// )?; /// /// imports /// .define("my_module", "print_i32", print_i32) diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 6700d53..4a92212 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -3,8 +3,11 @@ use core::hint::cold_path; use tinywasm_types::*; use crate::func::{FromWasmValues, IntoWasmValues, ToWasmTypes}; +use crate::reference::StoreId; use crate::store::MemoryInstance; -use crate::{Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Tag, Trap}; +use crate::{ + Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Tag, Trap, WasmValue, +}; /// A typed view over an exported extern value. pub enum ExternItem { @@ -47,7 +50,7 @@ pub struct ModuleInstance(Rc); #[cfg_attr(feature = "debug", derive(Debug))] struct ModuleInstanceInner { - store_id: u32, + store_id: StoreId, id: ModuleInstanceId, type_addrs: Box<[TypeAddr]>, func_addrs: Box<[FuncAddr]>, @@ -121,7 +124,7 @@ impl ModuleInstance { #[inline] pub(crate) fn validate_store(&self, store: &Store) -> Result<()> { - if self.0.store_id != store.id() { + if self.0.store_id != store.store_id() { return cold!(Err(Trap::InvalidStore.into())); } Ok(()) @@ -160,9 +163,9 @@ impl ModuleInstance { /// let mut store = Store::default(); /// let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?; /// - /// assert_eq!(instance.global_get(&store, "g")?, 0.into()); + /// assert_eq!(instance.global_get(&mut store, "g")?, 0.into()); /// instance.start(&mut store)?; - /// assert_eq!(instance.global_get(&store, "g")?, 42.into()); + /// assert_eq!(instance.global_get(&mut store, "g")?, 42.into()); /// # Ok(()) /// # } /// ``` @@ -189,7 +192,7 @@ impl ModuleInstance { store.init_data(&addrs.memories, &addrs.globals, &addrs.funcs, &module.data, &type_addrs)?; let instance = ModuleInstanceInner { - store_id: store.id(), + store_id: store.store_id(), id, type_addrs, func_addrs: addrs.funcs.into_boxed_slice(), @@ -213,7 +216,7 @@ impl ModuleInstance { } /// Get a export by name - pub fn export_addr(&self, name: &str) -> Option { + pub(crate) fn export_addr(&self, name: &str) -> Option { let export = self.0.exports.iter().find(|e| *e.name == *name)?; let addr = match export.kind { ExternalKind::Func => self.0.func_addrs.get(export.index as usize)?, @@ -312,7 +315,7 @@ impl ModuleInstance { /// let ExternItem::Global(global) = instance.extern_item("answer")? else { /// panic!("expected global export"); /// }; - /// assert_eq!(global.get(&store)?, 42.into()); + /// assert_eq!(global.get(&mut store)?, 42.into()); /// # Ok(()) /// # } /// ``` @@ -346,8 +349,9 @@ impl ModuleInstance { /// # let mut store = Store::default(); /// let instance = ModuleInstance::instantiate(&mut store, &module, None)?; /// let add = instance.func_untyped(&store, "add")?; - /// let result = add.call(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)])?; - /// assert_eq!(result, vec![WasmValue::I32(42)]); + /// let mut results = [WasmValue::I32(0)]; + /// add.call(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)], &mut results)?; + /// assert_eq!(results, [WasmValue::I32(42)]); /// # Ok(()) /// # } /// ``` @@ -516,7 +520,7 @@ impl ModuleInstance { } /// Get the value of a global export by name. - pub fn global_get(&self, store: &Store, name: &str) -> Result { + pub fn global_get(&self, store: &mut Store, name: &str) -> Result { self.global(name)?.get(store) } @@ -601,9 +605,9 @@ impl ModuleInstance { /// let mut store = Store::default(); /// let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?; /// - /// assert_eq!(instance.global_get(&store, "g")?, 0.into()); + /// assert_eq!(instance.global_get(&mut store, "g")?, 0.into()); /// assert_eq!(instance.start(&mut store)?, Some(())); - /// assert_eq!(instance.global_get(&store, "g")?, 7.into()); + /// assert_eq!(instance.global_get(&mut store, "g")?, 7.into()); /// # Ok(()) /// # } /// ``` @@ -611,7 +615,7 @@ impl ModuleInstance { /// See pub fn start(&self, store: &mut Store) -> Result> { match self.start_func(store)? { - Some(func) => func.call(store, &[]).map(|_| Some(())), + Some(func) => func.call(store, &[], &mut []).map(|_| Some(())), None => Ok(None), } } diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index a50c1fa..5f218fd 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -913,58 +913,46 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.cf.instr_ptr = target_ip as usize; } - fn create_exception(&mut self, tag_index: TagAddr) -> Result { + 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 = 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 payload_len = self.store.state.get_canonical_func_type(type_addr).params().len(); + self.store.state.gc.check_allocation(payload_len, true)?; let mut payload = Vec::new(); - cold_err!(payload.try_reserve_exact(params.len())).map_err(|_| Trap::OutOfMemory)?; + cold_err!(payload.try_reserve_exact(payload_len)).map_err(|_| Trap::OutOfMemory)?; let value_stack = &mut self.store.value_stack; - for &ty in params.iter().rev() { + for index in (0..payload_len).rev() { + let ty = self.store.state.get_canonical_func_type(type_addr).params()[index]; payload.push(match ty { - WasmType::I32 | WasmType::F32 => 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)), + WasmType::I32 | WasmType::F32 => RuntimeValue::Value32(Value32::stack_pop(value_stack)), + WasmType::I64 | WasmType::F64 => RuntimeValue::Value64(Value64::stack_pop(value_stack)), + WasmType::V128 => RuntimeValue::Value128(Value128::stack_pop(value_stack)), + WasmType::Ref(_) => RuntimeValue::ValueRef(ValueRef::stack_pop(value_stack)), }); } payload.reverse(); - let exception = crate::store::ExceptionInstance { tag_addr, payload: payload.into_boxed_slice() }; - self.store.state.exceptions.push(exception); - Ok(addr) + let roots = (&self.store.value_stack.stack_32).into_iter().copied().map(ValueRef::from_raw); + self.store.state.alloc_exception(tag_addr, payload, roots) } fn exec_throw(&mut self, tag_index: TagAddr) -> Result<()> { let exception = self.create_exception(tag_index)?; - let outcome = match self.dispatch_exception(exception) { - Ok(outcome) => outcome, - Err(trap) => { - _ = self.store.state.exceptions.pop(); - return Err(trap.into()); - } - }; - match outcome { - Some(catch) if !catch.with_ref() => { - debug_assert_eq!(self.store.state.exceptions.len() - 1, exception as usize); - _ = self.store.state.exceptions.pop(); - Ok(()) - } - Some(_) => Ok(()), - None => Err(Error::Exception(ExnRef::new(exception))), - } + self.throw_exception(exception) } fn exec_throw_ref(&mut self) -> Result<()> { let exception = ValueRef::stack_pop(&mut self.store.value_stack); - let exception = exception - .addr() - .filter(|addr| self.store.state.exceptions.get(*addr as usize).is_some()) - .ok_or(Trap::NullReference)?; - match self.dispatch_exception(exception)? { - Some(_) => Ok(()), - None => Err(Error::Exception(ExnRef::new(exception))), + if exception.is_null() { + return Err(Trap::NullReference.into()); + } + self.throw_exception(exception) + } + + fn throw_exception(&mut self, exception: ValueRef) -> Result<()> { + match self.dispatch_exception(exception) { + Ok(Some(_)) => Ok(()), + Ok(None) => self.store.root_exception(exception).and_then(|exception| Err(Error::Exception(exception))), + Err(trap) => Err(trap.into()), } } @@ -995,8 +983,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn dispatch_exception(&mut self, exception_addr: ExnAddr) -> Result, Trap> { - let tag_addr = self.store.state.exceptions[exception_addr as usize].tag_addr; + fn dispatch_exception(&mut self, exception: ValueRef) -> Result, Trap> { + let object = self.store.state.gc.get(exception).ok_or(Trap::InvalidReference)?; + let crate::store::GcObjectKind::Exception(tag_addr) = object.kind else { + return Err(Trap::InvalidReference); + }; let mut protected_ip = self.cf.instr_ptr; loop { if let Some(catch) = self.matching_catch(protected_ip, tag_addr) { @@ -1013,12 +1004,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.value_stack.truncate_to_base(target); if include_payload { let Store { state, value_stack, .. } = self.store; - for value in state.exceptions[exception_addr as usize].payload.iter().copied() { + let object = state.gc.get(exception).ok_or(Trap::InvalidReference)?; + for value in object.values.iter().copied() { value_stack.push_dyn(value)?; } } if with_ref { - self.store.value_stack.push(ValueRef::from_category_addr(exception_addr))?; + self.store.value_stack.push(exception)?; } self.cf.instr_ptr = landing_pad as usize; return Ok(Some(catch)); @@ -1078,12 +1070,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_call_host( - &mut self, - host_func: HostFunction, - type_addr: TypeAddr, - params_may_gc: bool, - ) -> Result { + fn exec_call_host(&mut self, host_func: HostFunction, type_addr: TypeAddr) -> Result { if let Some(host_func) = host_func.typed_callback() { cold_err!(host_func.call_stack(self.store, self.module.id(), type_addr)) .map_err(|error| Trap::HostFunction(Box::new(error)))?; @@ -1094,23 +1081,28 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return Ok(false); } - let param_types = self.store.state.get_canonical_func_type(type_addr).params(); - 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)); - } - params.reverse(); - if params_may_gc { - self.store.state.pin_host_values(¶ms); - } - 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_wasmvalues(res.iter().copied())?; + let (param_count, result_count, base) = { + let ty = self.store.state.get_canonical_func_type(type_addr); + (ty.params().len(), ty.results().len(), self.store.value_stack.base_before(ty.params().iter().collect())) + }; + let module_id = self.module.id(); + self.store + .with_scratch_values(param_count + result_count, |store, values| { + let host_values = store.stack_value_iter(type_addr, crate::store::FuncValueTypes::Params, base)?; + for (slot, value) in values[..param_count].iter_mut().zip(host_values) { + *slot = value; + } + store.value_stack.truncate_to_base(base); + let (params, results) = values.split_at_mut(param_count); + host_func + .call_values(store, module_id, type_addr, params, results) + .map_err(|error| Error::Trap(Trap::HostFunction(Box::new(error))))?; + store.push_wasm_values(results.iter().cloned()) + }) + .map_err(|error| match error { + Error::Trap(trap) => trap, + other => Trap::HostFunction(Box::new(other)), + })?; if TAIL { Ok(self.exec_return()) } else { @@ -1128,7 +1120,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.exec_call(wasm_func.func.clone(), wasm_func.owner, addr) } crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params)?; + self.exec_call_host::(host_func.clone(), func.type_addr)?; Ok(()) } } @@ -1144,7 +1136,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(false) } crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params) + self.exec_call_host::(host_func.clone(), func.type_addr) } } } @@ -1174,7 +1166,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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 let table_addr = self.module.resolve_table_addr(table_addr); let table_idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; @@ -1209,7 +1200,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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.clone(), func.type_addr, func.gc.params); + return self.exec_call_host::(host_func.clone(), func.type_addr); } }?; Ok(false) @@ -1438,22 +1429,34 @@ 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(); + 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) } 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 field_count = + self.store.state.get_type(type_addr).as_struct().expect("validated struct.new type").fields.len(); + self.store.state.check_gc_allocation(type_addr, field_count)?; let mut values = Vec::new(); - cold_err!(values.try_reserve_exact(fields.len())).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(field_count)).map_err(|_| Trap::OutOfMemory)?; if default { - values.extend(fields.iter().map(|field| default_value(field.storage))); + values.extend( + self.store + .state + .get_type(type_addr) + .as_struct() + .expect("validated struct.new type") + .fields + .iter() + .map(|field| default_value(field.storage)), + ); } else { - for field in fields.iter().rev() { - values.push(pop_value(&mut self.store.value_stack, field.storage)); + for index in (0..field_count).rev() { + let storage = self.store.state.get_type(type_addr).as_struct().unwrap().fields[index].storage; + values.push(pop_value(&mut self.store.value_stack, storage)); } values.reverse(); } @@ -1468,6 +1471,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { [field_index as usize] .storage; let object = self.store.state.gc_object(reference, type_addr)?; + let object = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; let value = *object.values.get(field_index as usize).expect("validated struct field index"); push_value(&mut self.store.value_stack, value, storage, signed) } @@ -1480,8 +1484,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { .storage; let value = pop_value(&mut self.store.value_stack, storage); let reference = ValueRef::stack_pop(&mut self.store.value_stack); - self.store.state.gc_object(reference, type_addr)?; - self.store.state.gc.set(reference, field_index as usize, value).expect("live struct field"); + let object = self.store.state.gc_object(reference, type_addr)?; + self.store.state.gc.set(object, field_index as usize, value).expect("live struct field"); Ok(()) } @@ -1489,6 +1493,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new type").field.storage; let len = u32::stack_pop(&mut self.store.value_stack) as usize; + self.store.state.check_gc_allocation(type_addr, len)?; let value = if default { default_value(storage) } else { pop_value(&mut self.store.value_stack, storage) }; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; @@ -1502,6 +1507,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; let len = len as usize; + self.store.state.check_gc_allocation(type_addr, len)?; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; for _ in 0..len { @@ -1517,6 +1523,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.get type").field.storage; let object = self.store.state.gc_object(reference, type_addr)?; + let object = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; let value = *object.values.get(index).ok_or(Trap::ArrayOutOfBounds)?; push_value(&mut self.store.value_stack, value, storage, signed) } @@ -1527,8 +1534,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); - self.store.state.gc_object(reference, type_addr)?; - self.store.state.gc.set(reference, index, value).ok_or(Trap::ArrayOutOfBounds) + let object = self.store.state.gc_object(reference, type_addr)?; + self.store.state.gc.set(object, index, value).ok_or(Trap::ArrayOutOfBounds) } fn exec_array_len(&mut self) -> Result<(), Trap> { @@ -1537,7 +1544,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return Err(Trap::NullArrayReference); } let object = self.store.state.gc.get(reference).ok_or(Trap::Other("invalid GC reference"))?; - if self.store.state.get_type(object.type_addr).as_array().is_none() { + let crate::store::GcObjectKind::Composite(type_addr) = object.kind else { + return Err(Trap::Other("GC reference is not an array")); + }; + if self.store.state.get_type(type_addr).as_array().is_none() { return Err(Trap::Other("GC reference is not an array")); } self.store.value_stack.push(object.values.len() as i32) @@ -1551,8 +1561,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let index = u32::stack_pop(&mut self.store.value_stack) as usize; let reference = ValueRef::stack_pop(&mut self.store.value_stack); let object = self.store.state.gc_object(reference, type_addr)?; - let end = index.checked_add(len).filter(|end| *end <= object.values.len()).ok_or(Trap::ArrayOutOfBounds)?; - self.store.state.gc.fill(reference, index..end, value).expect("live array range"); + let object_ref = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; + let end = index.checked_add(len).filter(|end| *end <= object_ref.values.len()).ok_or(Trap::ArrayOutOfBounds)?; + self.store.state.gc.fill(object, index..end, value).expect("live array range"); Ok(()) } @@ -1565,16 +1576,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let dst = ValueRef::stack_pop(&mut self.store.value_stack); let dst_type = self.module.resolve_type_addr(dst_type); let src_type = self.module.resolve_type_addr(src_type); - let dst_len = self.store.state.gc_object(dst, dst_type)?.values.len(); - let src_object = self.store.state.gc_object(src, src_type)?; + let dst_handle = self.store.state.gc_object(dst, dst_type)?; + let dst_len = self.store.state.gc.get_handle(dst_handle).expect("validated array").values.len(); + let src_handle = self.store.state.gc_object(src, src_type)?; + let src_object = self.store.state.gc.get_handle(src_handle).expect("validated array"); let src_end = src_index.checked_add(len).filter(|end| *end <= src_object.values.len()).ok_or(Trap::ArrayOutOfBounds)?; dst_index.checked_add(len).filter(|end| *end <= dst_len).ok_or(Trap::ArrayOutOfBounds)?; - if src == dst { - self.store.state.gc.copy_within(dst, src_index..src_end, dst_index).expect("live array range"); + if src_handle == dst_handle { + self.store.state.gc.copy_within(dst_handle, src_index..src_end, dst_index).expect("live array range"); return Ok(()); } - self.store.state.gc.copy_between(src, src_index..src_end, dst, dst_index).expect("live array ranges"); + self.store + .state + .gc + .copy_between(src_handle, src_index..src_end, dst_handle, dst_index) + .expect("live array ranges"); Ok(()) } @@ -1586,6 +1603,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage; let data_addr = self.module.resolve_data_addr(data_index); let data = self.store.state.data[data_addr as usize].data.as_deref().unwrap_or(&[]); + data_range(storage, data, src, len)?; + self.store.state.check_gc_allocation(type_addr, len)?; let values = decode_data(storage, data, src, len)?; self.push_gc_object(type_addr, values) } @@ -1594,12 +1613,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { 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 type_addr = self.module.resolve_type_addr(type_index); let elem_addr = self.module.resolve_elem_addr(elem_index); let items = self.store.state.elements[elem_addr as usize].items_range(src, len)?; + self.store.state.check_gc_allocation(type_addr, len)?; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; - values.extend(items.iter().copied().map(TinyWasmValue::ValueRef)); - let type_addr = self.module.resolve_type_addr(type_index); + values.extend(items.iter().copied().map(RuntimeValue::ValueRef)); self.push_gc_object(type_addr, values) } @@ -1611,12 +1631,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let reference = ValueRef::stack_pop(&mut self.store.value_stack); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage; - let object_len = self.store.state.gc_object(reference, type_addr)?.values.len(); + let object = self.store.state.gc_object(reference, type_addr)?; + let object_len = self.store.state.gc.get_handle(object).expect("validated array").values.len(); dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; let data = self.store.state.data[self.module.resolve_data_addr(data_index) as usize].data.as_deref().unwrap_or(&[]); let values = decode_data(storage, data, src, len)?; - self.store.state.gc.set_slice(reference, dst, &values).expect("live array range"); + self.store.state.gc.set_slice(object, dst, &values).expect("live array range"); Ok(()) } @@ -1627,14 +1648,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let dst = u32::stack_pop(&mut self.store.value_stack) as usize; let reference = ValueRef::stack_pop(&mut self.store.value_stack); let type_addr = self.module.resolve_type_addr(type_index); - let object_len = self.store.state.gc_object(reference, type_addr)?.values.len(); + let object = self.store.state.gc_object(reference, type_addr)?; + let object_len = self.store.state.gc.get_handle(object).expect("validated array").values.len(); dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; let items = self.store.state.elements[self.module.resolve_elem_addr(elem_index) as usize].items_range(src, len)?; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; - values.extend(items.iter().copied().map(TinyWasmValue::ValueRef)); - self.store.state.gc.set_slice(reference, dst, &values).expect("live array range"); + values.extend(items.iter().copied().map(RuntimeValue::ValueRef)); + self.store.state.gc.set_slice(object, dst, &values).expect("live array range"); Ok(()) } diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 62a9480..e123a41 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -1,6 +1,6 @@ -use alloc::{vec, vec::Vec}; +use alloc::vec::Vec; use core::hint::cold_path; -use tinywasm_types::{MemoryArch, ValueCounts, WasmType, WasmValue}; +use tinywasm_types::{MemoryArch, ValueCounts}; use super::StackBase; use crate::engine::{Config, StackConfig}; @@ -18,66 +18,6 @@ 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, @@ -281,11 +221,6 @@ impl ValueStack { } } - #[inline(always)] - pub(crate) fn len(&self) -> usize { - self.stack_32.len() + self.stack_64.len() + self.stack_128.len() - } - #[inline(always)] pub(crate) fn push(&mut self, value: T) -> Result<(), Trap> { T::stack_push(self, value) @@ -325,19 +260,6 @@ 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_wasmvalues(values.iter().copied()).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); @@ -352,57 +274,12 @@ impl ValueStack { self.stack_128.truncate_to(base.s128 as usize); } - pub(crate) fn push_dyn(&mut self, value: TinyWasmValue) -> Result<(), Trap> { + pub(crate) fn push_dyn(&mut self, value: RuntimeValue) -> Result<(), Trap> { match value { - TinyWasmValue::Value32(v) => self.stack_32.push(v), - TinyWasmValue::Value64(v) => self.stack_64.push(v), - TinyWasmValue::Value128(v) => self.stack_128.push(v), - TinyWasmValue::ValueRef(v) => self.stack_32.push(v.raw()), - } - } - - pub(crate) fn pop_wasmvalue(&mut self, state: &crate::store::State, val_type: WasmType) -> WasmValue { - match val_type { - WasmType::I32 => WasmValue::I32(self.stack_32.pop() as i32), - WasmType::I64 => WasmValue::I64(self.stack_64.pop() as i64), - WasmType::F32 => WasmValue::F32(f32::from_bits(self.stack_32.pop())), - WasmType::F64 => WasmValue::F64(f64::from_bits(self.stack_64.pop())), - WasmType::Ref(ty) => WasmValue::Ref(state.to_ref_value(ValueRef::from_raw(self.stack_32.pop()), ty)), - WasmType::V128 => WasmValue::V128(self.stack_128.pop().0), - } - } - - /// 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); + 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()), } - 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_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::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(ValueRef::from(v).raw())?, - WasmValue::V128(v) => self.stack_128.push(Value128(v))?, - } - } - Ok(()) } } diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index 2e0793b..22f20b7 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -1,7 +1,7 @@ use super::stack::{CallFrame, ValueStack}; use crate::store::Globals; -use crate::{Result, interpreter::simd::Value128}; -use tinywasm_types::{GlobalAddr, LocalAddr, RefValue, WasmValue}; +use crate::{Error, Result, Store, WasmValue, interpreter::simd::Value128}; +use tinywasm_types::{GlobalAddr, LocalAddr, WasmType}; pub(crate) type Value32 = u32; pub(crate) type Value64 = u64; @@ -34,6 +34,14 @@ impl ValueRef { Self(((value as u32) << 1) | 1) } + #[inline] + pub(crate) const fn try_from_host_any(addr: u32) -> Option { + if addr >= Self::HOST_ANY_TAG - 1 { + return None; + } + Some(Self::from_category_addr(addr | Self::HOST_ANY_TAG)) + } + pub(crate) const fn is_host_any(self) -> bool { matches!(self.addr(), Some(addr) if addr & Self::HOST_ANY_TAG != 0) } @@ -69,21 +77,9 @@ impl ValueRef { } } -impl From for ValueRef { - fn from(value: RefValue) -> Self { - match value { - RefValue::Null => Self::NULL, - RefValue::Func(value) => Self::from_category_addr(value.addr()), - RefValue::Extern(value) => Self::from_raw(value.raw()), - RefValue::Exn(value) => Self::from_category_addr(value.addr()), - RefValue::Any(value) => Self::from_raw(value.raw()), - } - } -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// An untyped internal WebAssembly value. -pub(crate) enum TinyWasmValue { +pub(crate) enum RuntimeValue { /// A 32-bit value. Value32(Value32), /// A 64-bit value. @@ -94,16 +90,17 @@ pub(crate) enum TinyWasmValue { ValueRef(ValueRef), } -impl From for TinyWasmValue { - fn from(value: WasmValue) -> Self { - match value { - WasmValue::I32(v) => Self::Value32(v as u32), - WasmValue::I64(v) => Self::Value64(v as u64), - WasmValue::F32(v) => Self::Value32(v.to_bits()), - WasmValue::F64(v) => Self::Value64(v.to_bits()), - WasmValue::Ref(value) => Self::ValueRef(value.into()), - WasmValue::V128(v) => Self::Value128(Value128(v)), - } +impl RuntimeValue { + pub(crate) fn into_wasm(self, store: &mut Store, ty: WasmType) -> Result { + Ok(match (self, ty) { + (Self::Value32(value), WasmType::I32) => WasmValue::I32(value as i32), + (Self::Value32(value), WasmType::F32) => WasmValue::F32(f32::from_bits(value)), + (Self::Value64(value), WasmType::I64) => WasmValue::I64(value as i64), + (Self::Value64(value), WasmType::F64) => WasmValue::F64(f64::from_bits(value)), + (Self::Value128(value), WasmType::V128) => WasmValue::V128(value.0), + (Self::ValueRef(value), WasmType::Ref(ty)) => WasmValue::Ref(store.decode_ref(value, ty)?), + _ => return Err(Error::other("internal value does not match its WebAssembly type")), + }) } } @@ -234,3 +231,13 @@ impl_internalvalue! { stack_32, s32, get_32, set_32, ValueRef, |v| v.raw(), |v| ValueRef(v) stack_128, s128, get_128, set_128, Value128, |v| v, |v| v } + +#[cfg(test)] +mod tests { + use super::ValueRef; + + #[test] + fn value_ref_remains_four_bytes() { + assert_eq!(core::mem::size_of::(), 4); + } +} diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index bd80ef1..15ccd0e 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -18,47 +18,48 @@ //! //! ## Getting started //! -//! The easiest way to get started is to use the `parse_bytes` function to load a -//! WebAssembly module from bytes. This will parse the module and validate it, returning -//! a [`Module`] that can be used to instantiate the module. +//! Use [`parse_bytes`] to parse and validate a WebAssembly module, then instantiate it +//! in a [`Store`]. A module can be reused, while each store owns its runtime state. //! //! ```rust //! # #[cfg(feature = "parser")] //! # fn main() -> tinywasm::Result<()> { //! use tinywasm::{ModuleInstance, Store}; //! -//! // Load a module from bytes //! let wasm = include_bytes!("../../../examples/wasm/add.wasm"); //! let module = tinywasm::parse_bytes(wasm)?; //! -//! // # Create a new store -//! // Stores are used to allocate objects like functions and globals //! let mut store = Store::default(); -//! -//! // # Instantiate the module -//! // This will allocate the module and its globals into the store -//! // and execute the module's start function. //! let instance = ModuleInstance::instantiate(&mut store, &module, None)?; //! -//! // # Get a typed handle to the exported "add" function -//! // Alternatively, you can use `instance.func_untyped` to get an untyped handle -//! // that takes and returns [`types::WasmValue`]s -//! let func = instance.func::<(i32, i32), i32>(&store, "add")?; -//! let res = func.call(&mut store, (1, 2))?; +//! let add = instance.func::<(i32, i32), i32>(&store, "add")?; +//! let result = add.call(&mut store, (1, 2))?; //! -//! assert_eq!(res, 3); +//! assert_eq!(result, 3); //! # Ok(()) //! # } //! # #[cfg(not(feature = "parser"))] //! # fn main() {} //! ``` //! -//! For non-default runtime behavior, construct a [`Store`] with a custom [`Engine`] -//! and [`engine::Config`] to control stack sizing 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. +//! Typed functions convert Rust values directly. Use [`ModuleInstance::func_untyped`] +//! and [`WasmValue`] when types are selected at runtime. References such as [`StructRef`] +//! and [`ExternRef`] are owned handles tied to their store. Cloning a managed reference +//! keeps its referent live. +//! +//! Construct a store with a custom [`Engine`] and [`engine::Config`] to configure +//! stack limits, fuel, and GC collection. A [`ResourceLimiter`] can bound guest memory, +//! table, and GC heap growth. +//! +//! ## References and GC +//! +//! Runtime references belong to a [`Store`]. Passing a reference to another store +//! returns [`Trap::InvalidStore`]. Managed references are cloneable owned handles, and +//! their referents become collectible after the last handle is dropped. Nullable typed +//! parameters and results use `Option`. Use [`RefValue`] for dynamic reference values +//! and [`Store::gc`] to request collection explicitly. //! -//! For more examples, see the [`examples`](https://github.com/explodingcamera/tinywasm/tree/main/examples) directory. +//! For more examples, see the [`examples`](https://github.com/explodingcamera/tinywasm/tree/next/examples) directory. //! //! ## Cargo features //! @@ -67,7 +68,7 @@ //! - **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default. //! - **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through `ParserOptions`. //! - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default. -//! - **`canonicalize-nans`:** Canonicalizes NaN values. Enabled by default. +//! - **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results. Enabled by default. //! - **`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`). @@ -108,8 +109,6 @@ pub(crate) mod log { mod error; pub use error::*; -#[allow(deprecated)] -pub use func::WasmTupleChain; pub use func::{ ExecProgress, FromWasmValues, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped, HostFunction, IntoWasmValues, ToWasmType, ToWasmTypes, @@ -145,6 +144,7 @@ pub use parser::{parse_file, parse_stream}; /// Re-export of [`tinywasm_types`]. pub mod types { + pub use crate::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, RefValue, StructRef, WasmValue}; pub use tinywasm_types::*; } diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs deleted file mode 100644 index 271e71c..0000000 --- a/crates/tinywasm/src/reference.rs +++ /dev/null @@ -1,513 +0,0 @@ -use core::hint::cold_path; - -use alloc::ffi::CString; -use alloc::format; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; - -use crate::interpreter::ValueRef; -use crate::store::TableInstance; -use crate::{Error, MemoryInstance, Result, Store, Trap}; -use tinywasm_types::{ - Addr, FuncType, GlobalType, MemAddr, MemoryType, TableAddr, TableType, TagAddr, WasmType, WasmValue, -}; - -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct StoreItem { - pub(crate) store_id: u32, - pub(crate) addr: Addr, -} - -impl StoreItem { - #[inline] - /// 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 } - } - - #[inline] - pub(crate) fn validate_store(&self, store: &Store) -> Result<(), Trap> { - if self.store_id != store.id() { - return Err(Trap::InvalidStore); - } - Ok(()) - } -} - -/// A memory instance in a store. -/// -/// ## Example -/// ```rust -/// # fn main() -> tinywasm::Result<()> { -/// use tinywasm::types::MemoryType; -/// use tinywasm::{Memory, Store}; -/// -/// let mut store = Store::default(); -/// let memory = Memory::new(&mut store, MemoryType::default().with_page_count_initial(1))?; -/// -/// memory.copy_from_slice(&mut store, 0, b"hi")?; -/// assert_eq!(memory.read_vec(&store, 0, 2)?, b"hi"); -/// assert_eq!(memory.page_count(&store)?, 1); -/// memory.grow(&mut store, 1)?; -/// assert_eq!(memory.page_count(&store)?, 2); -/// # Ok(()) -/// # } -/// ``` -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct Memory(pub(crate) StoreItem); - -/// A table instance in a store. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct Table(pub(crate) StoreItem); - -/// A global instance in a store. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct Global(pub(crate) StoreItem); - -/// A tag instance in a store. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct Tag(pub(crate) StoreItem); - -/// A cursor over a [`Memory`] instance. -/// -/// Available with the `std` feature enabled. -#[cfg(feature = "std")] -pub struct MemoryCursor<'a> { - memory: &'a mut MemoryInstance, - position: u64, -} - -#[cfg(feature = "std")] -impl 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") - }) - } - - fn advance(&mut self, amount: usize) -> crate::std::io::Result<()> { - self.position = self.position.checked_add(amount as u64).ok_or_else(|| { - crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position overflow") - })?; - Ok(()) - } - - /// Returns the current cursor position. - pub const fn position(&self) -> u64 { - self.position - } - - /// Sets the current cursor position. - pub fn set_position(&mut self, position: u64) { - self.position = position; - } -} - -#[cfg(feature = "std")] -impl crate::std::io::Read for MemoryCursor<'_> { - fn read(&mut self, buf: &mut [u8]) -> crate::std::io::Result { - let offset = self.offset()?; - let read = self.memory.inner.read(offset, buf); - self.advance(read)?; - Ok(read) - } -} - -#[cfg(feature = "std")] -impl crate::std::io::Write for MemoryCursor<'_> { - fn write(&mut self, buf: &[u8]) -> crate::std::io::Result { - let offset = self.offset()?; - let written = self.memory.inner.write(offset, buf); - self.advance(written)?; - Ok(written) - } - - fn flush(&mut self) -> crate::std::io::Result<()> { - Ok(()) - } -} - -#[cfg(feature = "std")] -impl crate::std::io::Seek for MemoryCursor<'_> { - fn seek(&mut self, pos: crate::std::io::SeekFrom) -> crate::std::io::Result { - let len = self.memory.inner.len() as i128; - let current = i128::from(self.position); - - let next = match pos { - crate::std::io::SeekFrom::Start(offset) => i128::from(offset), - crate::std::io::SeekFrom::End(offset) => len + i128::from(offset), - crate::std::io::SeekFrom::Current(offset) => current + i128::from(offset), - }; - - if next < 0 { - return Err(crate::std::io::Error::new( - crate::std::io::ErrorKind::InvalidInput, - "invalid seek before start", - )); - } - - let next = u64::try_from(next).map_err(|_| { - crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "invalid seek position") - })?; - self.position = next; - Ok(next) - } -} - -impl Memory { - /// Create a new memory in the given store. - pub fn new(store: &mut Store, ty: MemoryType) -> Result { - let addr = store.state.memories.len() as MemAddr; - let limiter = store.engine.config().resource_limiter.clone(); - store.state.memories.push(MemoryInstance::new(ty, limiter.as_deref())?); - Ok(Self(StoreItem::new(store.id(), addr))) - } - - /// Creates a cursor positioned at the start of this memory. - /// - /// Available with the `std` feature enabled. - /// - /// ## Example - /// - /// ```rust - /// # fn main() -> Result<(), Box> { - /// use std::io::{Read, Seek, SeekFrom, Write}; - /// use tinywasm::types::MemoryType; - /// use tinywasm::{Memory, Store}; - /// - /// let mut store = Store::default(); - /// let memory = Memory::new(&mut store, MemoryType::default().with_page_count_initial(1))?; - /// let mut cursor = memory.cursor(&mut store)?; - /// - /// cursor.seek(SeekFrom::Start(2))?; - /// cursor.write_all(b"abc")?; - /// cursor.seek(SeekFrom::Start(0))?; - /// - /// let mut bytes = [0; 5]; - /// cursor.read_exact(&mut bytes)?; - /// assert_eq!(bytes, [0, 0, b'a', b'b', b'c']); - /// # Ok(()) - /// # } - /// ``` - #[cfg(feature = "std")] - pub fn cursor<'a>(&self, store: &'a mut Store) -> Result> { - self.cursor_at(store, 0) - } - - /// Creates a cursor positioned at `position` bytes from the start of this memory. - /// - /// Available with the `std` feature enabled. - #[cfg(feature = "std")] - pub fn cursor_at<'a>(&self, store: &'a mut Store, position: u64) -> Result> { - Ok(MemoryCursor { memory: self.instance_mut(store)?, position }) - } - - #[inline] - fn instance<'a>(&self, store: &'a Store) -> Result<&'a MemoryInstance> { - self.0.validate_store(store)?; - Ok(store.state.get_mem(self.0.addr)) - } - - #[inline] - fn instance_mut<'a>(&self, store: &'a mut Store) -> Result<&'a mut MemoryInstance> { - self.0.validate_store(store)?; - Ok(store.state.get_mem_mut(self.0.addr)) - } - - /// Returns the raw memory byte length. - pub fn len(&self, store: &Store) -> Result { - Ok(self.instance(store)?.inner.len()) - } - - /// Returns the memory type, including page size and limits. - pub fn ty(&self, store: &Store) -> Result { - Ok(self.instance(store)?.kind) - } - - /// Reads up to `dst.len()` bytes from memory and returns the number of bytes read. - /// - /// This returns fewer bytes than requested when the range extends past the end of memory. Use - /// [`Self::read_exact`] or [`Self::read_vec`] when you need a full range. - pub fn read(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result { - Ok(self.instance(store)?.inner.read(offset, dst)) - } - - /// Writes up to `src.len()` bytes into memory and returns the number of bytes written. - /// - /// This returns fewer bytes than requested when the range extends past the end of memory. Use - /// [`Self::copy_from_slice`] when you need the full slice written. - pub fn write(&self, store: &mut Store, offset: usize, src: &[u8]) -> Result { - Ok(self.instance_mut(store)?.inner.write(offset, src)) - } - - /// Reads exactly `dst.len()` bytes from memory. - pub fn read_exact(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result<()> { - self.instance(store)?.inner.read_exact(offset, dst).ok_or_else(|| { - Error::Trap(crate::Trap::MemoryOutOfBounds { - offset, - len: dst.len(), - max: self.instance(store).unwrap().inner.len(), - }) - }) - } - - /// Reads `len` bytes from memory into a newly allocated buffer. - pub fn read_vec(&self, store: &Store, offset: usize, len: usize) -> Result> { - self.instance(store)?.inner.read_vec(offset, len).ok_or_else(|| { - Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() }) - }) - } - - /// Grows the memory by the given number of pages. - /// - /// Returns the previous size, or `None` if growth fails or is rejected by the resource limiter. - /// A limiter-provided trap is returned as an error. - pub fn grow(&self, store: &mut Store, delta_pages: i64) -> Result> { - let limiter = store.engine.config().resource_limiter.clone(); - let mem = self.instance_mut(store)?; - mem.grow(delta_pages, limiter.as_deref()).map_err(Into::into) - } - - /// Get the current size of the memory in pages. - pub fn page_count(&self, store: &Store) -> Result { - Ok(self.instance(store)?.page_count) - } - - /// Copy a slice of memory to another place in memory. - pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<()> { - self.instance_mut(store)?.copy_within(dst, src, len)?; - Ok(()) - } - - /// Fill a slice of memory with a value. - pub fn fill(&self, store: &mut Store, offset: usize, len: usize, val: u8) -> Result<()> { - self.instance_mut(store)?.inner.fill(offset, len, val).ok_or_else(|| { - Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() }) - }) - } - - /// Copies a full slice into memory. - pub fn copy_from_slice(&self, store: &mut Store, offset: usize, data: &[u8]) -> Result<()> { - self.instance_mut(store)?.inner.write_all(offset, data).ok_or_else(|| { - Error::Trap(crate::Trap::MemoryOutOfBounds { - offset, - len: data.len(), - max: self.instance(store).unwrap().inner.len(), - }) - }) - } - - /// Copies a nul-terminated C string into memory. - pub fn write_cstring(&self, store: &mut Store, offset: usize, string: &CString) -> Result<()> { - self.copy_from_slice(store, offset, string.as_bytes_with_nul()) - } - - /// Copies a UTF-8 string into memory and appends a trailing nul byte. - pub fn write_cstring_bytes(&self, store: &mut Store, offset: usize, string: &str) -> Result<()> { - let mut bytes = Vec::with_capacity(string.len() + 1); - bytes.extend_from_slice(string.as_bytes()); - bytes.push(0); - self.copy_from_slice(store, offset, &bytes) - } - - /// Reads a C-style string from memory. - pub fn read_cstring(&self, store: &Store, offset: usize, len: usize) -> Result { - CString::from_vec_with_nul(self.read_vec(store, offset, len)?) - .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}"))) - } - - /// Reads a C-style string from memory, stopping at the first null byte. - pub fn read_cstring_until_null(&self, store: &Store, offset: usize, max_len: usize) -> Result { - let bytes = self.read_vec(store, offset, max_len)?; - let Some(null) = bytes.iter().position(|byte| *byte == 0) else { - return Err(crate::Error::Other("Invalid C-style string: missing null terminator".to_string())); - }; - - CString::from_vec_with_nul(bytes[..=null].to_vec()) - .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}"))) - } - - /// Reads a UTF-8 string from memory. - pub fn read_string(&self, store: &Store, offset: usize, len: usize) -> Result { - String::from_utf8(self.read_vec(store, offset, len)?) - .map_err(|e| crate::Error::Other(format!("Invalid UTF-8 string: {e}"))) - } - - /// Reads a JavaScript-style utf-16 string from memory. - pub fn read_js_string(&self, store: &Store, offset: usize, len: usize) -> Result { - let bytes = self.read_vec(store, offset, len)?; - let mut string = String::new(); - for i in 0..(len / 2) { - let c = u16::from_le_bytes([bytes[i * 2], bytes[i * 2 + 1]]); - string.push( - char::from_u32(u32::from(c)).ok_or_else(|| crate::Error::Other("Invalid UTF-16 string".to_string()))?, - ); - } - Ok(string) - } -} - -fn table_value_to_element( - state: &crate::store::State, - element_type: tinywasm_types::RefType, - value: WasmValue, -) -> Result { - let WasmValue::Ref(value) = value else { - return Err(Trap::Other("invalid table value type")); - }; - if !state.value_matches_type(WasmValue::Ref(value), WasmType::Ref(element_type)) { - return Err(Trap::Other("invalid table value type")); - } - Ok(value.into()) -} - -impl Table { - /// Create a new table in the given store. - pub fn new(store: &mut Store, ty: TableType, init: WasmValue) -> Result { - if ty.element_type.is_concrete() { - return Err(Error::other("host tables cannot use module-relative concrete reference types")); - } - let init = table_value_to_element(&store.state, ty.element_type, init).map_err(Error::from)?; - let limiter = store.engine.config().resource_limiter.clone(); - let addr = store.state.tables.len() as TableAddr; - store.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); - Ok(Self(StoreItem::new(store.id(), addr))) - } - - #[inline] - fn instance<'a>(&self, store: &'a Store) -> Result<&'a TableInstance> { - self.0.validate_store(store)?; - Ok(store.state.get_table(self.0.addr)) - } - - /// Get the type of the table. - pub fn ty(&self, store: &Store) -> Result { - Ok(self.instance(store)?.kind) - } - - /// Get the current number of elements in the table. - pub fn size(&self, store: &Store) -> Result { - Ok(self.instance(store)?.size()) - } - - /// Get a table element as a wasm reference value. - pub fn get(&self, store: &Store, index: TableAddr) -> Result { - let table = self.instance(store)?; - let value = store.state.to_ref_value(*table.get(index as usize)?, table.kind.element_type); - store.state.pin_host_ref(value); - Ok(WasmValue::Ref(value)) - } - - /// Load a range of table elements and iterate over wasm reference values. - pub fn load<'a>( - &self, - store: &'a Store, - offset: usize, - len: usize, - ) -> Result + 'a> { - let table = self.instance(store)?; - let element_type = table.kind.element_type; - let elements = table.load(offset, len)?; - let may_contain_gc = store.state.type_may_contain_gc(&WasmType::Ref(element_type)); - Ok(elements.iter().copied().map(move |value| { - if may_contain_gc { - store.state.gc.pin(value); - } - WasmValue::Ref(store.state.to_ref_value(value, element_type)) - })) - } - - /// Set a table element. - pub fn set(&self, store: &mut Store, index: TableAddr, value: WasmValue) -> Result<(), Trap> { - self.0.validate_store(store)?; - let element_type = store.state.get_table(self.0.addr).kind.element_type; - let value = table_value_to_element(&store.state, element_type, value)?; - store.state.get_table_mut(self.0.addr).set(index as usize, value) - } - - /// Copy elements within the same table. - pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<(), Trap> { - self.0.validate_store(store)?; - store.state.get_table_mut(self.0.addr).copy_within(dst, src, len) - } - - /// Grows the table and returns the previous size. - /// - /// Returns `None` if growth fails or is rejected by the resource limiter. A limiter-provided - /// trap is returned as an error. - pub fn grow(&self, store: &mut Store, delta: i32, init: WasmValue) -> Result> { - 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 Ok(delta) = usize::try_from(delta) else { - return Ok(None); - }; - let limiter = store.engine.config().resource_limiter.clone(); - match store.state.get_table_mut(self.0.addr).grow(delta, init, limiter.as_deref())? { - true => Ok(Some(old_size)), - false => Ok(None), - } - } -} - -impl Global { - /// Create a new global in the given store. - pub fn new(store: &mut Store, ty: GlobalType, value: WasmValue) -> Result { - if matches!(ty.ty, WasmType::Ref(ty) if ty.is_concrete()) { - return Err(Error::other("host globals cannot use module-relative concrete reference types")); - } - if !store.state.value_matches_type(value, ty.ty) { - cold_path(); - return Err(Error::Other("invalid global value type".to_string())); - } - let addr = store.state.globals.push(ty, value.into()); - Ok(Self(StoreItem::new(store.id(), addr))) - } - - /// Get the type of the global. - pub fn ty(&self, store: &Store) -> Result { - self.0.validate_store(store)?; - Ok(store.state.globals.ty(self.0.addr)) - } - - /// Get the current value of the global. - pub fn get(&self, store: &Store) -> Result { - self.0.validate_store(store)?; - let value = store.state.get_global_wasmvalue(self.0.addr); - if let WasmValue::Ref(value) = value { - store.state.pin_host_ref(value); - } - Ok(value) - } - - /// Set the current value of the global. - pub fn set(&self, store: &mut Store, value: WasmValue) -> Result<()> { - self.0.validate_store(store)?; - store.state.set_global_wasmvalue(self.0.addr, value) - } -} - -impl Tag { - /// Create a new exception tag in the given store. - pub fn new(store: &mut Store, ty: FuncType) -> Result { - if !ty.results().is_empty() { - return Err(Error::other("tag types must not have results")); - } - let type_addr = store.register_host_type(&ty); - let addr = store.state.tags.len() as TagAddr; - store.state.tags.push(crate::store::TagInstance { type_addr }); - Ok(Self(StoreItem::new(store.id(), addr))) - } - - /// Get the payload type of the tag. - pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> { - self.0.validate_store(store)?; - Ok(store.state.get_canonical_func_type(store.state.get_tag(self.0.addr).type_addr)) - } -} diff --git a/crates/tinywasm/src/reference/managed.rs b/crates/tinywasm/src/reference/managed.rs new file mode 100644 index 0000000..1e5f38a --- /dev/null +++ b/crates/tinywasm/src/reference/managed.rs @@ -0,0 +1,236 @@ +use alloc::sync::Arc; +use core::sync::atomic::{AtomicU32, Ordering}; + +use crate::interpreter::ValueRef; +use crate::{Result, Store, Trap}; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) struct StoreId(u32); + +impl StoreId { + pub(crate) fn fresh() -> Self { + static NEXT: AtomicU32 = AtomicU32::new(0); + next_store_id(&NEXT) + } + + pub(crate) const fn get(self) -> u32 { + self.0 + } +} + +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 { + f.write_str("StoreId(..)") + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) enum ReferentKind { + I31, + HostExtern, + Struct, + Array, + Exception, +} + +#[derive(Clone)] +pub(crate) struct RootedItem { + pub(crate) store: StoreId, + pub(crate) value: ValueRef, + pub(crate) kind: ReferentKind, + pub(crate) _token: Option>, +} + +impl PartialEq for RootedItem { + fn eq(&self, other: &Self) -> bool { + self.kind == other.kind + && self.value == other.value + && (self.kind == ReferentKind::I31 || self.store == other.store) + } +} + +impl Eq for RootedItem {} + +#[cfg(feature = "debug")] +impl core::fmt::Debug for RootedItem { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Reference").field("kind", &self.kind).finish_non_exhaustive() + } +} + +pub(crate) trait StoredRef: Clone + Sized { + fn from_rooted_item(item: RootedItem) -> Self; + fn rooted_item(&self) -> &RootedItem; +} + +macro_rules! reference_types { + ($($(#[$meta:meta])* $name:ident),* $(,)?) => {$($( + #[$meta] + )* + #[derive(Clone, PartialEq, Eq)] + #[cfg_attr(feature = "debug", derive(Debug))] + pub struct $name(RootedItem); + + impl StoredRef for $name { + fn from_rooted_item(item: RootedItem) -> Self { Self(item) } + fn rooted_item(&self) -> &RootedItem { &self.0 } + } + )*}; +} + +reference_types! { + /// An owned WebAssembly `anyref`. + AnyRef, + /// An owned WebAssembly `eqref`. + EqRef, + /// An owned WebAssembly `i31ref`. + I31Ref, + /// An owned WebAssembly `structref`. + StructRef, + /// An owned WebAssembly `arrayref`. + ArrayRef, + /// An owned WebAssembly `externref`. + ExternRef, + /// An owned WebAssembly `exnref`. + ExnRef, +} + +impl AnyRef { + /// Returns this reference as an `eqref` when its referent is comparable. + pub fn as_eq(&self) -> Option { + matches!(self.0.kind, ReferentKind::I31 | ReferentKind::Struct | ReferentKind::Array) + .then(|| EqRef(self.0.clone())) + } + + /// Returns this reference as an `i31ref` when it contains an i31. + pub fn as_i31(&self) -> Option { + (self.0.kind == ReferentKind::I31).then(|| I31Ref(self.0.clone())) + } + + /// Returns this reference as a `structref` when it refers to a struct. + pub fn as_struct(&self) -> Option { + (self.0.kind == ReferentKind::Struct).then(|| StructRef(self.0.clone())) + } + + /// Returns this reference as an `arrayref` when it refers to an array. + pub fn as_array(&self) -> Option { + (self.0.kind == ReferentKind::Array).then(|| ArrayRef(self.0.clone())) + } + + /// Returns this reference with the `externref` view. + pub fn to_extern(&self) -> ExternRef { + ExternRef(self.0.clone()) + } +} + +macro_rules! impl_to_any { + ($($ty:ty),* $(,)?) => {$( + impl $ty { + /// Returns this reference with the `anyref` view. + pub fn to_any(&self) -> AnyRef { AnyRef(self.0.clone()) } + } + )*}; +} + +impl_to_any!(EqRef, I31Ref, StructRef, ArrayRef, ExternRef); + +/// A Store-aware WebAssembly function reference. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct FuncRef { + store: StoreId, + addr: u32, +} + +impl FuncRef { + pub(crate) const fn new(store: StoreId, addr: u32) -> Self { + Self { store, addr } + } + + pub(crate) fn addr(self, store: StoreId) -> Option { + (self.store == store).then_some(self.addr) + } +} + +#[cfg(feature = "debug")] +impl core::fmt::Debug for FuncRef { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("FuncRef(..)") + } +} + +/// A host-facing WebAssembly reference value. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum RefValue { + /// A null reference. + Null, + /// A function reference. + Func(FuncRef), + /// An external reference. + Extern(ExternRef), + /// A reference in the `any` hierarchy. + Any(AnyRef), + /// An exception reference. + Exn(ExnRef), +} + +impl ExternRef { + /// Creates an external reference containing a host-defined key. + /// + /// Keys must be in `0..=(1 << 30) - 2`. + pub fn try_new(store: &mut Store, key: u32) -> Result { + let value = ValueRef::try_from_host_any(key).ok_or(Trap::InvalidReference)?; + store.root_reference(value, ReferentKind::HostExtern) + } + + /// Returns the host-defined key stored in this external reference. + /// + /// Returns an error for a reference produced by `extern.convert_any` from a + /// guest GC object or when `store` does not own the reference. + pub fn key(&self, store: &Store) -> Result { + let value = store.resolve_ref(self)?; + let addr = value.addr().filter(|_| value.is_host_any()).ok_or(Trap::InvalidReference)?; + Ok(addr & !(1 << 30)) + } +} + +impl I31Ref { + /// Creates a signed WebAssembly i31 reference. + /// + /// Values must be in `-2^30..=2^30 - 1`. + pub fn try_new(store: &mut Store, value: i32) -> Result { + if !(-(1 << 30)..(1 << 30)).contains(&value) { + return Err(Trap::InvalidReference.into()); + } + store.root_reference(ValueRef::from_i31(value), ReferentKind::I31) + } +} + +#[cfg(test)] +mod tests { + extern crate std; + use super::*; + + #[test] + fn 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()); + assert!(ValueRef::try_from_host_any((1 << 30) - 1).is_none()); + } +} diff --git a/crates/tinywasm/src/reference/mod.rs b/crates/tinywasm/src/reference/mod.rs new file mode 100644 index 0000000..7bc61e5 --- /dev/null +++ b/crates/tinywasm/src/reference/mod.rs @@ -0,0 +1,13 @@ +mod managed; +mod store; +mod value; + +pub use managed::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, RefValue, StructRef}; +pub(crate) use managed::{ReferentKind, RootedItem, StoreId, StoredRef}; +#[cfg(feature = "std")] +pub use store::MemoryCursor; +pub(crate) use store::StoreItem; +pub use store::{ + GcFieldType, GcHeapType, GcRefType, GcStorageType, GcType, GcTypeKind, GcValueType, Global, Memory, Table, Tag, +}; +pub use value::WasmValue; diff --git a/crates/tinywasm/src/reference/store.rs b/crates/tinywasm/src/reference/store.rs new file mode 100644 index 0000000..d0eba6b --- /dev/null +++ b/crates/tinywasm/src/reference/store.rs @@ -0,0 +1,915 @@ +use core::hint::cold_path; + +use alloc::ffi::CString; +use alloc::format; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; + +use super::managed::{ReferentKind, StoreId, StoredRef}; +use crate::interpreter::ValueRef; +use crate::store::TableInstance; +use crate::{ArrayRef, Error, ExnRef, I31Ref, MemoryInstance, Result, Store, StructRef, Trap, WasmValue}; +use tinywasm_types::{ + AbstractHeapType, Addr, CompositeType, FieldType, FuncType, GlobalType, MemAddr, MemoryType, StorageType, + TableAddr, TableType, TagAddr, TypeAddr, WasmType, +}; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) struct StoreItem { + pub(crate) store_id: StoreId, + pub(crate) addr: Addr, +} + +impl StoreItem { + #[inline] + /// Creates a handle for an address owned by a store. + pub(crate) const fn new(store_id: StoreId, addr: Addr) -> Self { + Self { store_id, addr } + } + + #[inline] + pub(crate) fn validate_store(&self, store: &Store) -> Result<(), Trap> { + if self.store_id != store.store_id() { + return Err(Trap::InvalidStore); + } + Ok(()) + } +} + +/// A memory instance in a store. +/// +/// See +/// +/// ## Example +/// ```rust +/// # fn main() -> tinywasm::Result<()> { +/// use tinywasm::types::MemoryType; +/// use tinywasm::{Memory, Store}; +/// +/// let mut store = Store::default(); +/// let memory = Memory::try_new(&mut store, MemoryType::default().with_page_count_initial(1))?; +/// +/// memory.copy_from_slice(&mut store, 0, b"hi")?; +/// assert_eq!(memory.read_vec(&store, 0, 2)?, b"hi"); +/// assert_eq!(memory.page_count(&store)?, 1); +/// memory.grow(&mut store, 1)?; +/// assert_eq!(memory.page_count(&store)?, 2); +/// # Ok(()) +/// # } +/// ``` +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Memory(pub(crate) StoreItem); + +/// A table instance in a store. +/// +/// See +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Table(pub(crate) StoreItem); + +/// A global instance in a store. +/// +/// See +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Global(pub(crate) StoreItem); + +/// A tag instance in a store. +/// +/// See +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Tag(pub(crate) StoreItem); + +/// An opaque canonical function, struct, or array type owned by a Store. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct GcType(StoreItem); + +/// The composite kind of a [`GcType`]. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum GcTypeKind { + /// A function type. + Function, + /// A struct type. + Struct, + /// An array type. + Array, +} + +/// Metadata for a struct field or array element. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct GcFieldType { + storage: GcStorageType, + mutable: bool, +} + +impl GcFieldType { + /// Returns the field's storage type. + pub const fn storage(self) -> GcStorageType { + self.storage + } + + /// Returns whether the field can be changed. + pub const fn is_mutable(self) -> bool { + self.mutable + } +} + +/// Host-visible storage metadata for a GC field or array element. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum GcStorageType { + /// A packed 8-bit integer. + I8, + /// A packed 16-bit integer. + I16, + /// An unpacked WebAssembly value. + Value(GcValueType), +} + +/// Host-visible value metadata that does not expose concrete reference encodings. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum GcValueType { + /// A 32-bit integer. + I32, + /// A 64-bit integer. + I64, + /// A 32-bit float. + F32, + /// A 64-bit float. + F64, + /// A 128-bit vector. + V128, + /// A reference type. + Ref(GcRefType), +} + +/// Host-visible reference metadata with opaque concrete types. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct GcRefType { + nullable: bool, + heap_type: GcHeapType, +} + +impl GcRefType { + /// Returns whether the reference type accepts null. + pub const fn is_nullable(self) -> bool { + self.nullable + } + + /// Returns the abstract or opaque concrete heap type. + pub const fn heap_type(self) -> GcHeapType { + self.heap_type + } +} + +/// Host-visible heap type metadata. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum GcHeapType { + /// An abstract WebAssembly heap type. + Abstract(AbstractHeapType), + /// An opaque canonical type owned by the Store. + Concrete(GcType), +} + +impl GcType { + fn subtype(self, store: &Store) -> Result<&tinywasm_types::SubType> { + self.0.validate_store(store)?; + store.state.canonical_types.get(self.0.addr as usize).ok_or_else(|| Trap::InvalidReference.into()) + } + + /// Returns this type's composite kind. + pub fn kind(self, store: &Store) -> Result { + Ok(match &self.subtype(store)?.composite { + CompositeType::Func(_) => GcTypeKind::Function, + CompositeType::Struct(_) => GcTypeKind::Struct, + CompositeType::Array(_) => GcTypeKind::Array, + }) + } + + /// Returns whether this type is a nominal subtype of `other`. + pub fn is_subtype_of(self, store: &Store, other: Self) -> Result { + self.subtype(store)?; + other.subtype(store)?; + Ok(store.state.type_addr_is_subtype(self.0.addr, other.0.addr)) + } + + /// Returns the number of struct fields. + pub fn field_count(self, store: &Store) -> Result { + self.subtype(store)? + .as_struct() + .map(|ty| ty.fields.len()) + .ok_or_else(|| Error::other("GC type is not a struct")) + } + + /// Returns metadata for one struct field. + pub fn field(self, store: &Store, index: usize) -> Result { + let field = self + .subtype(store)? + .as_struct() + .ok_or_else(|| Error::other("GC type is not a struct"))? + .fields + .get(index) + .copied() + .ok_or_else(|| Error::other("struct field out of bounds"))?; + Ok(gc_field_type(store, field)) + } + + /// Returns metadata for an array element. + pub fn array_element(self, store: &Store) -> Result { + let field = self.subtype(store)?.as_array().ok_or_else(|| Error::other("GC type is not an array"))?.field; + Ok(gc_field_type(store, field)) + } +} + +fn gc_field_type(store: &Store, field: FieldType) -> GcFieldType { + let storage = match field.storage { + StorageType::I8 => GcStorageType::I8, + StorageType::I16 => GcStorageType::I16, + StorageType::Value(ty) => GcStorageType::Value(match ty { + WasmType::I32 => GcValueType::I32, + WasmType::I64 => GcValueType::I64, + WasmType::F32 => GcValueType::F32, + WasmType::F64 => GcValueType::F64, + WasmType::V128 => GcValueType::V128, + WasmType::Ref(ty) => GcValueType::Ref(GcRefType { + nullable: ty.is_nullable(), + heap_type: match ty.type_index() { + Some(addr) => GcHeapType::Concrete(GcType(StoreItem::new(store.store_id(), addr))), + None => GcHeapType::Abstract(ty.abstract_heap_type().expect("abstract reference type")), + }, + }), + }), + }; + GcFieldType { storage, mutable: field.mutable } +} + +fn rooted_object(store: &Store, root: &T, kind: ReferentKind) -> Result<(ValueRef, TypeAddr)> { + let value = store.resolve_ref(root)?; + if root.rooted_item().kind != kind { + return Err(Trap::InvalidReference.into()); + } + let object = store.state.gc.get(value).ok_or(Trap::InvalidReference)?; + let crate::store::GcObjectKind::Composite(type_addr) = object.kind else { + return Err(Trap::InvalidReference.into()); + }; + Ok((value, type_addr)) +} + +/// A cursor over a [`Memory`] instance. +/// +/// Available with the `std` feature enabled. +#[cfg(feature = "std")] +pub struct MemoryCursor<'a> { + memory: &'a mut MemoryInstance, + position: u64, +} + +#[cfg(feature = "std")] +impl MemoryCursor<'_> { + fn offset(&self) -> crate::std::io::Result { + usize::try_from(self.position).map_err(|_| { + crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position exceeds usize") + }) + } + + fn advance(&mut self, amount: usize) -> crate::std::io::Result<()> { + self.position = self.position.checked_add(amount as u64).ok_or_else(|| { + crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position overflow") + })?; + Ok(()) + } + + /// Returns the current cursor position. + pub const fn position(&self) -> u64 { + self.position + } + + /// Sets the current cursor position. + pub fn set_position(&mut self, position: u64) { + self.position = position; + } +} + +#[cfg(feature = "std")] +impl crate::std::io::Read for MemoryCursor<'_> { + fn read(&mut self, buf: &mut [u8]) -> crate::std::io::Result { + let offset = self.offset()?; + let read = self.memory.inner.read(offset, buf); + self.advance(read)?; + Ok(read) + } +} + +#[cfg(feature = "std")] +impl crate::std::io::Write for MemoryCursor<'_> { + fn write(&mut self, buf: &[u8]) -> crate::std::io::Result { + let offset = self.offset()?; + let written = self.memory.inner.write(offset, buf); + self.advance(written)?; + Ok(written) + } + + fn flush(&mut self) -> crate::std::io::Result<()> { + Ok(()) + } +} + +#[cfg(feature = "std")] +impl crate::std::io::Seek for MemoryCursor<'_> { + fn seek(&mut self, pos: crate::std::io::SeekFrom) -> crate::std::io::Result { + let len = self.memory.inner.len() as i128; + let current = i128::from(self.position); + + let next = match pos { + crate::std::io::SeekFrom::Start(offset) => i128::from(offset), + crate::std::io::SeekFrom::End(offset) => len + i128::from(offset), + crate::std::io::SeekFrom::Current(offset) => current + i128::from(offset), + }; + + if next < 0 { + return Err(crate::std::io::Error::new( + crate::std::io::ErrorKind::InvalidInput, + "invalid seek before start", + )); + } + + let next = u64::try_from(next).map_err(|_| { + crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "invalid seek position") + })?; + self.position = next; + Ok(next) + } +} + +impl Memory { + /// Create a new memory in the given store. + pub fn try_new(store: &mut Store, ty: MemoryType) -> Result { + 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))) + } + + /// Creates a cursor positioned at the start of this memory. + /// + /// Available with the `std` feature enabled. + /// + /// ## Example + /// + /// ```rust + /// # fn main() -> Result<(), Box> { + /// use std::io::{Read, Seek, SeekFrom, Write}; + /// use tinywasm::types::MemoryType; + /// use tinywasm::{Memory, Store}; + /// + /// let mut store = Store::default(); + /// let memory = Memory::try_new(&mut store, MemoryType::default().with_page_count_initial(1))?; + /// let mut cursor = memory.cursor(&mut store)?; + /// + /// cursor.seek(SeekFrom::Start(2))?; + /// cursor.write_all(b"abc")?; + /// cursor.seek(SeekFrom::Start(0))?; + /// + /// let mut bytes = [0; 5]; + /// cursor.read_exact(&mut bytes)?; + /// assert_eq!(bytes, [0, 0, b'a', b'b', b'c']); + /// # Ok(()) + /// # } + /// ``` + #[cfg(feature = "std")] + pub fn cursor<'a>(&self, store: &'a mut Store) -> Result> { + self.cursor_at(store, 0) + } + + /// Creates a cursor positioned at `position` bytes from the start of this memory. + /// + /// Available with the `std` feature enabled. + #[cfg(feature = "std")] + pub fn cursor_at<'a>(&self, store: &'a mut Store, position: u64) -> Result> { + Ok(MemoryCursor { memory: self.instance_mut(store)?, position }) + } + + #[inline] + fn instance<'a>(&self, store: &'a Store) -> Result<&'a MemoryInstance> { + self.0.validate_store(store)?; + Ok(store.state.get_mem(self.0.addr)) + } + + #[inline] + fn instance_mut<'a>(&self, store: &'a mut Store) -> Result<&'a mut MemoryInstance> { + self.0.validate_store(store)?; + Ok(store.state.get_mem_mut(self.0.addr)) + } + + /// Returns the raw memory byte length. + pub fn len(&self, store: &Store) -> Result { + Ok(self.instance(store)?.inner.len()) + } + + /// Returns the memory type, including page size and limits. + pub fn ty(&self, store: &Store) -> Result { + Ok(self.instance(store)?.kind) + } + + /// Reads up to `dst.len()` bytes from memory and returns the number of bytes read. + /// + /// This returns fewer bytes than requested when the range extends past the end of memory. Use + /// [`Self::read_exact`] or [`Self::read_vec`] when you need a full range. + pub fn read(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result { + Ok(self.instance(store)?.inner.read(offset, dst)) + } + + /// Writes up to `src.len()` bytes into memory and returns the number of bytes written. + /// + /// This returns fewer bytes than requested when the range extends past the end of memory. Use + /// [`Self::copy_from_slice`] when you need the full slice written. + pub fn write(&self, store: &mut Store, offset: usize, src: &[u8]) -> Result { + Ok(self.instance_mut(store)?.inner.write(offset, src)) + } + + /// Reads exactly `dst.len()` bytes from memory. + pub fn read_exact(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result<()> { + self.instance(store)?.inner.read_exact(offset, dst).ok_or_else(|| { + Error::Trap(crate::Trap::MemoryOutOfBounds { + offset, + len: dst.len(), + max: self.instance(store).unwrap().inner.len(), + }) + }) + } + + /// Reads `len` bytes from memory into a newly allocated buffer. + pub fn read_vec(&self, store: &Store, offset: usize, len: usize) -> Result> { + self.instance(store)?.inner.read_vec(offset, len).ok_or_else(|| { + Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() }) + }) + } + + /// Grows the memory by the given number of pages. + /// + /// Returns the previous size, or `None` if growth fails or is rejected by the resource limiter. + /// A limiter-provided trap is returned as an error. + pub fn grow(&self, store: &mut Store, delta_pages: i64) -> Result> { + let limiter = store.engine.config().resource_limiter.clone(); + let mem = self.instance_mut(store)?; + mem.grow(delta_pages, limiter.as_deref()).map_err(Into::into) + } + + /// Get the current size of the memory in pages. + pub fn page_count(&self, store: &Store) -> Result { + Ok(self.instance(store)?.page_count) + } + + /// Copy a slice of memory to another place in memory. + pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<()> { + self.instance_mut(store)?.copy_within(dst, src, len)?; + Ok(()) + } + + /// Fill a slice of memory with a value. + pub fn fill(&self, store: &mut Store, offset: usize, len: usize, val: u8) -> Result<()> { + self.instance_mut(store)?.inner.fill(offset, len, val).ok_or_else(|| { + Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() }) + }) + } + + /// Copies a full slice into memory. + pub fn copy_from_slice(&self, store: &mut Store, offset: usize, data: &[u8]) -> Result<()> { + self.instance_mut(store)?.inner.write_all(offset, data).ok_or_else(|| { + Error::Trap(crate::Trap::MemoryOutOfBounds { + offset, + len: data.len(), + max: self.instance(store).unwrap().inner.len(), + }) + }) + } + + /// Copies a nul-terminated C string into memory. + pub fn write_cstring(&self, store: &mut Store, offset: usize, string: &CString) -> Result<()> { + self.copy_from_slice(store, offset, string.as_bytes_with_nul()) + } + + /// Copies a UTF-8 string into memory and appends a trailing nul byte. + pub fn write_cstring_bytes(&self, store: &mut Store, offset: usize, string: &str) -> Result<()> { + let mut bytes = Vec::with_capacity(string.len() + 1); + bytes.extend_from_slice(string.as_bytes()); + bytes.push(0); + self.copy_from_slice(store, offset, &bytes) + } + + /// Reads a C-style string from memory. + pub fn read_cstring(&self, store: &Store, offset: usize, len: usize) -> Result { + CString::from_vec_with_nul(self.read_vec(store, offset, len)?) + .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}"))) + } + + /// Reads a C-style string from memory, stopping at the first null byte. + pub fn read_cstring_until_null(&self, store: &Store, offset: usize, max_len: usize) -> Result { + let bytes = self.read_vec(store, offset, max_len)?; + let Some(null) = bytes.iter().position(|byte| *byte == 0) else { + return Err(crate::Error::Other("Invalid C-style string: missing null terminator".to_string())); + }; + + CString::from_vec_with_nul(bytes[..=null].to_vec()) + .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}"))) + } + + /// Reads a UTF-8 string from memory. + pub fn read_string(&self, store: &Store, offset: usize, len: usize) -> Result { + String::from_utf8(self.read_vec(store, offset, len)?) + .map_err(|e| crate::Error::Other(format!("Invalid UTF-8 string: {e}"))) + } + + /// Reads a JavaScript-style utf-16 string from memory. + pub fn read_js_string(&self, store: &Store, offset: usize, len: usize) -> Result { + let bytes = self.read_vec(store, offset, len)?; + let mut string = String::new(); + for i in 0..(len / 2) { + let c = u16::from_le_bytes([bytes[i * 2], bytes[i * 2 + 1]]); + string.push( + char::from_u32(u32::from(c)).ok_or_else(|| crate::Error::Other("Invalid UTF-16 string".to_string()))?, + ); + } + Ok(string) + } +} + +fn table_value_to_element( + store: &Store, + element_type: tinywasm_types::RefType, + value: WasmValue, +) -> Result { + let WasmValue::Ref(reference) = &value else { + return Err(Trap::Other("invalid table value type")); + }; + if !store.value_matches_type(&value, WasmType::Ref(element_type)) { + return Err(Trap::Other("invalid table value type")); + } + store.encode_ref(reference).map_err(|error| match error { + Error::Trap(trap) => trap, + _ => Trap::Other("invalid table value type"), + }) +} + +impl I31Ref { + /// Returns the signed i31 value. + pub fn value(&self, store: &Store) -> Result { + if self.rooted_item().kind != ReferentKind::I31 { + return Err(Trap::InvalidReference.into()); + } + store.resolve_ref(self)?.i31_s().ok_or_else(|| Trap::InvalidReference.into()) + } +} + +impl StructRef { + /// Returns this struct's canonical type. + pub fn ty(&self, store: &Store) -> Result { + let (_, type_addr) = rooted_object(store, self, ReferentKind::Struct)?; + Ok(GcType(StoreItem::new(store.store_id(), type_addr))) + } + + /// Reads one field. + /// + /// Packed integer fields are returned as zero-extended `i32` values. Mutable + /// Store access is required to register owned reference results. + pub fn field(&self, store: &mut Store, index: usize) -> Result { + let (reference, type_addr) = rooted_object(store, self, ReferentKind::Struct)?; + let storage = store + .state + .get_type(type_addr) + .as_struct() + .unwrap() + .fields + .get(index) + .ok_or_else(|| Error::other("struct field out of bounds"))? + .storage; + let value = *store.state.gc.get(reference).unwrap().values.get(index).unwrap(); + value.into_wasm(store, storage.unpacked()) + } + + /// Reads all fields in declaration order. + /// + /// Mutable Store access is required because reference results are registered with the Store. + pub fn fields(&self, store: &mut Store) -> Result> { + let (reference, type_addr) = rooted_object(store, self, ReferentKind::Struct)?; + let field_count = store.state.get_type(type_addr).as_struct().unwrap().fields.len(); + let mut values = Vec::new(); + values.try_reserve_exact(field_count).map_err(|_| Trap::OutOfMemory)?; + for index in 0..field_count { + let storage = store.state.get_type(type_addr).as_struct().unwrap().fields[index].storage; + let value = store.state.gc.get(reference).unwrap().values[index]; + values.push(value.into_wasm(store, storage.unpacked())?); + } + Ok(values) + } + + /// Writes one mutable field after validating its canonical value type. + /// + /// Writes to packed integer fields truncate the input to the field width. + pub fn set_field(&self, store: &mut Store, index: usize, value: WasmValue) -> Result<()> { + let (reference, type_addr) = rooted_object(store, self, ReferentKind::Struct)?; + let field = *store + .state + .get_type(type_addr) + .as_struct() + .unwrap() + .fields + .get(index) + .ok_or_else(|| Error::other("struct field out of bounds"))?; + set_gc_value(store, reference, index, field, value, "struct field") + } +} + +impl ArrayRef { + /// Returns this array's canonical type. + pub fn ty(&self, store: &Store) -> Result { + let (_, type_addr) = rooted_object(store, self, ReferentKind::Array)?; + Ok(GcType(StoreItem::new(store.store_id(), type_addr))) + } + + /// Returns the number of array elements. + pub fn len(&self, store: &Store) -> Result { + let (reference, _) = rooted_object(store, self, ReferentKind::Array)?; + Ok(store.state.gc.get(reference).unwrap().values.len()) + } + + /// Returns whether the array contains no elements. + pub fn is_empty(&self, store: &Store) -> Result { + Ok(self.len(store)? == 0) + } + + /// Reads one array element. + /// + /// Packed integer elements are returned as zero-extended `i32` values. Mutable + /// Store access is required to register owned reference results. + pub fn get(&self, store: &mut Store, index: usize) -> Result { + let (reference, type_addr) = rooted_object(store, self, ReferentKind::Array)?; + let storage = store.state.get_type(type_addr).as_array().unwrap().field.storage; + let value = *store.state.gc.get(reference).unwrap().values.get(index).ok_or(Trap::ArrayOutOfBounds)?; + value.into_wasm(store, storage.unpacked()) + } + + /// Writes one mutable array element after validating its canonical value type. + /// + /// Writes to packed integer elements truncate the input to the element width. + pub fn set(&self, store: &mut Store, index: usize, value: WasmValue) -> Result<()> { + let (reference, type_addr) = rooted_object(store, self, ReferentKind::Array)?; + let field = store.state.get_type(type_addr).as_array().unwrap().field; + if index >= store.state.gc.get(reference).unwrap().values.len() { + return Err(Trap::ArrayOutOfBounds.into()); + } + set_gc_value(store, reference, index, field, value, "array element") + } +} + +fn set_gc_value( + store: &mut Store, + reference: ValueRef, + index: usize, + field: FieldType, + value: WasmValue, + field_name: &'static str, +) -> Result<()> { + if !field.mutable { + return Err(Error::other(format!("{field_name} is immutable"))); + } + let expected = field.storage.unpacked(); + if !store.value_matches_type(&value, expected) { + return Err(Error::other(format!("invalid {field_name} value type"))); + } + let value = match (field.storage, value.to_runtime(store)?) { + (StorageType::I8, crate::interpreter::RuntimeValue::Value32(value)) => { + crate::interpreter::RuntimeValue::Value32(value as u8 as u32) + } + (StorageType::I16, crate::interpreter::RuntimeValue::Value32(value)) => { + crate::interpreter::RuntimeValue::Value32(value as u16 as u32) + } + (_, value) => value, + }; + let handle = store.state.gc.handle(reference).ok_or(Trap::InvalidReference)?; + store.state.gc.set(handle, index, value).ok_or_else(|| Trap::InvalidReference.into()) +} + +impl ExnRef { + /// Returns the exception's tag. + pub fn tag(&self, store: &Store) -> Result { + let (_, tag_addr) = exception_object(store, self)?; + Ok(Tag(StoreItem::new(store.store_id(), tag_addr))) + } + + /// Reads one exception payload field. + /// + /// Mutable Store access is required because reference results are registered with the Store. + pub fn field(&self, store: &mut Store, index: usize) -> Result { + let (reference, tag_addr) = exception_object(store, self)?; + let type_addr = store.state.get_tag(tag_addr).type_addr; + let ty = *store + .state + .get_canonical_func_type(type_addr) + .params() + .get(index) + .ok_or_else(|| Error::other("exception payload field out of bounds"))?; + let value = *store + .state + .gc + .get(reference) + .unwrap() + .values + .get(index) + .ok_or_else(|| Error::other("exception payload field out of bounds"))?; + value.into_wasm(store, ty) + } + + /// Reads all exception payload fields. + /// + /// Mutable Store access is required because reference results are registered with the Store. + pub fn fields(&self, store: &mut Store) -> Result> { + let (reference, tag_addr) = exception_object(store, self)?; + let type_addr = store.state.get_tag(tag_addr).type_addr; + let field_count = store.state.gc.get(reference).unwrap().values.len(); + let mut fields = Vec::new(); + fields.try_reserve_exact(field_count).map_err(|_| Trap::OutOfMemory)?; + for index in 0..field_count { + let ty = store.state.get_canonical_func_type(type_addr).params()[index]; + let value = store.state.gc.get(reference).unwrap().values[index]; + fields.push(value.into_wasm(store, ty)?); + } + Ok(fields) + } +} + +fn exception_object(store: &Store, root: &ExnRef) -> Result<(ValueRef, TagAddr)> { + let reference = store.resolve_ref(root)?; + if root.rooted_item().kind != ReferentKind::Exception { + return Err(Trap::InvalidReference.into()); + } + let object = store.state.gc.get(reference).ok_or(Trap::InvalidReference)?; + let crate::store::GcObjectKind::Exception(tag_addr) = object.kind else { + return Err(Trap::InvalidReference.into()); + }; + Ok((reference, tag_addr)) +} + +impl Table { + /// Create a new table in the given store. + pub fn try_new(store: &mut Store, ty: TableType, init: WasmValue) -> Result { + if ty.element_type.is_concrete() { + return Err(Error::other("host tables cannot use module-relative concrete reference types")); + } + let init = table_value_to_element(store, ty.element_type, init).map_err(Error::from)?; + let limiter = store.engine.config().resource_limiter.clone(); + let addr = store.state.tables.len() as TableAddr; + store.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); + Ok(Self(StoreItem::new(store.store_id(), addr))) + } + + #[inline] + fn instance<'a>(&self, store: &'a Store) -> Result<&'a TableInstance> { + self.0.validate_store(store)?; + Ok(store.state.get_table(self.0.addr)) + } + + /// Get the type of the table. + pub fn ty(&self, store: &Store) -> Result { + Ok(self.instance(store)?.kind) + } + + /// Get the current number of elements in the table. + pub fn size(&self, store: &Store) -> Result { + Ok(self.instance(store)?.size()) + } + + /// Get a table element as a wasm reference value. + /// + /// Mutable Store access is required because managed results are registered with the Store. + pub fn get(&self, store: &mut Store, index: TableAddr) -> Result { + self.0.validate_store(store)?; + let table = store.state.get_table(self.0.addr); + let value = *table.get(index as usize)?; + let element_type = table.kind.element_type; + Ok(WasmValue::Ref(store.decode_ref(value, element_type)?)) + } + + /// Load a range of table elements and iterate over wasm reference values. + /// + /// Mutable Store access is required because managed results are registered with the Store. + pub fn load(&self, store: &mut Store, offset: usize, len: usize) -> Result> { + self.0.validate_store(store)?; + let table = store.state.get_table(self.0.addr); + let element_type = table.kind.element_type; + let elements = table.load(offset, len)?.to_vec(); + let mut values = Vec::new(); + values.try_reserve_exact(elements.len()).map_err(|_| Trap::OutOfMemory)?; + for value in elements { + values.push(WasmValue::Ref(store.decode_ref(value, element_type)?)); + } + Ok(values.into_iter()) + } + + /// Set a table element. + pub fn set(&self, store: &mut Store, index: TableAddr, value: WasmValue) -> Result<(), Trap> { + self.0.validate_store(store)?; + let element_type = store.state.get_table(self.0.addr).kind.element_type; + let value = table_value_to_element(store, element_type, value)?; + store.state.get_table_mut(self.0.addr).set(index as usize, value) + } + + /// Copy elements within the same table. + pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<(), Trap> { + self.0.validate_store(store)?; + store.state.get_table_mut(self.0.addr).copy_within(dst, src, len) + } + + /// Grows the table and returns the previous size. + /// + /// Returns `None` if growth fails or is rejected by the resource limiter. A limiter-provided + /// trap is returned as an error. + pub fn grow(&self, store: &mut Store, delta: i32, init: WasmValue) -> Result> { + self.0.validate_store(store)?; + let table = store.state.get_table(self.0.addr); + let old_size = table.size(); + let init = table_value_to_element(store, table.kind.element_type, init)?; + let Ok(delta) = usize::try_from(delta) else { + return Ok(None); + }; + let limiter = store.engine.config().resource_limiter.clone(); + match store.state.get_table_mut(self.0.addr).grow(delta, init, limiter.as_deref())? { + true => Ok(Some(old_size)), + false => Ok(None), + } + } +} + +impl Global { + /// Create a new global in the given store. + pub fn try_new(store: &mut Store, ty: GlobalType, value: WasmValue) -> Result { + if matches!(ty.ty, WasmType::Ref(ty) if ty.is_concrete()) { + return Err(Error::other("host globals cannot use module-relative concrete reference types")); + } + if !store.value_matches_type(&value, ty.ty) { + cold_path(); + return Err(Error::Other("invalid global value type".to_string())); + } + let value = value.to_runtime(store)?; + let addr = store.state.globals.push(ty, value); + Ok(Self(StoreItem::new(store.store_id(), addr))) + } + + /// Get the type of the global. + pub fn ty(&self, store: &Store) -> Result { + self.0.validate_store(store)?; + Ok(store.state.globals.ty(self.0.addr)) + } + + /// Get the current value of the global. + /// + /// Mutable Store access is required because an owned reference result is registered with the Store. + pub fn get(&self, store: &mut Store) -> Result { + self.0.validate_store(store)?; + let ty = store.state.globals.ty(self.0.addr).ty; + let value = store.state.global_value(self.0.addr); + value.into_wasm(store, ty) + } + + /// Set the current value of the global. + pub fn set(&self, store: &mut Store, value: WasmValue) -> Result<()> { + self.0.validate_store(store)?; + let ty = store.state.globals.ty(self.0.addr).ty; + if !store.value_matches_type(&value, ty) { + return Err(Error::other("invalid global value type")); + } + let value = value.to_runtime(store)?; + store.state.set_global_value(self.0.addr, value) + } +} + +impl Tag { + /// Create a new exception tag in the given store. + pub fn try_new(store: &mut Store, ty: FuncType) -> Result { + if !ty.results().is_empty() { + return Err(Error::other("tag types must not have results")); + } + if ty.params().iter().any(|ty| matches!(ty, WasmType::Ref(ty) if ty.is_concrete())) { + return Err(Error::other("host tags cannot use concrete reference types")); + } + let type_addr = store.register_host_type(&ty); + let addr = store.state.tags.len() as TagAddr; + store.state.tags.push(crate::store::TagInstance { type_addr }); + Ok(Self(StoreItem::new(store.store_id(), addr))) + } + + /// Get the payload type of the tag. + pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> { + self.0.validate_store(store)?; + Ok(store.state.get_canonical_func_type(store.state.get_tag(self.0.addr).type_addr)) + } +} diff --git a/crates/tinywasm/src/reference/value.rs b/crates/tinywasm/src/reference/value.rs new file mode 100644 index 0000000..7ef3dea --- /dev/null +++ b/crates/tinywasm/src/reference/value.rs @@ -0,0 +1,232 @@ +use core::fmt::Debug; + +use tinywasm_types::{AbstractHeapType, RefType, WasmType}; + +use crate::interpreter::{RuntimeValue, Value128}; +use crate::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, RefValue, Result, Store, StructRef}; + +/// A host-facing WebAssembly value. +/// +/// See +#[derive(Clone, PartialEq)] +pub enum WasmValue { + /// A 32-bit integer. + I32(i32), + /// A 64-bit integer. + I64(i64), + /// A 32-bit float. + F32(f32), + /// A 64-bit float. + F64(f64), + /// A 128-bit vector. + V128([u8; 16]), + /// A reference. + Ref(RefValue), +} + +impl WasmValue { + pub(crate) fn to_runtime(&self, store: &Store) -> Result { + Ok(match self { + Self::I32(value) => RuntimeValue::Value32(*value as u32), + Self::I64(value) => RuntimeValue::Value64(*value as u64), + Self::F32(value) => RuntimeValue::Value32(value.to_bits()), + Self::F64(value) => RuntimeValue::Value64(value.to_bits()), + Self::V128(value) => RuntimeValue::Value128(Value128(*value)), + Self::Ref(value) => RuntimeValue::ValueRef(store.encode_ref(value)?), + }) + } + + /// Returns this value's broad WebAssembly type, or `None` for null. + pub fn ty(&self) -> Option { + match self { + Self::I32(_) => Some(WasmType::I32), + Self::I64(_) => Some(WasmType::I64), + Self::F32(_) => Some(WasmType::F32), + Self::F64(_) => Some(WasmType::F64), + Self::V128(_) => Some(WasmType::V128), + Self::Ref(RefValue::Null) => None, + Self::Ref(RefValue::Func(_)) => Some(WasmType::Ref(RefType::FUNCREF)), + Self::Ref(RefValue::Extern(_)) => Some(WasmType::Ref(RefType::EXTERNREF)), + Self::Ref(RefValue::Exn(_)) => Some(WasmType::Ref(RefType::EXNREF)), + Self::Ref(RefValue::Any(_)) => Some(WasmType::Ref(RefType::new_abstract(true, AbstractHeapType::Any))), + } + } + + /// Returns whether this value matches a broad or abstract type. + /// + /// A non-null value does not match a concrete reference type because + /// concrete types require Store-specific subtype information. + pub fn matches_type(&self, ty: WasmType) -> bool { + match (self, ty) { + (Self::I32(_), WasmType::I32) + | (Self::I64(_), WasmType::I64) + | (Self::F32(_), WasmType::F32) + | (Self::F64(_), WasmType::F64) + | (Self::V128(_), WasmType::V128) => true, + (Self::Ref(RefValue::Null), WasmType::Ref(ty)) => ty.is_nullable(), + (Self::Ref(RefValue::Func(_)), WasmType::Ref(ty)) => { + ty.abstract_heap_type() == Some(AbstractHeapType::Func) + } + (Self::Ref(RefValue::Extern(_)), WasmType::Ref(ty)) => { + ty.abstract_heap_type() == Some(AbstractHeapType::Extern) + } + (Self::Ref(RefValue::Exn(_)), WasmType::Ref(ty)) => ty.abstract_heap_type() == Some(AbstractHeapType::Exn), + (Self::Ref(RefValue::Any(value)), WasmType::Ref(ty)) => match ty.abstract_heap_type() { + Some(AbstractHeapType::Any) => true, + Some(AbstractHeapType::Eq) => value.as_eq().is_some(), + Some(AbstractHeapType::I31) => value.as_i31().is_some(), + Some(AbstractHeapType::Struct) => value.as_struct().is_some(), + Some(AbstractHeapType::Array) => value.as_array().is_some(), + _ => false, + }, + _ => false, + } + } + + /// Returns the default value for `ty`, or `None` for a non-null reference type. + pub fn default_for(ty: WasmType) -> Option { + match ty { + WasmType::I32 => Some(Self::I32(0)), + WasmType::I64 => Some(Self::I64(0)), + WasmType::F32 => Some(Self::F32(0.0)), + WasmType::F64 => Some(Self::F64(0.0)), + WasmType::V128 => Some(Self::V128([0; 16])), + WasmType::Ref(ty) if ty.is_nullable() => Some(Self::Ref(RefValue::Null)), + WasmType::Ref(_) => None, + } + } + + /// Compares values while treating NaN values with different payloads as equal. + pub fn eq_loose(&self, other: &Self) -> bool { + match (self, other) { + (Self::F32(a), Self::F32(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(), + (Self::F64(a), Self::F64(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(), + (Self::V128(a), Self::V128(b)) => a == b || vector_nan_eq(*a, *b), + _ => self == other, + } + } +} + +fn vector_nan_eq(a: [u8; 16], b: [u8; 16]) -> bool { + let f32_equal = a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0).all(|(a, b)| { + let a = f32::from_le_bytes(*a); + let b = f32::from_le_bytes(*b); + a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits() + }); + if f32_equal && a.as_chunks::<4>().0.iter().any(|v| f32::from_le_bytes(*v).is_nan()) { + return true; + } + a.as_chunks::<8>().0.iter().zip(b.as_chunks::<8>().0).all(|(a, b)| { + let a = f64::from_le_bytes(*a); + let b = f64::from_le_bytes(*b); + a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits() + }) && a.as_chunks::<8>().0.iter().any(|v| f64::from_le_bytes(*v).is_nan()) +} + +impl Debug for WasmValue { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::I32(value) => write!(f, "i32({value})"), + Self::I64(value) => write!(f, "i64({value})"), + Self::F32(value) => write!(f, "f32({value})"), + Self::F64(value) => write!(f, "f64({value})"), + Self::V128(value) => write!(f, "v128({value:?})"), + #[cfg(feature = "debug")] + Self::Ref(value) => write!(f, "ref({value:?})"), + #[cfg(not(feature = "debug"))] + Self::Ref(_) => f.write_str("ref(..)"), + } + } +} + +macro_rules! value_conversions { + ($($ty:ty => $variant:ident, $method:ident);* $(;)?) => {$( + impl WasmValue { + #[doc = concat!("Returns the contained `", stringify!($ty), "` value.")] + pub fn $method(&self) -> Option<$ty> { + if let Self::$variant(value) = self { Some(value.clone()) } else { None } + } + } + impl From<$ty> for WasmValue { fn from(value: $ty) -> Self { Self::$variant(value) } } + impl TryFrom for $ty { + type Error = (); + fn try_from(value: WasmValue) -> Result { + if let WasmValue::$variant(value) = value { Ok(value) } else { Err(()) } + } + } + )*}; +} + +value_conversions! { + i32 => I32, as_i32; + i64 => I64, as_i64; + f32 => F32, as_f32; + f64 => F64, as_f64; + [u8; 16] => V128, as_v128; +} + +impl WasmValue { + /// Returns the contained reference value. + pub const fn as_ref(&self) -> Option<&RefValue> { + if let Self::Ref(value) = self { Some(value) } else { None } + } +} + +impl From for WasmValue { + fn from(value: RefValue) -> Self { + Self::Ref(value) + } +} + +impl TryFrom for RefValue { + type Error = (); + + fn try_from(value: WasmValue) -> Result { + if let WasmValue::Ref(value) = value { Ok(value) } else { Err(()) } + } +} + +macro_rules! ref_conversions { + ($($ty:ty => $variant:ident),* $(,)?) => {$( + impl From<$ty> for WasmValue { fn from(value: $ty) -> Self { Self::Ref(RefValue::$variant(value)) } } + impl TryFrom for $ty { + type Error = (); + fn try_from(value: WasmValue) -> Result { + if let WasmValue::Ref(RefValue::$variant(value)) = value { Ok(value) } else { Err(()) } + } + } + )*}; +} + +ref_conversions!(FuncRef => Func, ExternRef => Extern, AnyRef => Any, ExnRef => Exn); + +macro_rules! any_ref_conversions { + ($($ty:ty => $cast:ident),* $(,)?) => {$( + impl From<$ty> for WasmValue { fn from(value: $ty) -> Self { Self::Ref(RefValue::Any(value.to_any())) } } + impl TryFrom for $ty { + type Error = (); + fn try_from(value: WasmValue) -> Result { + let WasmValue::Ref(RefValue::Any(value)) = value else { return Err(()) }; + value.$cast().ok_or(()) + } + } + )*}; +} + +any_ref_conversions!(EqRef => as_eq, I31Ref => as_i31, StructRef => as_struct, ArrayRef => as_array); + +macro_rules! nullable_conversions { + ($($ty:ty),* $(,)?) => {$( + impl From> for WasmValue { + fn from(value: Option<$ty>) -> Self { value.map(Into::into).unwrap_or(Self::Ref(RefValue::Null)) } + } + impl TryFrom for Option<$ty> { + type Error = (); + fn try_from(value: WasmValue) -> Result { + if matches!(value, WasmValue::Ref(RefValue::Null)) { Ok(None) } else { <$ty>::try_from(value).map(Some) } + } + } + )*}; +} + +nullable_conversions!(FuncRef, AnyRef, EqRef, I31Ref, StructRef, ArrayRef, ExternRef, ExnRef); diff --git a/crates/tinywasm/src/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs index 356304b..cd01648 100644 --- a/crates/tinywasm/src/store/const_expr.rs +++ b/crates/tinywasm/src/store/const_expr.rs @@ -2,42 +2,42 @@ use alloc::{format, vec::Vec}; use tinywasm_types::*; use super::{State, default_value}; -use crate::interpreter::{TinyWasmValue, Value128, ValueRef}; +use crate::interpreter::{RuntimeValue, Value128, ValueRef}; use crate::{Error, Result, Trap}; fn resolve(items: &[T], index: u32, kind: &str) -> Result { items.get(index as usize).copied().ok_or_else(|| Error::Other(format!("{kind} {index} not found"))) } -fn pop_value(stack: &mut Vec, storage: StorageType) -> Result { +fn 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), + (StorageType::I8, RuntimeValue::Value32(value)) => Ok(RuntimeValue::Value32(value as u8 as u32)), + (StorageType::I16, RuntimeValue::Value32(value)) => Ok(RuntimeValue::Value32(value as u16 as u32)), + (StorageType::Value(WasmType::I32 | WasmType::F32), value @ RuntimeValue::Value32(_)) + | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ RuntimeValue::Value64(_)) + | (StorageType::Value(WasmType::V128), value @ RuntimeValue::Value128(_)) + | (StorageType::Value(WasmType::Ref(_)), value @ RuntimeValue::ValueRef(_)) => Ok(value), _ => Err(Error::other("type mismatch in GC constant")), } } -fn value_ref(value: &TinyWasmValue) -> Option { +fn value_ref(value: &RuntimeValue) -> Option { match value { - TinyWasmValue::ValueRef(value) => Some(*value), + RuntimeValue::ValueRef(value) => Some(*value), _ => None, } } fn alloc_object( state: &mut State, - stack: &mut Vec, + stack: &mut Vec, type_addr: TypeAddr, - values: Vec, + values: Vec, ) -> Result<()> { - let roots = stack.iter().filter_map(value_ref).map(ValueRef::raw); + let roots = stack.iter().filter_map(value_ref); let reference = state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); + stack.push(RuntimeValue::ValueRef(reference)); Ok(()) } @@ -48,33 +48,33 @@ pub(super) fn eval_const( global_addrs: &[GlobalAddr], func_addrs: &[FuncAddr], type_addrs: &[TypeAddr], -) -> Result { +) -> Result { use ConstInstruction::*; 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(Value128(*value))), + I32Const(value) => return Ok(RuntimeValue::Value32(*value as u32)), + I64Const(value) => return Ok(RuntimeValue::Value64(*value as u64)), + F32Const(value) => return Ok(RuntimeValue::Value32(value.to_bits())), + F64Const(value) => return Ok(RuntimeValue::Value64(value.to_bits())), + V128Const(value) => return Ok(RuntimeValue::Value128(Value128(*value))), GlobalGet32(index) => { - return Ok(TinyWasmValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); + return Ok(RuntimeValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); } GlobalGet64(index) => { - return Ok(TinyWasmValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); + return Ok(RuntimeValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); } GlobalGet128(index) => { - return Ok(TinyWasmValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); + return Ok(RuntimeValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); } GlobalGetRef(index) => { let value = state.globals.get_32(resolve(global_addrs, *index, "global")?); - return Ok(TinyWasmValue::ValueRef(ValueRef::from_raw(value))); + return Ok(RuntimeValue::ValueRef(ValueRef::from_raw(value))); } - Ref(RefValue::Null) => return Ok(TinyWasmValue::ValueRef(ValueRef::NULL)), - Ref(RefValue::Func(func)) => { - let addr = resolve(func_addrs, func.addr(), "function")?; - return Ok(TinyWasmValue::ValueRef(ValueRef::from_category_addr(addr))); + RefNull(_) => return Ok(RuntimeValue::ValueRef(ValueRef::NULL)), + RefFunc(func) => { + let addr = resolve(func_addrs, func.index(), "function")?; + return Ok(RuntimeValue::ValueRef(ValueRef::from_category_addr(addr))); } _ => {} } @@ -83,62 +83,69 @@ pub(super) fn eval_const( 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(Value128(*value))), + I32Const(value) => stack.push(RuntimeValue::Value32(*value as u32)), + I64Const(value) => stack.push(RuntimeValue::Value64(*value as u64)), + F32Const(value) => stack.push(RuntimeValue::Value32(value.to_bits())), + F64Const(value) => stack.push(RuntimeValue::Value64(value.to_bits())), + V128Const(value) => stack.push(RuntimeValue::Value128(Value128(*value))), GlobalGet32(index) => { - stack.push(TinyWasmValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); + stack.push(RuntimeValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); } GlobalGet64(index) => { - stack.push(TinyWasmValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); + stack.push(RuntimeValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); } GlobalGet128(index) => { - stack.push(TinyWasmValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); + stack.push(RuntimeValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); } GlobalGetRef(index) => { let value = state.globals.get_32(resolve(global_addrs, *index, "global")?); - stack.push(TinyWasmValue::ValueRef(ValueRef::from_raw(value))); + stack.push(RuntimeValue::ValueRef(ValueRef::from_raw(value))); } - Ref(RefValue::Null) => stack.push(TinyWasmValue::ValueRef(ValueRef::NULL)), - Ref(RefValue::Func(func)) => { - let addr = resolve(func_addrs, func.addr(), "function")?; - stack.push(TinyWasmValue::ValueRef(ValueRef::from_category_addr(addr))); - } - Ref(_) => { - return cold!(Err(Error::other("unsupported reference constant"))); + RefNull(_) => stack.push(RuntimeValue::ValueRef(ValueRef::NULL)), + RefFunc(func) => { + let addr = resolve(func_addrs, func.index(), "function")?; + stack.push(RuntimeValue::ValueRef(ValueRef::from_category_addr(addr))); } RefI31 => { let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - let TinyWasmValue::Value32(value) = value else { + let RuntimeValue::Value32(value) = value else { return Err(Error::other("type mismatch in const ref.i31")); }; - stack.push(TinyWasmValue::ValueRef(ValueRef::from_i31(value as i32))); + stack.push(RuntimeValue::ValueRef(ValueRef::from_i31(value as i32))); } AnyConvertExtern | ExternConvertAny => { let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - if !matches!(value, TinyWasmValue::ValueRef(_)) { + if !matches!(value, RuntimeValue::ValueRef(_)) { return Err(Error::other("type mismatch in const reference conversion")); } stack.push(value); } StructNew(type_index) | StructNewDefault(type_index) => { let type_addr = resolve(type_addrs, *type_index, "type")?; - let fields = state + let field_count = state .get_type(type_addr) .as_struct() .ok_or_else(|| Error::other("GC constant type is not a struct"))? .fields - .as_ref(); + .len(); let default = matches!(instruction, StructNewDefault(_)); + state.check_gc_allocation(type_addr, field_count)?; let mut values = Vec::new(); - cold_err!(values.try_reserve_exact(fields.len())).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(field_count)).map_err(|_| Trap::OutOfMemory)?; if default { - values.extend(fields.iter().map(|field| default_value(field.storage))); + values.extend( + state + .get_type(type_addr) + .as_struct() + .unwrap() + .fields + .iter() + .map(|field| default_value(field.storage)), + ); } else { - for field in fields.iter().rev() { - values.push(pop_value(&mut stack, field.storage)?); + for index in (0..field_count).rev() { + let storage = state.get_type(type_addr).as_struct().unwrap().fields[index].storage; + values.push(pop_value(&mut stack, storage)?); } values.reverse(); } @@ -152,9 +159,10 @@ pub(super) fn eval_const( .ok_or_else(|| Error::other("GC constant type is not an array"))? .field .storage; - let Some(TinyWasmValue::Value32(len)) = stack.pop() else { + let Some(RuntimeValue::Value32(len)) = stack.pop() else { return Err(Error::other("type mismatch in const array length")); }; + state.check_gc_allocation(type_addr, len as usize)?; let value = if matches!(instruction, ArrayNewDefault(_)) { default_value(storage) } else { @@ -173,6 +181,7 @@ pub(super) fn eval_const( .ok_or_else(|| Error::other("GC constant type is not an array"))? .field .storage; + state.check_gc_allocation(type_addr, *len as usize)?; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(*len as usize)).map_err(|_| Trap::OutOfMemory)?; for _ in 0..*len { @@ -184,7 +193,7 @@ pub(super) fn eval_const( 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 { + let (RuntimeValue::Value32(lhs), RuntimeValue::Value32(rhs)) = (lhs, rhs) else { return cold!(Err(Error::other("type mismatch in const i32 op"))); }; let out = match instruction { @@ -193,12 +202,12 @@ pub(super) fn eval_const( I32Mul => (lhs as i32).wrapping_mul(rhs as i32), _ => unreachable!(), }; - stack.push(TinyWasmValue::Value32(out as u32)); + stack.push(RuntimeValue::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 { + let (Some(RuntimeValue::Value64(lhs)), Some(RuntimeValue::Value64(rhs))) = (lhs, rhs) else { return cold!(Err(Error::other("type mismatch in const i64 op"))); }; let out = match instruction { @@ -207,7 +216,7 @@ pub(super) fn eval_const( I64Mul => (lhs as i64).wrapping_mul(rhs as i64), _ => unreachable!(), }; - stack.push(TinyWasmValue::Value64(out as u64)); + stack.push(RuntimeValue::Value64(out as u64)); } } } diff --git a/crates/tinywasm/src/store/exception.rs b/crates/tinywasm/src/store/exception.rs deleted file mode 100644 index 0725cda..0000000 --- a/crates/tinywasm/src/store/exception.rs +++ /dev/null @@ -1,10 +0,0 @@ -use alloc::boxed::Box; -use tinywasm_types::TagAddr; - -use crate::interpreter::TinyWasmValue; - -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct ExceptionInstance { - pub(crate) tag_addr: TagAddr, - pub(crate) payload: Box<[TinyWasmValue]>, -} diff --git a/crates/tinywasm/src/store/function.rs b/crates/tinywasm/src/store/function.rs index 3580e9d..3c716a7 100644 --- a/crates/tinywasm/src/store/function.rs +++ b/crates/tinywasm/src/store/function.rs @@ -10,17 +10,9 @@ use crate::func::HostFunction; #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct FunctionInstance { pub(crate) type_addr: TypeAddr, - pub(crate) gc: FunctionGcMetadata, pub(crate) kind: FunctionKind, } -#[derive(Clone, Copy)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct FunctionGcMetadata { - pub(crate) params: bool, - pub(crate) results: bool, -} - #[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) enum FunctionKind { diff --git a/crates/tinywasm/src/store/gc/mod.rs b/crates/tinywasm/src/store/gc/mod.rs index 6379357..152d651 100644 --- a/crates/tinywasm/src/store/gc/mod.rs +++ b/crates/tinywasm/src/store/gc/mod.rs @@ -1,58 +1,57 @@ mod arena; mod object; +mod roots; use alloc::vec::Vec; +use core::ops::Range; use tinywasm_types::{StorageType, WasmType}; use crate::Trap; use crate::interpreter::stack::ValueStack; -use crate::interpreter::{InternalValue, TinyWasmValue, Value128, ValueRef}; +use crate::interpreter::{InternalValue, RuntimeValue, Value128, ValueRef}; pub(crate) use arena::{AllocError, Arena, Handle, Trace}; -pub(crate) use object::{GcHeap, GcObject}; +pub(crate) use object::{GcHeap, GcObjectKind}; +pub(crate) use roots::Roots; /// Returns the zero value for a GC field or array element. -pub(crate) fn default_value(storage: StorageType) -> TinyWasmValue { +pub(crate) fn default_value(storage: StorageType) -> RuntimeValue { match storage { StorageType::I8 | StorageType::I16 | StorageType::Value(WasmType::I32 | WasmType::F32) => { - TinyWasmValue::Value32(0) + RuntimeValue::Value32(0) } - StorageType::Value(WasmType::I64 | WasmType::F64) => TinyWasmValue::Value64(0), - StorageType::Value(WasmType::V128) => TinyWasmValue::Value128(Value128([0; 16])), - StorageType::Value(WasmType::Ref(_)) => TinyWasmValue::ValueRef(ValueRef::NULL), + StorageType::Value(WasmType::I64 | WasmType::F64) => RuntimeValue::Value64(0), + StorageType::Value(WasmType::V128) => RuntimeValue::Value128(Value128([0; 16])), + StorageType::Value(WasmType::Ref(_)) => RuntimeValue::ValueRef(ValueRef::NULL), } } /// Pops and packs a GC field or array element from the operand stack. -pub(crate) fn pop_value(stack: &mut ValueStack, storage: StorageType) -> TinyWasmValue { +pub(crate) fn pop_value(stack: &mut ValueStack, storage: StorageType) -> RuntimeValue { match storage { - StorageType::I8 => TinyWasmValue::Value32(i32::stack_pop(stack) as u8 as u32), - StorageType::I16 => TinyWasmValue::Value32(i32::stack_pop(stack) as u16 as u32), - StorageType::Value(WasmType::I32 | WasmType::F32) => TinyWasmValue::Value32(u32::stack_pop(stack)), - StorageType::Value(WasmType::I64 | WasmType::F64) => TinyWasmValue::Value64(u64::stack_pop(stack)), - StorageType::Value(WasmType::V128) => TinyWasmValue::Value128(Value128::stack_pop(stack)), - StorageType::Value(WasmType::Ref(_)) => TinyWasmValue::ValueRef(ValueRef::stack_pop(stack)), + StorageType::I8 => RuntimeValue::Value32(i32::stack_pop(stack) as u8 as u32), + StorageType::I16 => RuntimeValue::Value32(i32::stack_pop(stack) as u16 as u32), + StorageType::Value(WasmType::I32 | WasmType::F32) => RuntimeValue::Value32(u32::stack_pop(stack)), + StorageType::Value(WasmType::I64 | WasmType::F64) => RuntimeValue::Value64(u64::stack_pop(stack)), + StorageType::Value(WasmType::V128) => RuntimeValue::Value128(Value128::stack_pop(stack)), + StorageType::Value(WasmType::Ref(_)) => RuntimeValue::ValueRef(ValueRef::stack_pop(stack)), } } /// Extends a packed value and pushes it onto the operand stack. pub(crate) fn push_value( stack: &mut ValueStack, - value: TinyWasmValue, + value: RuntimeValue, storage: StorageType, signed: Option, ) -> Result<(), Trap> { let value = match (value, storage, signed) { - (TinyWasmValue::Value32(value), StorageType::I8, Some(true)) => { - TinyWasmValue::Value32(value as i8 as i32 as u32) - } - (TinyWasmValue::Value32(value), StorageType::I16, Some(true)) => { - TinyWasmValue::Value32(value as i16 as i32 as u32) - } - (TinyWasmValue::Value32(value), StorageType::I8, Some(false)) => TinyWasmValue::Value32(value & u8::MAX as u32), - (TinyWasmValue::Value32(value), StorageType::I16, Some(false)) => { - TinyWasmValue::Value32(value & u16::MAX as u32) + (RuntimeValue::Value32(value), StorageType::I8, Some(true)) => RuntimeValue::Value32(value as i8 as i32 as u32), + (RuntimeValue::Value32(value), StorageType::I16, Some(true)) => { + RuntimeValue::Value32(value as i16 as i32 as u32) } + (RuntimeValue::Value32(value), StorageType::I8, Some(false)) => RuntimeValue::Value32(value & u8::MAX as u32), + (RuntimeValue::Value32(value), StorageType::I16, Some(false)) => RuntimeValue::Value32(value & u16::MAX as u32), (value, _, None) => value, _ => unreachable!("validated packed field access"), }; @@ -60,12 +59,12 @@ pub(crate) fn push_value( } /// Decodes numeric array elements from a data segment. -pub(crate) fn decode_data( +pub(crate) fn data_range( storage: StorageType, data: &[u8], src: usize, len: usize, -) -> Result, Trap> { +) -> Result<(Range, usize), Trap> { let width = match storage { StorageType::I8 => 1, StorageType::I16 => 2, @@ -78,14 +77,25 @@ pub(crate) fn decode_data( else { return Err(Trap::MemoryOutOfBounds { offset: src, len: len.saturating_mul(width), max: data.len() }); }; + Ok((src..end, width)) +} + +/// Decodes numeric array elements from a data segment. +pub(crate) fn decode_data( + storage: StorageType, + data: &[u8], + src: usize, + len: usize, +) -> Result, Trap> { + let (range, width) = data_range(storage, data, src, len)?; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; - values.extend(data[src..end].chunks_exact(width).map(|bytes| match width { - 1 => TinyWasmValue::Value32(u32::from(bytes[0])), - 2 => TinyWasmValue::Value32(u32::from(u16::from_le_bytes(bytes.try_into().unwrap()))), - 4 => TinyWasmValue::Value32(u32::from_le_bytes(bytes.try_into().unwrap())), - 8 => TinyWasmValue::Value64(u64::from_le_bytes(bytes.try_into().unwrap())), - 16 => TinyWasmValue::Value128(Value128(<[u8; 16]>::try_from(bytes).unwrap())), + values.extend(data[range].chunks_exact(width).map(|bytes| match width { + 1 => RuntimeValue::Value32(u32::from(bytes[0])), + 2 => RuntimeValue::Value32(u32::from(u16::from_le_bytes(bytes.try_into().unwrap()))), + 4 => RuntimeValue::Value32(u32::from_le_bytes(bytes.try_into().unwrap())), + 8 => RuntimeValue::Value64(u64::from_le_bytes(bytes.try_into().unwrap())), + 16 => RuntimeValue::Value128(Value128(<[u8; 16]>::try_from(bytes).unwrap())), _ => unreachable!(), })); Ok(values) diff --git a/crates/tinywasm/src/store/gc/object.rs b/crates/tinywasm/src/store/gc/object.rs index ca22338..cf27cd5 100644 --- a/crates/tinywasm/src/store/gc/object.rs +++ b/crates/tinywasm/src/store/gc/object.rs @@ -1,12 +1,11 @@ use alloc::{boxed::Box, sync::Arc, vec::Vec}; -use core::cell::RefCell; use core::mem::size_of; use core::sync::atomic::{AtomicU32, Ordering}; -use tinywasm_types::TypeAddr; +use tinywasm_types::{TagAddr, TypeAddr}; use crate::engine::Config; -use crate::interpreter::{TinyWasmValue, ValueRef}; +use crate::interpreter::{RuntimeValue, ValueRef}; use crate::{ResourceLimiter, Trap}; use super::{AllocError, Arena, Handle, Trace}; @@ -14,11 +13,17 @@ use super::{AllocError, Arena, Handle, Trace}; static NEXT_GC_REF: AtomicU32 = AtomicU32::new(0); pub(crate) struct GcObject { - pub(crate) type_addr: TypeAddr, - pub(crate) values: Box<[TinyWasmValue]>, + pub(crate) kind: GcObjectKind, + pub(crate) values: Box<[RuntimeValue]>, references: Option]>>, } +#[derive(Clone, Copy)] +pub(crate) enum GcObjectKind { + Composite(TypeAddr), + Exception(TagAddr), +} + impl Trace for GcObject { fn trace(&self, mark: &mut impl FnMut(Handle)) { if let Some(references) = &self.references { @@ -30,7 +35,6 @@ impl Trace for GcObject { pub(crate) struct GcHeap { objects: Arena, directory: Vec<(u32, Handle)>, - pinned: RefCell>, resource_limiter: Option>, } @@ -46,7 +50,6 @@ impl GcHeap { Self { objects: Arena::new(config.gc_collection_threshold), directory: Vec::new(), - pinned: RefCell::new(Vec::new()), resource_limiter: config.resource_limiter.clone(), } } @@ -65,19 +68,13 @@ impl GcHeap { } #[inline] - pub(crate) fn get_mut(&mut self, value: ValueRef) -> Option<&mut GcObject> { - self.objects.get_mut(self.handle(value)?) + pub(crate) fn get_handle(&self, handle: Handle) -> Option<&GcObject> { + self.objects.get(handle) } - /// Allocates an object and returns its compact runtime reference. - pub(crate) fn alloc( - &mut self, - type_addr: TypeAddr, - values: Vec, - trace_references: bool, - ) -> 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)?; + pub(crate) fn check_allocation(&self, value_count: usize, trace_references: bool) -> Result<(), Trap> { + let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; + let out_of_line_bytes = value_count.checked_mul(element_size).ok_or(Trap::OutOfMemory)?; let allocation_size = Arena::::allocation_size(out_of_line_bytes).ok_or(Trap::OutOfMemory)?; let desired = self.objects.allocated_bytes.checked_add(allocation_size).ok_or(Trap::OutOfMemory)?; if let Some(limiter) = &self.resource_limiter @@ -85,7 +82,38 @@ impl GcHeap { { return Err(Trap::OutOfMemory); } + Ok(()) + } + + /// Allocates an object and returns its compact runtime reference. + pub(crate) fn alloc( + &mut self, + type_addr: TypeAddr, + values: Vec, + trace_references: bool, + ) -> Result { + self.alloc_kind(GcObjectKind::Composite(type_addr), values, trace_references, None) + } + + /// Allocates an exception and traces references in its payload. + pub(crate) fn alloc_exception( + &mut self, + tag_addr: TagAddr, + payload: Vec, + trace_fields: &[bool], + ) -> Result { + self.alloc_kind(GcObjectKind::Exception(tag_addr), payload, true, Some(trace_fields)) + } + fn alloc_kind( + &mut self, + kind: GcObjectKind, + values: Vec, + trace_references: bool, + trace_fields: Option<&[bool]>, + ) -> 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 { @@ -94,27 +122,27 @@ impl GcHeap { let references = if trace_references { let mut references = Vec::new(); references.try_reserve_exact(values.len()).map_err(|_| Trap::OutOfMemory)?; - references.extend(values.iter().map(|value| match value { - TinyWasmValue::ValueRef(value) => self.handle(*value), + references.extend(values.iter().enumerate().map(|(index, value)| match value { + RuntimeValue::ValueRef(value) if trace_fields.is_none_or(|fields| fields[index]) => self.handle(*value), _ => None, })); Some(references.into_boxed_slice()) } else { None }; - let object = GcObject { type_addr, values: values.into_boxed_slice(), references }; + let object = GcObject { kind, values: values.into_boxed_slice(), references }; self.directory.try_reserve(1).map_err(|_| Trap::OutOfMemory)?; let handle = self.objects.alloc(object, out_of_line_bytes).map_err(|_| Trap::OutOfMemory)?; self.directory.push((key, handle)); Ok(ValueRef::from_category_addr(key)) } - pub(crate) fn set(&mut self, object: ValueRef, index: usize, value: TinyWasmValue) -> Option<()> { + pub(crate) fn set(&mut self, object: Handle, index: usize, value: RuntimeValue) -> Option<()> { let reference = match value { - TinyWasmValue::ValueRef(value) => self.handle(value), + RuntimeValue::ValueRef(value) => self.handle(value), _ => None, }; - let object = self.get_mut(object)?; + let object = self.objects.get_mut(object)?; *object.values.get_mut(index)? = value; if let Some(references) = &mut object.references { references[index] = reference; @@ -123,20 +151,17 @@ impl GcHeap { } /// Replaces a contiguous range and updates its traced references. - pub(crate) fn set_slice(&mut self, object: ValueRef, index: usize, values: &[TinyWasmValue]) -> Option<()> { - let object_handle = self.handle(object)?; + pub(crate) fn set_slice(&mut self, object: Handle, index: usize, values: &[RuntimeValue]) -> Option<()> { let end = index.checked_add(values.len())?; let directory = &self.directory; - let object = self.objects.get_mut(object_handle)?; + let object = self.objects.get_mut(object)?; object.values.get_mut(index..end)?.copy_from_slice(values); if let Some(references) = &mut object.references { for (reference, value) in references[index..end].iter_mut().zip(values) { *reference = match value { - TinyWasmValue::ValueRef(value) => { - let key = value.addr(); - key.and_then(|key| directory.binary_search_by_key(&key, |entry| entry.0).ok()) - .map(|index| directory[index].1) - } + RuntimeValue::ValueRef(value) => value.addr().and_then(|key| { + directory.binary_search_by_key(&key, |entry| entry.0).ok().map(|index| directory[index].1) + }), _ => None, }; } @@ -145,17 +170,12 @@ impl GcHeap { } /// Fills a contiguous range and updates its traced references. - pub(crate) fn fill( - &mut self, - object: ValueRef, - range: core::ops::Range, - value: TinyWasmValue, - ) -> Option<()> { + pub(crate) fn fill(&mut self, object: Handle, range: core::ops::Range, value: RuntimeValue) -> Option<()> { let reference = match value { - TinyWasmValue::ValueRef(value) => self.handle(value), + RuntimeValue::ValueRef(value) => self.handle(value), _ => None, }; - let object = self.get_mut(object)?; + let object = self.objects.get_mut(object)?; object.values.get_mut(range.clone())?.fill(value); if let Some(references) = &mut object.references { references[range].fill(reference); @@ -164,36 +184,24 @@ impl GcHeap { } pub(crate) fn should_collect(&self, value_count: usize, trace_references: bool) -> bool { - let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; + let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; self.objects.should_collect(value_count.saturating_mul(element_size)) } - /// Reclaims objects unreachable from runtime and permanent host roots. + /// Reclaims objects unreachable from runtime roots. pub(crate) fn collect(&mut self, roots: impl IntoIterator) -> Result<(), AllocError> { - let pinned = self.pinned.borrow(); let directory = &self.directory; let root_handles = roots.into_iter().filter_map(|value| { let key = value.addr()?; Some(directory.get(directory.binary_search_by_key(&key, |entry| entry.0).ok()?)?.1) }); - self.objects.collect(pinned.iter().copied().chain(root_handles))?; - drop(pinned); + self.objects.collect(root_handles)?; self.directory.retain(|(_, handle)| self.objects.get(*handle).is_some()); Ok(()) } - /// Permanently roots a managed reference exposed through the copyable host API. - pub(crate) fn pin(&self, value: ValueRef) { - if let Some(handle) = self.handle(value) { - let mut pinned = self.pinned.borrow_mut(); - if let Err(index) = pinned.binary_search(&handle) { - pinned.insert(index, handle); - } - } - } - - pub(crate) fn copy_within(&mut self, object: ValueRef, src: core::ops::Range, dst: usize) -> Option<()> { - let object = self.get_mut(object)?; + pub(crate) fn copy_within(&mut self, object: Handle, src: core::ops::Range, dst: usize) -> Option<()> { + let object = self.objects.get_mut(object)?; object.values.copy_within(src.clone(), dst); if let Some(references) = &mut object.references { references.copy_within(src, dst); @@ -204,13 +212,11 @@ impl GcHeap { /// Copies values and tracing metadata between two distinct objects. pub(crate) fn copy_between( &mut self, - src: ValueRef, + src: Handle, src_range: core::ops::Range, - dst: ValueRef, + dst: Handle, dst_index: usize, ) -> Option<()> { - let src = self.handle(src)?; - let dst = self.handle(dst)?; let (src, dst) = self.objects.get_disjoint_mut(src, dst)?; let src_values = src.values.get(src_range.clone())?; let dst_end = dst_index.checked_add(src_values.len())?; @@ -254,13 +260,27 @@ mod tests { #[test] fn collection_reclaims_object_cycles() { let mut heap = GcHeap::default(); - let first = heap.alloc(0, alloc::vec![TinyWasmValue::ValueRef(ValueRef::NULL)], true).unwrap(); - let second = heap.alloc(0, alloc::vec![TinyWasmValue::ValueRef(first)], true).unwrap(); - heap.set(first, 0, TinyWasmValue::ValueRef(second)).unwrap(); + let first = heap.alloc(0, alloc::vec![RuntimeValue::ValueRef(ValueRef::NULL)], true).unwrap(); + let second = heap.alloc(0, alloc::vec![RuntimeValue::ValueRef(first)], true).unwrap(); + heap.set(heap.handle(first).unwrap(), 0, RuntimeValue::ValueRef(second)).unwrap(); heap.collect([]).unwrap(); assert!(heap.get(first).is_none()); assert!(heap.get(second).is_none()); } + + #[test] + fn exception_payload_traces_managed_objects() { + let mut heap = GcHeap::default(); + let payload = heap.alloc(0, Vec::new(), false).unwrap(); + let exception = heap.alloc_exception(0, alloc::vec![RuntimeValue::ValueRef(payload)], &[true]).unwrap(); + + heap.collect([exception]).unwrap(); + assert!(heap.get(payload).is_some()); + + heap.collect([]).unwrap(); + assert!(heap.get(exception).is_none()); + assert!(heap.get(payload).is_none()); + } } diff --git a/crates/tinywasm/src/store/gc/roots.rs b/crates/tinywasm/src/store/gc/roots.rs new file mode 100644 index 0000000..7107295 --- /dev/null +++ b/crates/tinywasm/src/store/gc/roots.rs @@ -0,0 +1,58 @@ +use alloc::{sync::Arc, sync::Weak, vec::Vec}; + +use crate::Trap; +use crate::interpreter::ValueRef; + +pub(crate) struct Roots { + entries: Vec>, + free: Vec, +} + +struct Root { + value: ValueRef, + token: Weak<()>, +} + +impl Roots { + pub(crate) const fn new() -> Self { + Self { entries: Vec::new(), free: Vec::new() } + } + + pub(crate) fn reserve(&mut self, additional: usize) -> Result<(), Trap> { + self.remove_dead(); + let needed = additional.saturating_sub(self.free.len()); + self.entries.try_reserve(needed).map_err(|_| Trap::OutOfMemory) + } + + pub(crate) fn insert(&mut self, value: ValueRef) -> Result, Trap> { + if self.free.is_empty() && self.entries.len() == self.entries.capacity() { + self.remove_dead(); + } + let index = if let Some(index) = self.free.pop() { + index + } else { + let index = u32::try_from(self.entries.len()).map_err(|_| Trap::OutOfMemory)?; + self.entries.try_reserve(1).map_err(|_| Trap::OutOfMemory)?; + self.entries.push(None); + index + }; + + let token = Arc::new(()); + self.entries[index as usize] = Some(Root { value, token: Arc::downgrade(&token) }); + Ok(token) + } + + pub(crate) fn values(&mut self) -> impl Iterator + '_ { + self.remove_dead(); + self.entries.iter().flatten().map(|root| root.value) + } + + fn remove_dead(&mut self) { + for (index, root) in self.entries.iter_mut().enumerate() { + if root.as_ref().is_some_and(|root| root.token.strong_count() == 0) { + *root = None; + self.free.push(index as u32); + } + } + } +} diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index 69e538f..4052eb8 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -1,7 +1,7 @@ use alloc::vec::Vec; use tinywasm_types::*; -use crate::interpreter::{TinyWasmValue, Value32, Value64, Value128}; +use crate::interpreter::{RuntimeValue, Value32, Value64, Value128}; struct GlobalLane { values: Vec, @@ -98,18 +98,18 @@ impl Globals { } /// Adds a global and returns its packed store address. - pub(crate) fn push(&mut self, ty: GlobalType, value: TinyWasmValue) -> GlobalAddr { + pub(crate) fn push(&mut self, ty: GlobalType, value: RuntimeValue) -> GlobalAddr { match (ty.ty, value) { - (WasmType::I32 | WasmType::F32, TinyWasmValue::Value32(value)) => { + (WasmType::I32 | WasmType::F32, RuntimeValue::Value32(value)) => { Self::addr(Self::LANE_32, self.globals_32.push(ty, value)) } - (WasmType::Ref(_), TinyWasmValue::ValueRef(value)) => { + (WasmType::Ref(_), RuntimeValue::ValueRef(value)) => { Self::addr(Self::LANE_32, self.globals_32.push(ty, value.raw())) } - (WasmType::I64 | WasmType::F64, TinyWasmValue::Value64(value)) => { + (WasmType::I64 | WasmType::F64, RuntimeValue::Value64(value)) => { Self::addr(Self::LANE_64, self.globals_64.push(ty, value)) } - (WasmType::V128, TinyWasmValue::Value128(value)) => { + (WasmType::V128, RuntimeValue::Value128(value)) => { Self::addr(Self::LANE_128, self.globals_128.push(ty, value)) } _ => unreachable!("global value does not match its declared type"), diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 2ddd43c..91895b4 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -1,17 +1,16 @@ use alloc::{boxed::Box, format, vec::Vec}; use core::hint::cold_path; -use core::sync::atomic::{AtomicU32, Ordering}; use tinywasm_types::*; use crate::func::FromWasmValues; use crate::interpreter::stack::{CallStack, StackBase, ValueStack}; -use crate::interpreter::{TinyWasmValue, ValueRef}; -use crate::{Engine, Error, ModuleInstance, Result, Trap}; +use crate::interpreter::{RuntimeValue, ValueRef}; +use crate::reference::{ReferentKind, RootedItem, StoreId, StoredRef}; +use crate::{Engine, Error, ExnRef, FuncRef, ModuleInstance, RefValue, Result, Trap, WasmValue}; mod const_expr; mod data; mod element; -mod exception; mod function; mod gc; mod global; @@ -22,22 +21,24 @@ mod tag; mod types; use const_expr::eval_const; -pub(crate) use gc::{decode_data, default_value, pop_value, push_value}; +pub(crate) use gc::{GcObjectKind, data_range, decode_data, default_value, pop_value, push_value}; pub(crate) use memory::{MemValue, MemoryInstance}; pub(crate) use state::State; pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; -pub(crate) use {data::*, element::*, exception::*, function::*, global::*, table::*, tag::*}; +pub(crate) use {data::*, element::*, function::*, global::*, table::*, tag::*}; -// global store id counter -static STORE_ID: AtomicU32 = AtomicU32::new(0); - -/// Controls resource usage by WebAssembly instances. +/// Controls selected allocation requests from WebAssembly instances. /// /// Configure a limiter with -/// [`Config::with_resource_limiter`](crate::engine::Config::with_resource_limiter). It currently -/// controls guest linear-memory, table, and GC heap growth. It does not account for stacks, runtime +/// [`Config::with_resource_limiter`](crate::engine::Config::with_resource_limiter). The callbacks +/// cover linear memory, tables, and the logical GC heap. They do not account for stacks, runtime /// metadata, temporary buffers, backing-capacity overhead, or other host allocations. /// +/// `Ok(true)` allows an allocation attempt, `Ok(false)` rejects it, and `Err` returns the supplied +/// trap. Allowing a request does not guarantee that the backing allocation will succeed. Rejected +/// growth uses the operation's normal failed-growth result. Rejected initial allocation and GC +/// allocation produce [`Trap::OutOfMemory`]. +/// /// # Example /// ```rust /// use std::sync::Arc; @@ -60,17 +61,17 @@ static STORE_ID: AtomicU32 = AtomicU32::new(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))?; +/// let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; /// assert_eq!(memory.grow(&mut store, 1)?, None); /// # Ok::<(), tinywasm::Error>(()) /// ``` pub trait ResourceLimiter: Send + Sync { - /// Returns whether a memory allocation or growth is allowed. + /// Checks a nonzero memory allocation or growth request. /// - /// 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. + /// Sizes are in bytes. `current` is zero for initial allocation. `maximum` is the declared + /// maximum in bytes, saturated to `usize::MAX` if needed, or `None` if no maximum was declared. + /// Growth limits are checked before this callback. The default implementation allows the + /// request. fn memory_growing( &self, _current: usize, @@ -80,12 +81,11 @@ pub trait ResourceLimiter: Send + Sync { Ok(true) } - /// Returns whether a table allocation or growth is allowed. + /// Checks a nonzero table allocation or growth request. /// - /// 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. + /// Sizes are in elements. `current` is zero for initial allocation. `maximum` is the declared + /// maximum element count when it fits `usize`, or `None` otherwise. Table limits are checked + /// before this callback. The default implementation allows the request. fn table_growing( &self, _current: usize, @@ -95,11 +95,12 @@ pub trait ResourceLimiter: Send + Sync { Ok(true) } - /// Returns whether a GC object allocation is allowed. + /// Checks a GC object allocation request. /// - /// Sizes are the logical bytes retained by live GC objects after collection. `maximum` is - /// currently always `None`. `Ok(false)` rejects the allocation with [`Trap::OutOfMemory`], while - /// `Err` returns the provided trap. The default implementation allows the request. + /// Sizes are the current TinyWasm-accounted heap bytes and that count plus the requested + /// allocation. They include unreachable objects until collection but not all allocator + /// overhead. `maximum` is currently always `None`. This callback runs before threshold-triggered + /// collection. fn gc_growing( &self, _current: usize, @@ -122,9 +123,9 @@ pub trait ResourceLimiter: Send + Sync { /// # _ = store; /// ``` /// -/// See +/// See pub struct Store { - id: u32, + id: StoreId, pub(crate) module_instances: Vec, pub(crate) engine: Engine, @@ -133,9 +134,74 @@ pub struct Store { pub(crate) state: State, pub(crate) call_stack: CallStack, pub(crate) value_stack: ValueStack, - pub(crate) host_params: Vec, + value_scratch: ValueScratch, +} + +#[derive(Default)] +struct ValueScratch(Vec); + +impl ValueScratch { + fn take_resized(&mut self, len: usize) -> Result> { + self.0.clear(); + self.0.try_reserve(len).map_err(|_| Trap::OutOfMemory)?; + self.0.resize(len, WasmValue::I32(0)); + Ok(core::mem::take(&mut self.0)) + } + + fn restore(&mut self, mut values: Vec) { + values.clear(); + if values.capacity() > self.0.capacity() { + self.0 = values; + } + } +} + +#[derive(Clone, Copy)] +pub(crate) enum FuncValueTypes { + Params, + Results, +} + +pub(crate) struct StackValueIter<'a> { + store: &'a mut Store, + type_addr: TypeAddr, + types: FuncValueTypes, + index: StackBase, + position: usize, + len: usize, } +impl Iterator for StackValueIter<'_> { + type Item = WasmValue; + + fn next(&mut self) -> Option { + if self.position == self.len { + return None; + } + let ty = { + let func_ty = self.store.state.get_canonical_func_type(self.type_addr); + match self.types { + FuncValueTypes::Params => func_ty.params()[self.position], + FuncValueTypes::Results => func_ty.results()[self.position], + } + }; + self.position += 1; + let value = self.store.stack_value(ty, &mut self.index); + Some( + value + .into_wasm(self.store, ty) + .unwrap_or_else(|_| unreachable!("invalid internal value at a typed host boundary")), + ) + } + + fn size_hint(&self) -> (usize, Option) { + let remaining = self.len - self.position; + (remaining, Some(remaining)) + } +} + +impl ExactSizeIterator for StackValueIter<'_> {} + #[cfg(feature = "debug")] impl core::fmt::Debug for Store { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { @@ -162,8 +228,7 @@ impl Default for Store { impl Store { /// Create a new store pub fn new(engine: Engine) -> Self { - let id = - STORE_ID.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)).expect("too many stores"); + let id = StoreId::fresh(); let state = State::new(engine.config()); Self { id, @@ -171,7 +236,7 @@ impl Store { state, call_stack: CallStack::new(engine.config()), value_stack: ValueStack::new(engine.config()), - host_params: Vec::new(), + value_scratch: ValueScratch::default(), engine, execution_fuel: 0, execution_active: false, @@ -180,9 +245,166 @@ 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 { self.id } + pub(crate) fn with_scratch_values( + &mut self, + len: usize, + use_values: impl FnOnce(&mut Self, &mut Vec) -> Result, + ) -> Result { + let mut values = self.value_scratch.take_resized(len)?; + let result = use_values(self, &mut values); + self.value_scratch.restore(values); + result + } + + pub(crate) fn root_reference(&mut self, value: ValueRef, kind: ReferentKind) -> Result { + let token = match kind { + ReferentKind::Struct | ReferentKind::Array | ReferentKind::Exception => { + Some(self.state.roots.insert(value)?) + } + ReferentKind::I31 | ReferentKind::HostExtern => None, + }; + Ok(T::from_rooted_item(RootedItem { store: self.id, value, kind, _token: token })) + } + + pub(crate) fn root_exception(&mut self, value: ValueRef) -> Result { + if !matches!(self.state.gc.get(value).map(|object| object.kind), Some(gc::GcObjectKind::Exception(_))) { + return Err(Trap::InvalidReference.into()); + } + self.root_reference(value, ReferentKind::Exception) + } + + pub(crate) fn resolve_ref(&self, reference: &T) -> Result { + let item = reference.rooted_item(); + if item.store != self.id { + return Err(Trap::InvalidStore); + } + Ok(item.value) + } + + pub(crate) fn encode_ref(&self, value: &RefValue) -> Result { + Ok(match value { + RefValue::Null => ValueRef::NULL, + RefValue::Func(value) => ValueRef::from_category_addr(value.addr(self.id).ok_or(Trap::InvalidStore)?), + RefValue::Any(value) => self.resolve_ref(value)?, + RefValue::Extern(value) => self.resolve_ref(value)?, + RefValue::Exn(value) => self.resolve_ref(value)?, + }) + } + + pub(crate) fn decode_ref(&mut self, value: ValueRef, ty: RefType) -> Result { + if value.is_null() { + return Ok(RefValue::Null); + } + if ty.type_index().is_some_and(|addr| self.state.get_type(addr).as_func().is_some()) || ty.is_func() { + return Ok(RefValue::Func(FuncRef::new(self.id, value.addr().ok_or(Trap::InvalidReference)?))); + } + if ty.is_exn() { + return self.root_exception(value).map(RefValue::Exn); + } + let kind = if value.is_i31() { + ReferentKind::I31 + } else if value.is_host_any() { + ReferentKind::HostExtern + } else { + match self.state.gc.get(value).map(|object| object.kind) { + Some(gc::GcObjectKind::Composite(type_addr)) => match &self.state.get_type(type_addr).composite { + CompositeType::Struct(_) => ReferentKind::Struct, + CompositeType::Array(_) => ReferentKind::Array, + CompositeType::Func(_) => return Err(Trap::InvalidReference.into()), + }, + _ => return Err(Trap::InvalidReference.into()), + } + }; + if ty.is_extern() { + Ok(RefValue::Extern(self.root_reference(value, kind)?)) + } else { + Ok(RefValue::Any(self.root_reference(value, kind)?)) + } + } + + fn stack_value(&self, ty: WasmType, index: &mut StackBase) -> RuntimeValue { + match ty { + WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => { + let value = *self.value_stack.stack_32.get(index.s32 as usize); + index.s32 += 1; + if matches!(ty, WasmType::Ref(_)) { + RuntimeValue::ValueRef(ValueRef::from_raw(value)) + } else { + RuntimeValue::Value32(value) + } + } + WasmType::I64 | WasmType::F64 => { + let value = *self.value_stack.stack_64.get(index.s64 as usize); + index.s64 += 1; + RuntimeValue::Value64(value) + } + WasmType::V128 => { + let value = *self.value_stack.stack_128.get(index.s128 as usize); + index.s128 += 1; + RuntimeValue::Value128(value) + } + } + } + + pub(crate) fn stack_value_iter( + &mut self, + type_addr: TypeAddr, + types: FuncValueTypes, + index: StackBase, + ) -> Result, Trap> { + let canonical = self.state.get_canonical_func_type(type_addr); + let canonical = match types { + FuncValueTypes::Params => canonical.params(), + FuncValueTypes::Results => canonical.results(), + }; + let len = canonical.len(); + let reference_count = canonical.iter().filter(|ty| matches!(ty, WasmType::Ref(_))).count(); + self.state.roots.reserve(reference_count)?; + Ok(StackValueIter { store: self, type_addr, types, index, position: 0, len }) + } + + pub(crate) fn push_wasm_values(&mut self, values: impl IntoIterator) -> Result<()> { + for value in values { + let value = value.to_runtime(self)?; + self.value_stack.push_dyn(value)?; + } + Ok(()) + } + + pub(crate) fn pop_stack_values(&mut self, types: &[WasmType], results: &mut [WasmValue]) -> Result<()> { + if types.len() != results.len() { + return Err(Error::other("result buffer has the wrong length")); + } + let base = self.value_stack.base_before(types.iter().collect()); + let result = (|| { + let mut index = base; + for (&ty, result) in types.iter().zip(results) { + let value = self.stack_value(ty, &mut index); + *result = value.into_wasm(self, ty)?; + } + Ok(()) + })(); + self.value_stack.truncate_to_base(base); + result + } + + /// Reclaims unreachable managed objects. + /// + /// Globals, tables, operand stacks, and owned host references are traced as + /// roots. Objects also become eligible for automatic threshold collection + /// after the last owned handle is dropped. + pub fn gc(&mut self) -> Result<()> { + let stack_roots = self.value_stack.stack_32.into_iter().copied().map(ValueRef::from_raw).collect::>(); + self.state.collect_gc(stack_roots).map_err(|_| Trap::OutOfMemory.into()) + } + /// 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) @@ -197,10 +419,27 @@ impl Store { self.module_instances.push(instance); } - /// Returns whether a public value has the requested runtime type. - #[doc(hidden)] - pub fn value_matches_type(&self, value: WasmValue, ty: WasmType) -> bool { - self.state.value_matches_type(value, ty) + pub(crate) fn value_matches_type(&self, value: &WasmValue, ty: WasmType) -> bool { + let (WasmValue::Ref(value), WasmType::Ref(expected)) = (value, ty) else { + return value.matches_type(ty); + }; + let category_matches = match value { + RefValue::Null => return expected.is_nullable(), + RefValue::Func(_) => { + expected.is_func() + || expected.type_index().is_some_and(|addr| self.state.get_type(addr).as_func().is_some()) + } + RefValue::Extern(_) => expected.is_extern(), + RefValue::Exn(_) => expected.is_exn(), + RefValue::Any(_) => !expected.is_func() && !expected.is_extern() && !expected.is_exn(), + }; + if !category_matches { + return false; + } + match self.encode_ref(value) { + Ok(value) => self.state.value_ref_matches(value, expected), + _ => false, + } } /// Marks the store as executing and rejects nested root calls. @@ -233,10 +472,11 @@ impl Store { 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) { + let internal = value.to_runtime(self)?; + if !self.value_matches_type(&value, ty) { return Err(Error::other("typed function value does not match its signature")); } - self.value_stack.extend_wasmvalues(core::iter::once(value))?; + self.value_stack.push_dyn(internal)?; } if values.next().is_some() { return Err(Error::other("too many typed function values")); @@ -254,18 +494,11 @@ impl Store { &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); + let result = { + let mut values = self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base)?; + R::from_wasm_values_exact(&mut values) + }; self.value_stack.truncate_to_base(stack_base); result } @@ -283,11 +516,9 @@ 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, - gc: self.state.func_gc_metadata(type_addr), - kind: FunctionKind::Wasm(WasmFunctionInstance { func, owner }), - }); + self.state + .funcs + .push(FunctionInstance { type_addr, kind: FunctionKind::Wasm(WasmFunctionInstance { func, owner }) }); } start..start + funcs.len() as FuncAddr } @@ -318,7 +549,7 @@ impl Store { for table in tables { let init = match &table.init { Some(expr) => match eval_const(&mut self.state, expr, global_addrs, func_addrs, type_addrs)? { - TinyWasmValue::ValueRef(value) => value, + RuntimeValue::ValueRef(value) => value, _ => return Err(Error::other("table initializer is not a reference value")), }, None => ValueRef::NULL, @@ -374,7 +605,7 @@ impl Store { ) -> Result { match item { ElementItem::Expr(expr) => match eval_const(&mut self.state, expr, globals, funcs, type_addrs)? { - TinyWasmValue::ValueRef(value) => Ok(value), + RuntimeValue::ValueRef(value) => Ok(value), other => { cold_path(); Err(Error::Other(format!("expected ref type, got {other:?}"))) @@ -426,8 +657,8 @@ impl Store { // this one is active, so we need to initialize it (essentially a `table.init` instruction) ElementKind::Active { offset, table } => { 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, + RuntimeValue::Value32(value) => u64::from(value), + RuntimeValue::Value64(value) => value, other => return Err(Error::Other(format!("expected i32 or i64, got {other:?}"))), }; let table_addr = table_addrs @@ -493,8 +724,8 @@ impl Store { }; 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, + RuntimeValue::Value32(value) => u64::from(value), + RuntimeValue::Value64(value) => value, other => return Err(Error::Other(format!("expected i32 or i64, got {other:?}"))), }; let Some(mem) = self.state.memories.get_mut(*mem_addr as usize) else { diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 90d1fb0..11ea70d 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::*; use crate::engine::Config; -use crate::interpreter::Value128; /// Global state that can be manipulated by WebAssembly programs /// @@ -17,10 +16,10 @@ pub(crate) struct State { pub(crate) memories: Vec, pub(crate) globals: Globals, pub(crate) tags: Vec, - pub(crate) exceptions: Vec, pub(crate) elements: Vec, pub(crate) data: Vec, pub(crate) gc: gc::GcHeap, + pub(crate) roots: gc::Roots, } impl State { @@ -33,16 +32,37 @@ impl State { memories: Vec::new(), globals: Globals::default(), tags: Vec::new(), - exceptions: Vec::new(), elements: Vec::new(), data: Vec::new(), gc: gc::GcHeap::new(config), + roots: gc::Roots::new(), } } - /// 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) + pub(crate) fn collect_gc(&mut self, additional: impl IntoIterator) -> Result<(), gc::AllocError> { + let canonical_types = &self.canonical_types; + let store_roots = self + .globals + .globals_32() + .filter(|(_, ty)| Self::type_may_contain_gc_in(canonical_types, &ty.ty)) + .map(|(value, _)| ValueRef::from_raw(*value)) + .chain( + self.tables + .iter() + .filter(|table| { + Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(table.kind.element_type)) + }) + .flat_map(|table| table.elements.iter().copied()), + ) + .chain( + self.elements + .iter() + .filter(|element| Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(element.ty))) + .flat_map(|element| element.items.iter().flatten().copied()), + ) + .chain(additional); + let roots = self.roots.values().chain(store_roots); + self.gc.collect(roots) } fn type_may_contain_gc_in(types: &[SubType], ty: &WasmType) -> bool { @@ -58,25 +78,28 @@ impl State { | AbstractHeapType::Struct | AbstractHeapType::Array | AbstractHeapType::Extern + | AbstractHeapType::Exn ) ) } - /// Precomputes whether a canonical function signature can carry GC objects. - pub(crate) fn func_gc_metadata(&self, type_addr: TypeAddr) -> FunctionGcMetadata { - let ty = self.get_canonical_func_type(type_addr); - FunctionGcMetadata { - params: ty.params().iter().any(|ty| self.type_may_contain_gc(ty)), - results: ty.results().iter().any(|ty| self.type_may_contain_gc(ty)), - } + pub(crate) fn check_gc_allocation(&self, type_addr: TypeAddr, value_count: usize) -> Result<(), Trap> { + let trace_references = match &self.get_type(type_addr).composite { + CompositeType::Struct(ty) => { + ty.fields.iter().any(|field| matches!(field.storage, StorageType::Value(WasmType::Ref(_)))) + } + CompositeType::Array(ty) => matches!(ty.field.storage, StorageType::Value(WasmType::Ref(_))), + CompositeType::Func(_) => unreachable!("GC object type is not a function"), + }; + self.gc.check_allocation(value_count, trace_references) } /// Allocates an object, collecting from all runtime roots when needed. pub(crate) fn alloc_gc_object( &mut self, type_addr: TypeAddr, - values: Vec, - stack_32: impl IntoIterator, + values: Vec, + additional_roots: impl IntoIterator, ) -> Result { let trace_references = match &self.get_type(type_addr).composite { CompositeType::Struct(ty) => { @@ -86,66 +109,43 @@ impl State { CompositeType::Func(_) => unreachable!("GC object type is not a function"), }; if self.gc.should_collect(values.len(), trace_references) { - let canonical_types = &self.canonical_types; - let roots = stack_32 - .into_iter() - .map(ValueRef::from_raw) - .chain( - self.globals - .globals_32() - .filter(|(_, ty)| Self::type_may_contain_gc_in(canonical_types, &ty.ty)) - .map(|(value, _)| ValueRef::from_raw(*value)), - ) - .chain( - self.tables - .iter() - .filter(|table| { - Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(table.kind.element_type)) - }) - .flat_map(|table| table.elements.iter().copied()), - ) - .chain( - self.elements - .iter() - .filter(|element| Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(element.ty))) - .flat_map(|element| element.items.iter().flatten().copied()), - ) - .chain(self.exceptions.iter().flat_map(|exception| { - exception.payload.iter().filter_map(|value| match value { - TinyWasmValue::ValueRef(value) => Some(*value), - _ => None, - }) - })) - .chain(values.iter().filter_map(|value| match value { - TinyWasmValue::ValueRef(value) => Some(*value), - _ => None, - })); - cold_err!(self.gc.collect(roots)).map_err(|_| Trap::OutOfMemory)?; + let roots = additional_roots.into_iter().chain(values.iter().filter_map(|value| match value { + RuntimeValue::ValueRef(value) => Some(*value), + _ => None, + })); + cold_err!(self.collect_gc(roots)).map_err(|_| Trap::OutOfMemory)?; } self.gc.alloc(type_addr, values, trace_references) } - /// Pins a host-visible reference when it resolves to a managed GC object. - pub(crate) fn pin_host_ref(&self, value: RefValue) { - let raw = match value { - RefValue::Any(value) => value.raw(), - RefValue::Extern(value) => value.raw(), - RefValue::Null | RefValue::Func(_) | RefValue::Exn(_) => return, - }; - self.gc.pin(ValueRef::from_raw(raw)); - } - - /// Pins GC references that have crossed into host-visible values. - pub(crate) fn pin_host_values(&self, values: &[WasmValue]) { - for &value in values { - if let WasmValue::Ref(value) = value { - self.pin_host_ref(value); - } + /// Allocates a traced exception object, collecting with its payload as temporary roots. + pub(crate) fn alloc_exception( + &mut self, + tag_addr: TagAddr, + payload: Vec, + additional_roots: impl IntoIterator, + ) -> Result { + let type_addr = self.get_tag(tag_addr).type_addr; + let mut trace_fields = Vec::new(); + trace_fields.try_reserve_exact(payload.len()).map_err(|_| Trap::OutOfMemory)?; + trace_fields.extend( + self.get_canonical_func_type(type_addr) + .params() + .iter() + .map(|ty| Self::type_may_contain_gc_in(&self.canonical_types, ty)), + ); + if self.gc.should_collect(payload.len(), true) { + let roots = additional_roots.into_iter().chain(payload.iter().filter_map(|value| match value { + RuntimeValue::ValueRef(value) => Some(*value), + _ => None, + })); + cold_err!(self.collect_gc(roots)).map_err(|_| Trap::OutOfMemory)?; } + self.gc.alloc_exception(tag_addr, payload, &trace_fields) } /// Resolves a non-null object of the expected canonical type. - pub(crate) fn gc_object(&self, reference: ValueRef, expected_type: TypeAddr) -> Result<&gc::GcObject, Trap> { + pub(crate) fn gc_object(&self, reference: ValueRef, expected_type: TypeAddr) -> Result { if reference.is_null() { return Err(if self.get_type(expected_type).as_array().is_some() { Trap::NullArrayReference @@ -154,36 +154,13 @@ impl State { }); } let object = self.gc.get(reference).ok_or(Trap::Other("invalid GC reference"))?; - if !self.type_addr_is_subtype(object.type_addr, expected_type) { + let gc::GcObjectKind::Composite(type_addr) = object.kind else { + return Err(Trap::Other("GC reference is not a struct or array")); + }; + if !self.type_addr_is_subtype(type_addr, expected_type) { return Err(Trap::Other("GC reference type mismatch")); } - Ok(object) - } - - /// Converts an internal reference using canonical heap type information. - pub(crate) fn to_ref_value(&self, value: ValueRef, ty: RefType) -> RefValue { - if value.is_null() { - return RefValue::Null; - } - - if let Some(type_addr) = ty.type_index() { - return match &self.get_type(type_addr).composite { - CompositeType::Func(_) => { - RefValue::Func(FuncRef::new(value.addr().expect("non-null reference has an address"))) - } - CompositeType::Struct(_) | CompositeType::Array(_) => RefValue::Any(AnyRef::from_raw(value.raw())), - }; - } - if ty.is_func() { - return RefValue::Func(FuncRef::new(value.addr().expect("non-null reference has an address"))); - } - if ty.is_extern() { - return RefValue::Extern(ExternRef::from_raw(value.raw())); - } - if ty.is_exn() { - return RefValue::Exn(ExnRef::new(value.addr().expect("non-null reference has an address"))); - } - RefValue::Any(AnyRef::from_raw(value.raw())) + self.gc.handle(reference).ok_or(Trap::Other("invalid GC reference")) } /// Returns whether one canonical type is a subtype of another. @@ -276,7 +253,7 @@ impl State { return self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected); } if expected.abstract_heap_type() == Some(AbstractHeapType::Exn) { - return value.addr().is_some_and(|addr| self.exceptions.get(addr as usize).is_some()); + return matches!(self.gc.get(value).map(|object| object.kind), Some(gc::GcObjectKind::Exception(_))); } if value.is_i31() { return self.ref_type_is_subtype(RefType::new_abstract(false, AbstractHeapType::I31), expected); @@ -286,7 +263,8 @@ impl State { } let Some(object) = self.gc.get(value) else { return false }; - let actual = RefType::new_concrete(false, object.type_addr); + let gc::GcObjectKind::Composite(type_addr) = object.kind else { return false }; + let actual = RefType::new_concrete(false, type_addr); self.ref_type_is_subtype(actual, expected) } @@ -305,30 +283,6 @@ impl State { self.get_type(addr).as_func().expect("validated function address references a function type") } - pub(crate) fn value_matches_type(&self, value: WasmValue, expected: WasmType) -> bool { - match (value, expected) { - (WasmValue::Ref(RefValue::Null), WasmType::Ref(expected)) => expected.is_nullable(), - (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => self - .funcs - .get(func.addr() as usize) - .is_some_and(|func| self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected)), - (WasmValue::Ref(RefValue::Any(_)), WasmType::Ref(expected)) - if expected.is_func() || expected.is_extern() || expected.is_exn() => - { - false - } - (WasmValue::Ref(RefValue::Exn(value)), WasmType::Ref(expected)) => { - expected.abstract_heap_type() == Some(AbstractHeapType::Exn) - && self.exceptions.get(value.addr() as usize).is_some() - } - (WasmValue::Ref(RefValue::Any(value)), WasmType::Ref(expected)) => { - self.value_ref_matches(ValueRef::from_raw(value.raw()), expected) - } - (_, WasmType::Ref(expected)) if expected.is_concrete() => false, - _ => value.matches_type(expected), - } - } - pub(super) fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T { items.get(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}")) } @@ -405,37 +359,29 @@ impl State { Self::get_mut(&mut self.elements, addr, "element") } - /// Converts a global directly to its public value representation. - pub(crate) fn get_global_wasmvalue(&self, addr: GlobalAddr) -> WasmValue { + /// Returns a global in its internal value representation. + pub(crate) fn global_value(&self, addr: GlobalAddr) -> RuntimeValue { let ty = self.globals.ty(addr).ty; match ty { - WasmType::I32 => WasmValue::I32(self.globals.get_32(addr) as i32), - WasmType::I64 => WasmValue::I64(self.globals.get_64(addr) as i64), - WasmType::F32 => WasmValue::F32(f32::from_bits(self.globals.get_32(addr))), - WasmType::F64 => WasmValue::F64(f64::from_bits(self.globals.get_64(addr))), - WasmType::Ref(ty) => WasmValue::Ref(self.to_ref_value(ValueRef::from_raw(self.globals.get_32(addr)), ty)), - WasmType::V128 => WasmValue::V128(self.globals.get_128(addr).0), + 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)), } } - /// Validates and sets a global from its public value representation. - pub(crate) fn set_global_wasmvalue(&mut self, addr: GlobalAddr, value: WasmValue) -> Result<()> { + /// Sets a global from its internal value representation. + pub(crate) fn set_global_value(&mut self, addr: GlobalAddr, value: RuntimeValue) -> Result<()> { let ty = self.globals.ty(addr); if !ty.mutable { cold_path(); return Err(Error::other("global is immutable")); } - if !self.value_matches_type(value, ty.ty) { - cold_path(); - return Err(Error::other("invalid global value type")); - } match value { - WasmValue::I32(value) => self.globals.set_32(addr, value as u32), - WasmValue::I64(value) => self.globals.set_64(addr, value as u64), - WasmValue::F32(value) => self.globals.set_32(addr, value.to_bits()), - WasmValue::F64(value) => self.globals.set_64(addr, value.to_bits()), - WasmValue::Ref(value) => self.globals.set_32(addr, ValueRef::from(value).raw()), - WasmValue::V128(value) => self.globals.set_128(addr, Value128(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), } Ok(()) } diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index da52660..cb8ded0 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -17,6 +17,9 @@ pub(crate) struct TableInstance { impl TableInstance { /// Creates a table filled with the given initial reference. pub(crate) fn new(kind: TableType, init: ValueRef, limiter: Option<&dyn ResourceLimiter>) -> Result { + if kind.size_max.is_some_and(|maximum| maximum < kind.size_initial) { + return Err(Trap::OutOfMemory.into()); + } let size = cold_err!(usize::try_from(kind.size_initial)).map_err(|_| Trap::OutOfMemory)?; if size > MAX_TABLE_SIZE { return Err(Trap::OutOfMemory.into()); diff --git a/crates/tinywasm/tests/gc_refs.rs b/crates/tinywasm/tests/gc_refs.rs index d3f2994..9662bee 100644 --- a/crates/tinywasm/tests/gc_refs.rs +++ b/crates/tinywasm/tests/gc_refs.rs @@ -1,4 +1,4 @@ -use tinywasm::types::{ExternRef, RefValue, WasmValue}; +use tinywasm::types::{RefValue, WasmValue}; use tinywasm::{Engine, ExecProgress, ModuleInstance, Store, engine::Config}; const MODULE: &str = r#" @@ -28,7 +28,7 @@ fn store() -> Store { } #[test] -fn host_result_is_pinned_and_rejected_by_another_store() { +fn host_result_is_rooted_and_rejected_by_another_store() { let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap(); let mut first_store = store(); let first = ModuleInstance::instantiate(&mut first_store, &module, None).unwrap(); @@ -36,19 +36,23 @@ fn host_result_is_pinned_and_rejected_by_another_store() { let read = first.func_untyped(&first_store, "read").unwrap(); let churn = first.func_untyped(&first_store, "churn").unwrap(); - let value = new.call(&mut first_store, &[]).unwrap().pop().unwrap(); + let mut results = [WasmValue::Ref(RefValue::Null)]; + new.call(&mut first_store, &[], &mut results).unwrap(); + let [value] = results; assert!(matches!(value, WasmValue::Ref(RefValue::Any(_)))); - churn.call(&mut first_store, &[]).unwrap(); - assert_eq!(read.call(&mut first_store, &[value]).unwrap(), [WasmValue::I32(42)]); + churn.call(&mut first_store, &[], &mut []).unwrap(); + let mut results = [WasmValue::I32(0)]; + read.call(&mut first_store, std::slice::from_ref(&value), &mut results).unwrap(); + assert_eq!(results, [WasmValue::I32(42)]); let mut second_store = store(); let second = ModuleInstance::instantiate(&mut second_store, &module, None).unwrap(); let other_read = second.func_untyped(&second_store, "read").unwrap(); - assert!(other_read.call(&mut second_store, &[value]).is_err()); + assert!(other_read.call(&mut second_store, &[value], &mut [WasmValue::I32(0)]).is_err()); } #[test] -fn externalized_gc_result_is_pinned() { +fn externalized_gc_result_is_rooted() { let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap(); let mut store = store(); let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap(); @@ -56,10 +60,14 @@ fn externalized_gc_result_is_pinned() { let read = instance.func_untyped(&store, "read-extern").unwrap(); let churn = instance.func_untyped(&store, "churn").unwrap(); - let value = new.call(&mut store, &[]).unwrap().pop().unwrap(); + let mut results = [WasmValue::Ref(RefValue::Null)]; + new.call(&mut store, &[], &mut results).unwrap(); + let [value] = results; assert!(matches!(value, WasmValue::Ref(RefValue::Extern(_)))); - churn.call(&mut store, &[]).unwrap(); - assert_eq!(read.call(&mut store, &[value]).unwrap(), [WasmValue::I32(42)]); + churn.call(&mut store, &[], &mut []).unwrap(); + let mut results = [WasmValue::I32(0)]; + read.call(&mut store, &[value], &mut results).unwrap(); + assert_eq!(results, [WasmValue::I32(42)]); } #[test] @@ -70,13 +78,13 @@ fn host_externref_does_not_alias_a_gc_object() { let new = instance.func_untyped(&store, "new").unwrap(); let read = instance.func_untyped(&store, "read-extern").unwrap(); - new.call(&mut store, &[]).unwrap(); - let host_ref = WasmValue::Ref(RefValue::Extern(ExternRef::new(0))); - assert!(read.call(&mut store, &[host_ref]).is_err()); + new.call(&mut store, &[], &mut [WasmValue::Ref(RefValue::Null)]).unwrap(); + let host_ref = tinywasm::ExternRef::try_new(&mut store, 0).unwrap().into(); + assert!(read.call(&mut store, &[host_ref], &mut [WasmValue::I32(0)]).is_err()); } #[test] -fn resumable_gc_result_is_pinned() { +fn resumable_gc_result_is_rooted() { let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap(); let mut store = store(); let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap(); @@ -84,15 +92,20 @@ fn resumable_gc_result_is_pinned() { let read = instance.func_untyped(&store, "read").unwrap(); let churn = instance.func_untyped(&store, "churn").unwrap(); - let mut execution = new.call_resumable(&mut store, &[]).unwrap(); - let value = match execution.resume_with_fuel(1000).unwrap() { - ExecProgress::Completed(mut values) => values.pop().unwrap(), - ExecProgress::Suspended => panic!("constructor unexpectedly suspended"), - }; - drop(execution); + let mut results = [WasmValue::Ref(RefValue::Null)]; + { + let mut execution = new.call_resumable(&mut store, &[], &mut results).unwrap(); + match execution.resume_with_fuel(1000).unwrap() { + ExecProgress::Completed(()) => {} + ExecProgress::Suspended => panic!("constructor unexpectedly suspended"), + } + } + let [value] = results; - churn.call(&mut store, &[]).unwrap(); - assert_eq!(read.call(&mut store, &[value]).unwrap(), [WasmValue::I32(42)]); + churn.call(&mut store, &[], &mut []).unwrap(); + let mut results = [WasmValue::I32(0)]; + read.call(&mut store, &[value], &mut results).unwrap(); + assert_eq!(results, [WasmValue::I32(42)]); } #[test] @@ -116,5 +129,7 @@ fn element_initializers_root_previous_gc_values() { let mut store = store(); let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap(); - assert_eq!(instance.func_untyped(&store, "first").unwrap().call(&mut store, &[]).unwrap(), [WasmValue::I32(1)]); + let mut results = [WasmValue::I32(0)]; + instance.func_untyped(&store, "first").unwrap().call(&mut store, &[], &mut results).unwrap(); + assert_eq!(results, [WasmValue::I32(1)]); } diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index 38a85ef..484b3cc 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -1,6 +1,30 @@ use std::fmt::Write; -use tinywasm::types::{ExternRef, FuncType, RefType, RefValue, WasmType, WasmValue}; -use tinywasm::{FuncContext, HostFunction, Imports, Module, ModuleInstance, Store}; +use tinywasm::types::{FuncType, RefType, RefValue, WasmType, WasmValue}; +use tinywasm::{FuncContext, HostFunction, Imports, IntoWasmValues, Module, ModuleInstance, Store, ToWasmTypes}; + +struct TooFewParams; + +impl ToWasmTypes for TooFewParams { + const WASM_TYPES: Option<&'static [WasmType]> = Some(&[WasmType::I32, WasmType::I32]); +} + +impl IntoWasmValues for TooFewParams { + fn into_wasm_values(self) -> impl Iterator { + [WasmValue::I32(1)].into_iter() + } +} + +struct TooManyParams; + +impl ToWasmTypes for TooManyParams { + const WASM_TYPES: Option<&'static [WasmType]> = Some(&[WasmType::I32, WasmType::I32]); +} + +impl IntoWasmValues for TooManyParams { + fn into_wasm_values(self) -> impl Iterator { + [WasmValue::I32(1), WasmValue::I32(2), WasmValue::I32(3)].into_iter() + } +} const VAL_LISTS: &[&[WasmValue]] = &[ &[], @@ -8,7 +32,6 @@ const VAL_LISTS: &[&[WasmValue]] = &[ &[WasmValue::I32(0), WasmValue::I32(0)], &[WasmValue::I32(0), WasmValue::I32(0), WasmValue::F64(0.0)], &[WasmValue::I32(0), WasmValue::F64(0.0), WasmValue::I32(0)], - &[WasmValue::Ref(RefValue::Extern(ExternRef::new(0))), WasmValue::F64(0.0), WasmValue::I32(0)], ]; fn module_cases() -> Vec<(Module, FuncType, Vec)> { @@ -32,7 +55,13 @@ fn test_return_invalid_type() -> Result<(), Box> { for returned_values in VAL_LISTS { let mut store = Store::default(); let mut imports = Imports::new(); - let hfn = HostFunction::from_untyped(&ty, |_: FuncContext<'_>, _| Ok(returned_values.to_vec())); + let hfn = HostFunction::from_untyped(&ty, move |_: FuncContext<'_>, _, results| { + if results.len() != returned_values.len() { + return Err(tinywasm::Error::Other("invalid fixture result count".into())); + } + results.clone_from_slice(returned_values); + Ok(()) + }); imports.define("host", "hfn", hfn); let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)).unwrap(); @@ -40,7 +69,8 @@ fn test_return_invalid_type() -> Result<(), Box> { // Return-type mismatch is only observable at call time. let should_succeed = returned_values.len() == ty.results().len() && returned_values.iter().zip(ty.results()).all(|(value, ty)| value.matches_type(*ty)); - let call_res = caller.call(&mut store, &args); + let mut results = vec![WasmValue::I32(0); ty.results().len()]; + let call_res = caller.call(&mut store, &args, &mut results); assert_eq!(call_res.is_ok(), should_succeed); } } @@ -54,7 +84,8 @@ fn test_linking_invalid_untyped_func() -> Result<(), Box for (module, expected_func_ty, _) in &cases { for (_, ty, _) in &cases { let mut store = Store::default(); - let tried_fn = HostFunction::from_untyped(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); @@ -105,7 +136,79 @@ fn test_linking_invalid_typed_func() -> Result<(), Box> } #[test] -fn concrete_host_references_use_canonical_types() -> Result<(), Box> { +fn typed_v128_values_roundtrip() -> Result<(), Box> { + let module = tinywasm::parse_bytes(&wat::parse_str( + r#" + (module + (import "host" "identity" (func $identity (param v128) (result v128))) + (func (export "identity") (param v128) (result v128) + local.get 0 + call $identity)) + "#, + )?)?; + let mut store = Store::default(); + let mut imports = Imports::new(); + imports.define("host", "identity", HostFunction::from(|_, value: [u8; 16]| Ok(value))); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let identity = instance.func::<[u8; 16], [u8; 16]>(&store, "identity")?; + let value = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + + assert_eq!(identity.call(&mut store, value)?, value); + Ok(()) +} + +#[test] +fn untyped_host_callbacks_must_write_all_results() -> Result<(), Box> { + let ty = FuncType::new(&[], &[WasmType::I32]); + let host = HostFunction::from_untyped(&ty, |_, _, _| Ok(())); + let mut store = Store::default(); + let function = host.clone().instantiate(&mut store)?; + let mut results = [WasmValue::I32(7)]; + + assert!(function.call(&mut store, &[], &mut results).is_err()); + assert!(function.call_resumable(&mut store, &[], &mut results).is_err()); + + let module = tinywasm::parse_bytes(&wat::parse_str( + r#" + (module + (import "host" "value" (func $value (result i32))) + (func (export "value") (result i32) call $value)) + "#, + )?)?; + let mut imports = Imports::new(); + imports.define("host", "value", host); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let function = instance.func_untyped(&store, "value")?; + + assert!(function.call(&mut store, &[], &mut results).is_err()); + Ok(()) +} + +#[test] +fn typed_untyped_bridge_rejects_inexact_parameter_iterators() -> Result<(), Box> { + let module = tinywasm::parse_bytes(&wat::parse_str( + r#" + (module + (import "host" "take" (func $take (param i32 i32))) + (export "take" (func $take))) + "#, + )?)?; + let mut store = Store::default(); + let mut imports = Imports::new(); + imports.define( + "host", + "take", + HostFunction::from_untyped(&FuncType::new(&[WasmType::I32, WasmType::I32], &[]), |_, _, _| Ok(())), + ); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + + assert!(instance.func::(&store, "take")?.call(&mut store, TooFewParams).is_err()); + assert!(instance.func::(&store, "take")?.call(&mut store, TooManyParams).is_err()); + Ok(()) +} + +#[test] +fn standalone_host_functions_reject_concrete_types() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -125,19 +228,11 @@ fn concrete_host_references_use_canonical_types() -> Result<(), Box Result<(), Box Result<(), Box 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)?; - let invalid = WasmValue::Ref(RefValue::Func(tinywasm::types::FuncRef::new(u32::MAX))); + let host = HostFunction::from_untyped(&ty, |_, _, _| Ok(())).instantiate(&mut store)?; + let mut other_store = Store::default(); + let other = HostFunction::from_untyped(&FuncType::new(&[], &[]), |_, _, _| Ok(())).instantiate(&mut other_store)?; + let invalid = WasmValue::Ref(RefValue::Func(other.as_func_ref(&other_store)?)); - assert!(host.call(&mut store, &[invalid]).is_err()); + assert!(host.call(&mut store, &[invalid], &mut []).is_err()); Ok(()) } diff --git a/crates/tinywasm/tests/imported_table_init.rs b/crates/tinywasm/tests/imported_table_init.rs index aaa781b..aa27b85 100644 --- a/crates/tinywasm/tests/imported_table_init.rs +++ b/crates/tinywasm/tests/imported_table_init.rs @@ -1,4 +1,4 @@ -use tinywasm::types::{FuncRef, RefType, TableType}; +use tinywasm::types::{RefType, TableType}; use tinywasm::{HostFunction, Imports, ModuleInstance, Store, Table}; #[test] @@ -18,8 +18,9 @@ fn imported_table_uses_provided_init_value() -> Result<(), Box Result<(), Box Result<(), Box Result<(), Box Result<() let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let ExternItem::Func(func) = instance.extern_item("f")? else { panic!("expected function export") }; - assert_eq!(func.call(&mut store, &[])?, vec![]); + func.call(&mut store, &[], &mut [])?; Ok(()) } @@ -196,7 +199,7 @@ fn start_resolves_module_func_index_to_store_addr() -> Result<(), Box ModuleInstance { + let wasm = wat::parse_str(MODULE).unwrap(); + let module = tinywasm::parse_bytes(&wasm).unwrap(); + ModuleInstance::instantiate(store, &module, None).unwrap() +} + +fn exception(error: Error) -> ExnRef { + let Error::Exception(exception) = error else { panic!("expected exception") }; + exception +} + +#[test] +fn exception_accessors_validate_store_and_expose_payload() { + let mut store = Store::default(); + let instance = instantiate(&mut store); + let throw = instance.func_untyped(&store, "throw-scalar").unwrap(); + let exception = exception(throw.call(&mut store, &[WasmValue::I32(17)], &mut []).unwrap_err()); + + assert_eq!(exception.tag(&store).unwrap(), instance.tag("scalar-tag").unwrap()); + assert_eq!(exception.field(&mut store, 0).unwrap(), WasmValue::I32(17)); + assert_eq!(exception.fields(&mut store).unwrap(), [WasmValue::I32(17)]); + assert!(exception.field(&mut store, 1).is_err()); + + let other = Store::default(); + assert_eq!(exception.tag(&other).unwrap_err(), Error::Trap(Trap::InvalidStore)); +} + +#[test] +fn exception_roots_keep_payload_graphs_live() { + let mut store = Store::new(Engine::new(Config::new().with_gc_collection_threshold(1))); + let instance = instantiate(&mut store); + let throw = instance.func_untyped(&store, "throw-graph").unwrap(); + let read = instance.func_untyped(&store, "read-node").unwrap(); + let exception = exception(throw.call(&mut store, &[], &mut []).unwrap_err()); + + store.gc().unwrap(); + let payload = exception.field(&mut store, 0).unwrap(); + assert!(matches!(payload, WasmValue::Ref(RefValue::Any(_)))); + let mut results = [WasmValue::I32(0)]; + read.call(&mut store, &[payload], &mut results).unwrap(); + assert_eq!(results, [WasmValue::I32(42)]); +} + +#[test] +fn owned_exception_references_survive_collection_and_reject_another_store() { + let mut store = Store::default(); + let instance = instantiate(&mut store); + let throw = instance.func_untyped(&store, "throw-scalar").unwrap(); + let first = exception(throw.call(&mut store, &[WasmValue::I32(1)], &mut []).unwrap_err()); + + store.gc().unwrap(); + let current = exception(throw.call(&mut store, &[WasmValue::I32(2)], &mut []).unwrap_err()); + assert_eq!(current.field(&mut store, 0).unwrap(), WasmValue::I32(2)); + assert_eq!(first.field(&mut store, 0).unwrap(), WasmValue::I32(1)); + let rethrow = instance.func_untyped(&store, "rethrow").unwrap(); + let rethrown = exception(rethrow.call(&mut store, &[WasmValue::Ref(RefValue::Exn(first))], &mut []).unwrap_err()); + assert_eq!(rethrown.field(&mut store, 0).unwrap(), WasmValue::I32(1)); + + let mut other = Store::default(); + let other_instance = instantiate(&mut other); + let other_rethrow = other_instance.func_untyped(&other, "rethrow").unwrap(); + assert_eq!( + other_rethrow.call(&mut other, &[WasmValue::Ref(RefValue::Exn(current))], &mut []).unwrap_err(), + Error::Trap(Trap::InvalidStore) + ); +} + +#[test] +fn host_tags_reject_unbranded_concrete_types() { + let mut store = Store::default(); + let ty = FuncType::new(&[WasmType::Ref(RefType::new_concrete(true, 0))], &[]); + + assert!(Tag::try_new(&mut store, ty).is_err()); +} + +struct GcUsage(Arc>>); + +impl ResourceLimiter for GcUsage { + fn gc_growing(&self, current: usize, desired: usize, _maximum: Option) -> Result { + self.0.lock().unwrap().push((current, desired)); + Ok(true) + } +} + +#[test] +fn dropped_exception_roots_release_counted_gc_bytes() { + let usage = Arc::new(Mutex::new(Vec::new())); + let config = + Config::new().with_gc_collection_threshold(usize::MAX).with_resource_limiter(Arc::new(GcUsage(usage.clone()))); + let mut store = Store::new(Engine::new(config)); + let instance = instantiate(&mut store); + let catch = instance.func_untyped(&store, "catch-scalar").unwrap(); + + for value in 0..32 { + catch.call(&mut store, &[WasmValue::I32(value)], &mut []).unwrap(); + } + store.gc().unwrap(); + usage.lock().unwrap().clear(); + + catch.call(&mut store, &[WasmValue::I32(33)], &mut []).unwrap(); + assert_eq!(usage.lock().unwrap()[0].0, 0); +} diff --git a/crates/tinywasm/tests/memory.rs b/crates/tinywasm/tests/memory.rs index 213a15f..819fe85 100644 --- a/crates/tinywasm/tests/memory.rs +++ b/crates/tinywasm/tests/memory.rs @@ -16,7 +16,7 @@ fn store_with_limiter(limiter: Arc) -> Store { #[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))?; + let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4, 5])?; assert_eq!(memory.read_vec(&store, 0, 5)?, &[1, 2, 3, 4, 5]); @@ -28,7 +28,7 @@ fn memory_read_write_roundtrip() -> TestResult { #[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)))?; + let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)))?; memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4])?; let mut dst = [9; 8]; @@ -84,7 +84,7 @@ impl ResourceLimiter for TrapGrowth { #[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))?; + let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; assert_eq!(memory.grow(&mut store, 1)?, None); assert_eq!(memory.page_count(&store)?, 1); @@ -134,7 +134,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 result = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None)); + let result = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None)); assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); } @@ -153,7 +153,15 @@ 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 result = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into()); + let result = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into()); + + assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); +} + +#[test] +fn table_rejects_initial_size_above_maximum() { + let mut store = Store::default(); + let result = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 2, Some(1)), RefValue::Null.into()); assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); } @@ -161,7 +169,7 @@ fn resource_limiter_rejects_table_initial_size() { #[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())?; + let table = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; assert_eq!(table.grow(&mut store, 1, RefValue::Null.into())?, None); assert_eq!(table.size(&store)?, 1); @@ -171,7 +179,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 table = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; + let table = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; assert!(matches!(table.grow(&mut store, 1, RefValue::Null.into()), Err(tinywasm::Error::Trap(Trap::Unreachable)))); Ok(()) diff --git a/crates/tinywasm/tests/reference_roots.rs b/crates/tinywasm/tests/reference_roots.rs new file mode 100644 index 0000000..775047e --- /dev/null +++ b/crates/tinywasm/tests/reference_roots.rs @@ -0,0 +1,104 @@ +use std::sync::{Arc, Mutex}; +use tinywasm::types::{ExternRef, FuncType, RefType, RefValue, WasmType, WasmValue}; +use tinywasm::{HostFunction, Imports, ModuleInstance, Store, Trap}; + +#[test] +fn direct_references_stay_live_until_the_last_clone_is_dropped() { + let mut store = Store::default(); + let reference = ExternRef::try_new(&mut store, 7).unwrap(); + let clone = reference.clone(); + drop(reference); + store.gc().unwrap(); + + assert_eq!(clone.key(&store), Ok(7)); +} + +#[test] +fn roots_and_function_references_reject_another_store() { + let mut first = Store::default(); + let mut second = Store::default(); + let root = ExternRef::try_new(&mut first, 1).unwrap(); + let function = HostFunction::from(|_, ()| -> tinywasm::Result<()> { Ok(()) }).instantiate(&mut first).unwrap(); + let func_ref = function.as_func_ref(&first).unwrap(); + let accepts_func_ref = + HostFunction::from(|_, _: Option| -> tinywasm::Result<()> { Ok(()) }) + .instantiate(&mut second) + .unwrap(); + + assert!(matches!(root.key(&second), Err(tinywasm::Error::Trap(Trap::InvalidStore)))); + assert!(matches!( + accepts_func_ref.call(&mut second, &[WasmValue::Ref(RefValue::Func(func_ref))], &mut []), + Err(tinywasm::Error::Trap(Trap::InvalidStore)) + )); +} + +#[test] +fn callback_results_and_captured_clones_remain_valid() { + let mut store = Store::default(); + let captured = Arc::new(Mutex::new(None)); + let callback_root = captured.clone(); + let ty = FuncType::new(&[], &[WasmType::Ref(RefType::EXTERNREF)]); + let function = HostFunction::from_untyped(&ty, move |mut context, _, results| { + let root = ExternRef::try_new(context.store_mut(), 17)?; + *callback_root.lock().unwrap() = Some(root.clone()); + results[0] = root.into(); + Ok(()) + }) + .instantiate(&mut store) + .unwrap(); + + let mut results = [WasmValue::Ref(RefValue::Null)]; + function.call(&mut store, &[], &mut results).unwrap(); + let [result] = results; + let WasmValue::Ref(RefValue::Extern(result)) = result else { panic!("expected externref") }; + assert_eq!(result.key(&store), Ok(17)); + assert_eq!(captured.lock().unwrap().as_ref().unwrap().key(&store), Ok(17)); +} + +#[test] +fn guest_callback_arguments_are_rooted_before_entering_untyped_host_code() { + let wasm = wat::parse_str( + r#" + (module + (import "host" "make" (func $make (result (ref extern)))) + (import "host" "check" (func $check (param externref))) + (func (export "call") + call $make + call $check)) + "#, + ) + .unwrap(); + let module = tinywasm::parse_bytes(&wasm).unwrap(); + let mut store = Store::default(); + let mut imports = Imports::new(); + imports.define("host", "make", HostFunction::from(|mut context, ()| ExternRef::try_new(context.store_mut(), 23))); + imports.define( + "host", + "check", + HostFunction::from_untyped( + &FuncType::new(&[WasmType::Ref(RefType::EXTERNREF)], &[]), + |context, args, _results| { + let WasmValue::Ref(RefValue::Extern(value)) = &args[0] else { panic!("expected externref") }; + assert_eq!(value.key(context.store()), Ok(23)); + Ok(()) + }, + ), + ); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)).unwrap(); + + instance.func::<(), ()>(&store, "call").unwrap().call(&mut store, ()).unwrap(); +} + +#[test] +fn typed_option_reference_signatures_are_nullable() { + let mut store = Store::default(); + let function = + HostFunction::from(|_context, value: Option| -> tinywasm::Result> { Ok(value) }) + .instantiate(&mut store) + .unwrap(); + + assert_eq!(function.ty(&store).unwrap().params(), &[WasmType::Ref(RefType::EXTERNREF)]); + let mut results = [WasmValue::Ref(RefValue::Null)]; + function.call(&mut store, &[WasmValue::Ref(RefValue::Null)], &mut results).unwrap(); + assert_eq!(results, [WasmValue::Ref(RefValue::Null)]); +} diff --git a/crates/tinywasm/tests/resume_execution.rs b/crates/tinywasm/tests/resume_execution.rs index 2798e7b..f7dff4f 100644 --- a/crates/tinywasm/tests/resume_execution.rs +++ b/crates/tinywasm/tests/resume_execution.rs @@ -42,15 +42,17 @@ fn untyped_resume_supports_zero_fuel() -> Result<()> { let instance = ModuleInstance::instantiate(&mut store, &module, None)?; let func = instance.func_untyped(&store, "add")?; - let mut exec = func.call_resumable(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)])?; - assert!(matches!(exec.resume_with_fuel(0)?, ExecProgress::Suspended)); - - match exec.resume_with_fuel(16)? { - ExecProgress::Completed(values) => { - assert_eq!(values, vec![WasmValue::I32(42)]) + let mut results = [WasmValue::I32(0)]; + { + let mut exec = func.call_resumable(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)], &mut results)?; + assert!(matches!(exec.resume_with_fuel(0)?, ExecProgress::Suspended)); + + match exec.resume_with_fuel(16)? { + ExecProgress::Completed(()) => {} + ExecProgress::Suspended => panic!("expected completion"), } - ExecProgress::Suspended => panic!("expected completion"), } + assert_eq!(results, [WasmValue::I32(42)]); Ok(()) } diff --git a/crates/tinywasm/tests/store_ownership.rs b/crates/tinywasm/tests/store_ownership.rs index a508817..72c9478 100644 --- a/crates/tinywasm/tests/store_ownership.rs +++ b/crates/tinywasm/tests/store_ownership.rs @@ -21,7 +21,7 @@ fn func_handle_rejects_wrong_store() -> Result<(), Box> let func = instance.func_untyped(&owner_store, "add")?; let mut other_store = Store::default(); - let err = func.call(&mut other_store, &[1.into(), 2.into()]).unwrap_err(); + let err = func.call(&mut other_store, &[1.into(), 2.into()], &mut [0.into()]).unwrap_err(); assert!(err.to_string().contains("invalid store")); Ok(()) @@ -58,8 +58,8 @@ fn global_access_rejects_wrong_store() -> Result<(), Box let instance = ModuleInstance::instantiate(&mut owner_store, &module, None)?; let global = instance.global("g")?; - let other_store = Store::default(); - let err = global.get(&other_store).unwrap_err(); + let mut other_store = Store::default(); + let err = global.get(&mut other_store).unwrap_err(); assert_eq!(err, tinywasm::Error::Trap(tinywasm::Trap::InvalidStore)); Ok(()) @@ -92,7 +92,7 @@ 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(); - let global = Global::new(&mut owner_store, GlobalType::new(WasmType::I32, false), 1.into())?; + let global = Global::try_new(&mut owner_store, GlobalType::new(WasmType::I32, false), 1.into())?; let mut imports = Imports::default(); imports.define("env", "g", global); diff --git a/crates/tinywasm/tests/typed_gc_access.rs b/crates/tinywasm/tests/typed_gc_access.rs new file mode 100644 index 0000000..26b2362 --- /dev/null +++ b/crates/tinywasm/tests/typed_gc_access.rs @@ -0,0 +1,49 @@ +use tinywasm::types::{ArrayRef, RefValue, StructRef, WasmValue}; +use tinywasm::{GcStorageType, ModuleInstance, Store}; + +#[test] +fn typed_struct_and_array_access() -> tinywasm::Result<()> { + let wasm = wat::parse_str( + r#"(module + (type $s (struct (field (mut i32)) (field i8))) + (type $refs (struct (field (ref $s)) (field (ref null $s)))) + (type $a (array (mut i16))) + (func $make-struct (result (ref $s)) + i32.const 7 + i32.const 258 + struct.new $s) + (func (export "struct") (result (ref struct)) + call $make-struct) + (func (export "refs") (result (ref struct)) + call $make-struct + ref.null $s + struct.new $refs) + (func (export "array") (result (ref array)) + i32.const 65537 + i32.const 2 + array.new $a))"#, + ) + .expect("valid WAT"); + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &tinywasm::parse_bytes(&wasm)?, None)?; + + let structure: StructRef = instance.func::<(), StructRef>(&store, "struct")?.call(&mut store, ())?; + assert_eq!(structure.fields(&mut store)?, [WasmValue::I32(7), WasmValue::I32(2)]); + structure.set_field(&mut store, 0, WasmValue::I32(9))?; + assert_eq!(structure.field(&mut store, 0)?, WasmValue::I32(9)); + assert_eq!(structure.ty(&store)?.field(&store, 1)?.storage(), GcStorageType::I8); + + let references: StructRef = instance.func::<(), StructRef>(&store, "refs")?.call(&mut store, ())?; + let fields = references.fields(&mut store)?; + let WasmValue::Ref(RefValue::Any(nested)) = &fields[0] else { panic!("expected struct reference") }; + assert_eq!(fields[1], WasmValue::Ref(RefValue::Null)); + store.gc()?; + assert_eq!(nested.as_struct().unwrap().field(&mut store, 0)?, WasmValue::I32(7)); + + let array: ArrayRef = instance.func::<(), ArrayRef>(&store, "array")?.call(&mut store, ())?; + assert_eq!(array.len(&store)?, 2); + assert_eq!(array.get(&mut store, 0)?, WasmValue::I32(1)); + array.set(&mut store, 1, WasmValue::I32(3))?; + assert_eq!(array.get(&mut store, 1)?, WasmValue::I32(3)); + Ok(()) +} diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs index e57309f..34f402d 100644 --- a/crates/tinywasm/tests/typed_globals.rs +++ b/crates/tinywasm/tests/typed_globals.rs @@ -60,7 +60,9 @@ fn globals_use_typed_instructions_and_roundtrip_values() -> Result<(), Box(&store, "add-i32")?.call(&mut store, 2)?, 13); assert_eq!(instance.func::(&store, "add-i64")?.call(&mut store, 2)?, 15); @@ -81,12 +83,12 @@ fn imported_global_keeps_its_typed_store_address() -> Result<(), Box(&store, "roundtrip")?.call(&mut store, 42)?, 42); - assert_eq!(global.get(&store)?, WasmValue::I64(42)); + assert_eq!(global.get(&mut store)?, WasmValue::I64(42)); Ok(()) } diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index db40263..b568155 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -7,7 +7,7 @@ use crate::Module; #[rustfmt::skip] const TWASM_MAGIC: [u8; 16] = [ TWASM_MAGIC_PREFIX[0], TWASM_MAGIC_PREFIX[1], TWASM_MAGIC_PREFIX[2], TWASM_MAGIC_PREFIX[3], TWASM_VERSION[0], TWASM_VERSION[1], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; const TWASM_MAGIC_PREFIX: &[u8; 4] = b"TWAS"; -const TWASM_VERSION: &[u8; 2] = b"05"; +const TWASM_VERSION: &[u8; 2] = b"06"; fn validate_magic(wasm: &[u8]) -> Result { if wasm.len() < TWASM_MAGIC.len() || &wasm[..TWASM_MAGIC_PREFIX.len()] != TWASM_MAGIC_PREFIX { @@ -64,7 +64,10 @@ impl Module { #[cfg(test)] mod tests { use super::*; - use crate::{Instruction, ModuleInner, V128Operand, WasmFunction}; + use crate::{ + AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, RefType, + V128Operand, WasmFunction, WasmType, + }; use crate::{OperandIdx, OperandType}; use alloc::{boxed::Box, sync::Arc, vec}; @@ -94,7 +97,7 @@ mod tests { 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"); + assert_eq!(&archive[..6], b"TWAS06"); let decoded = Module::try_from_twasm(&archive).expect("deserialize archive"); let function = &decoded.funcs[0]; @@ -106,4 +109,37 @@ mod tests { assert_eq!(index.get(&function.data).value, bytes); } } + + #[test] + fn const_reference_expressions_round_trip_archive() { + let null_type = RefType::new_abstract(true, AbstractHeapType::Extern); + let module = Module::from(ModuleInner { + globals: vec![ + Global { + ty: GlobalType::new(WasmType::Ref(null_type), false), + init: vec![ConstInstruction::RefNull(null_type)].into_boxed_slice(), + }, + Global { + ty: GlobalType::new(WasmType::Ref(RefType::FUNCREF), false), + init: vec![ConstInstruction::RefFunc(ModuleFuncIdx::new(7))].into_boxed_slice(), + }, + Global { + ty: GlobalType::new(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::I31)), false), + init: vec![ConstInstruction::I32Const(42), ConstInstruction::RefI31].into_boxed_slice(), + }, + ] + .into_boxed_slice(), + ..ModuleInner::default() + }); + + let archive = module.serialize_twasm().expect("serialize archive"); + let decoded = Module::try_from_twasm(&archive).expect("deserialize archive"); + + assert!(matches!(decoded.globals[0].init.as_ref(), [ConstInstruction::RefNull(ty)] if *ty == null_type)); + assert!(matches!( + decoded.globals[1].init.as_ref(), + [ConstInstruction::RefFunc(index)] if index.index() == 7 + )); + assert!(matches!(decoded.globals[2].init.as_ref(), [ConstInstruction::I32Const(42), ConstInstruction::RefI31])); + } } diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index c9786d3..7e0cd28 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -2,7 +2,7 @@ use alloc::boxed::Box; use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; use crate::operands::sealed; -use crate::{DataAddr, ElemAddr, MemAddr, Operand64, Operand128, OperandIdx, OperandType, RefType, RefValue}; +use crate::{DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand128, OperandIdx, OperandType, RefType}; /// Represents a memory immediate in a WebAssembly memory instruction. #[derive(Copy, Clone, PartialEq, Eq)] @@ -429,7 +429,8 @@ pub enum ConstInstruction { GlobalGet64(GlobalAddr), GlobalGet128(GlobalAddr), GlobalGetRef(GlobalAddr), - Ref(RefValue), + RefNull(RefType), + RefFunc(ModuleFuncIdx), RefI31, AnyConvertExtern, ExternConvertAny, @@ -535,8 +536,6 @@ pub enum BinOp128 { /// These instructions are an internal, version-specific representation and do not /// map one-to-one to WebAssembly instructions. Their variants and serialized form /// may change between TinyWasm releases. -/// -/// See #[rustfmt::skip] #[derive(Clone, Copy, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index d1f7453..686433d 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -47,11 +47,12 @@ pub mod archive { impl core::error::Error for TwasmError {} } -/// A `TinyWasm` WebAssembly Module +/// TinyWasm's parsed and lowered representation of a WebAssembly module. /// -/// This is the internal representation of a WebAssembly module in `TinyWasm`. /// Modules produced by the parser are validated by default, but validation can be /// disabled for trusted input. Do not trust modules or archives from third parties. +/// +/// See #[derive(Clone, Default, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -326,13 +327,35 @@ pub type TableAddr = Addr; pub type MemAddr = Addr; pub type GlobalAddr = Addr; pub type TagAddr = Addr; -pub type ExnAddr = Addr; pub type ElemAddr = Addr; pub type DataAddr = Addr; pub type ExternAddr = Addr; pub type ConstIdx = Addr; // additional internal addresses +/// A function index in a WebAssembly module's function index space. +/// +/// This remains module-local until instantiation resolves it to a [`FuncAddr`]. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "archive", serde(transparent))] +pub struct ModuleFuncIdx(u32); + +impl ModuleFuncIdx { + /// Creates a module-local function index. + #[inline] + pub const fn new(index: u32) -> Self { + Self(index) + } + + /// Returns the module-local function index. + #[inline] + pub const fn index(self) -> u32 { + self.0 + } +} + /// An address in the current type space. /// /// Parsed modules use module-local addresses; instantiated types use their store's canonical addresses. @@ -484,6 +507,9 @@ pub struct Global { pub init: Box<[ConstInstruction]>, } +/// A WebAssembly global type. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -517,6 +543,9 @@ impl Default for GlobalType { } } +/// A WebAssembly table type. +/// +/// See #[derive(Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -556,7 +585,9 @@ impl TableType { } } -/// Represents a memory's type. +/// A WebAssembly memory type. +/// +/// See #[derive(Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -597,7 +628,7 @@ impl MemoryType { } } - /// The declared maximum page count, or `None` when the memory is unbounded. + /// Returns the declared maximum page count, or `None` if no maximum was declared. #[inline] pub const fn page_count_max_declared(&self) -> Option { self.page_count_max @@ -648,6 +679,8 @@ pub enum MemoryArch { } /// A WebAssembly tag type. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index ed59ae5..2d725ca 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -1,15 +1,8 @@ -const HOST_REF_TAG: u32 = 1 << 30; - -const fn encode_host_ref(addr: u32) -> Option { - if addr >= HOST_REF_TAG - 1 { - return None; - } - Some((addr | HOST_REF_TAG).wrapping_add(1).wrapping_mul(2)) -} - /// An abstract WebAssembly heap type. /// /// This contains exactly the abstract heap types in core Wasm 3.0. +/// +/// See #[repr(u8)] #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "debug", derive(Debug))] @@ -43,6 +36,8 @@ pub enum AbstractHeapType { /// For concrete types, `payload` is a module type index before instantiation /// and a canonical store type address at runtime. /// Otherwise, it is an [`AbstractHeapType`]. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct RefType(u32); @@ -148,156 +143,3 @@ impl RefType { matches!(self.abstract_heap_type(), Some(AbstractHeapType::Exn | AbstractHeapType::NoExn)) } } - -/// A host-facing WebAssembly reference value. -#[derive(Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub enum RefValue { - Null, - Func(FuncRef), - Extern(ExternRef), - Any(AnyRef), - Exn(ExnRef), -} - -/// A reference to a function in a store. -/// -/// The payload is the function's store-local address. -#[derive(Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct FuncRef(u32); - -impl FuncRef { - #[inline] - pub const fn new(addr: u32) -> Self { - Self(addr) - } - - #[inline] - pub const fn addr(self) -> u32 { - self.0 - } -} - -/// An opaque external reference. -/// -/// Packed as `[payload:31 i31:1]`. Host addresses use the upper payload -/// category, Store-managed objects use the lower category, and odd values -/// contain an externalized i31. -#[derive(Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct ExternRef(u32); - -impl ExternRef { - #[inline] - pub const fn new(addr: u32) -> Self { - let Some(value) = Self::try_new(addr) else { panic!("external reference address is too large") }; - value - } - - /// Creates an external reference when `addr` fits the runtime encoding. - #[inline] - pub const fn try_new(addr: u32) -> Option { - match encode_host_ref(addr) { - Some(encoded) => Some(Self(encoded)), - None => None, - } - } - - #[doc(hidden)] - #[inline] - pub const fn from_raw(raw: u32) -> Self { - Self(raw) - } - - #[doc(hidden)] - #[inline] - pub const fn raw(self) -> u32 { - self.0 - } -} - -/// A reference to an exception in a store. -/// -/// The payload is the exception's store-local address. -#[derive(Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct ExnRef(u32); - -impl ExnRef { - #[inline] - pub const fn new(addr: u32) -> Self { - Self(addr) - } - - #[inline] - pub const fn addr(self) -> u32 { - self.0 - } -} - -/// A WebAssembly `anyref` value. -/// -/// Packed as: -/// -/// ```text -/// [payload:31 i31:1] -/// ``` -/// -/// Odd values contain an inline signed i31. Non-zero even values are reserved -/// for store-managed references, and zero is reserved for null by the runtime. -#[derive(Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct AnyRef(u32); - -impl AnyRef { - /// Creates a host reference when `addr` fits the runtime encoding. - #[inline] - pub const fn from_host(addr: u32) -> Option { - match encode_host_ref(addr) { - Some(encoded) => Some(Self(encoded)), - None => None, - } - } - - #[doc(hidden)] - #[inline] - pub const fn from_raw(raw: u32) -> Self { - Self(raw) - } - - pub const fn from_i31(value: i32) -> Option { - if value < -(1 << 30) || value >= (1 << 30) { - return None; - } - - Some(Self(((value as u32) << 1) | 1)) - } - - pub const fn as_i31(self) -> Option { - if self.0 & 1 == 1 { Some((self.0 as i32) >> 1) } else { None } - } - - #[inline] - pub const fn raw(self) -> u32 { - self.0 - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn host_reference_encoding_is_checked_and_unique() { - assert_ne!(AnyRef::from_host(0), AnyRef::from_host(1)); - assert!(AnyRef::from_host(HOST_REF_TAG - 2).is_some()); - assert!(AnyRef::from_host(HOST_REF_TAG - 1).is_none()); - assert!(ExternRef::try_new(u32::MAX).is_none()); - } -} diff --git a/crates/types/src/types.rs b/crates/types/src/types.rs index 0801849..12386f1 100644 --- a/crates/types/src/types.rs +++ b/crates/types/src/types.rs @@ -3,6 +3,8 @@ use alloc::{boxed::Box, sync::Arc}; use crate::{TypeAddr, WasmType}; /// The dense type index space of a WebAssembly module. +/// +/// See #[derive(Clone, PartialEq, Eq, Default)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -31,6 +33,8 @@ impl TypeSection { } /// A type with optional declared subtyping. +/// +/// See #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -58,6 +62,8 @@ impl SubType { } /// A function, struct, or array type. +/// +/// See #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -123,6 +129,8 @@ impl FuncType { } /// A WebAssembly struct type. +/// +/// See #[derive(Clone, PartialEq, Eq, Default)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -131,6 +139,8 @@ pub struct StructType { } /// A WebAssembly array type. +/// +/// See #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -139,6 +149,8 @@ pub struct ArrayType { } /// A struct field or array element type. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -148,6 +160,8 @@ pub struct FieldType { } /// A field's packed or unpacked storage type. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -156,3 +170,13 @@ pub enum StorageType { I16, Value(WasmType), } + +impl StorageType { + /// Returns the unpacked WebAssembly value type used on the stack. + pub const fn unpacked(self) -> WasmType { + match self { + Self::I8 | Self::I16 => WasmType::I32, + Self::Value(ty) => ty, + } + } +} diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs index 5049ba2..847e5e1 100644 --- a/crates/types/src/value.rs +++ b/crates/types/src/value.rs @@ -1,307 +1,38 @@ -use core::fmt::Debug; - -use crate::{ConstInstruction, RefType, RefValue}; - -/// A WebAssembly value. -/// -/// See -#[derive(Clone, Copy, PartialEq)] -pub enum WasmValue { - // Num types - /// A 32-bit integer - I32(i32), - /// A 64-bit integer - I64(i64), - /// A 32-bit float - F32(f32), - /// A 64-bit float - F64(f64), - /// A 128-bit vector - V128([u8; 16]), - /// A reference type - Ref(RefValue), -} - -impl WasmValue { - /// Return this value's broad WebAssembly type. - /// - /// A null reference has no intrinsic heap type and returns `None`. - pub const fn ty(self) -> Option { - match self { - Self::I32(_) => Some(WasmType::I32), - Self::I64(_) => Some(WasmType::I64), - Self::F32(_) => Some(WasmType::F32), - Self::F64(_) => Some(WasmType::F64), - Self::V128(_) => Some(WasmType::V128), - Self::Ref(RefValue::Null) => None, - Self::Ref(RefValue::Func(_)) => Some(WasmType::Ref(RefType::FUNCREF)), - Self::Ref(RefValue::Extern(_)) => Some(WasmType::Ref(RefType::EXTERNREF)), - Self::Ref(RefValue::Exn(_)) => Some(WasmType::Ref(RefType::EXNREF)), - Self::Ref(RefValue::Any(_)) => { - Some(WasmType::Ref(RefType::new_abstract(true, crate::AbstractHeapType::Any))) - } - } - } - - #[inline] - pub const fn matches_type(self, ty: WasmType) -> bool { - // Concrete references require a store lookup; this method only classifies their broad heap type. - match (self, ty) { - (Self::I32(_), WasmType::I32) - | (Self::I64(_), WasmType::I64) - | (Self::F32(_), WasmType::F32) - | (Self::F64(_), WasmType::F64) - | (Self::V128(_), WasmType::V128) => true, - (Self::Ref(RefValue::Null), WasmType::Ref(ty)) => ty.is_nullable(), - (Self::Ref(RefValue::Func(_)), WasmType::Ref(ty)) => { - matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Func)) - } - (Self::Ref(RefValue::Extern(_)), WasmType::Ref(ty)) => { - matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Extern)) - } - (Self::Ref(RefValue::Exn(_)), WasmType::Ref(ty)) => { - matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Exn)) - } - (Self::Ref(RefValue::Any(value)), WasmType::Ref(ty)) => matches!( - (value.as_i31(), ty.abstract_heap_type()), - ( - Some(_), - Some(crate::AbstractHeapType::I31 | crate::AbstractHeapType::Eq | crate::AbstractHeapType::Any) - ) | (None, Some(crate::AbstractHeapType::Any)) - ), - _ => false, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{AbstractHeapType, AnyRef, FuncRef, RefType}; - - #[test] - fn concrete_references_require_store_type_information() { - let concrete = WasmType::Ref(RefType::new_concrete(false, 0)); - - assert!(!WasmValue::from(FuncRef::new(0)).matches_type(concrete)); - assert!(!WasmValue::from(AnyRef::from_host(0).unwrap()).matches_type(concrete)); - } - - #[test] - fn i31_only_matches_its_store_independent_supertypes() { - let value = WasmValue::from(AnyRef::from_i31(0).unwrap()); - - for ty in [AbstractHeapType::I31, AbstractHeapType::Eq, AbstractHeapType::Any] { - assert!(value.matches_type(WasmType::Ref(RefType::new_abstract(false, ty)))); - } - assert!(!value.matches_type(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::Struct)))); - } -} - -impl Debug for WasmValue { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - Self::I32(i) => write!(f, "i32({i})"), - Self::I64(i) => write!(f, "i64({i})"), - Self::F32(i) => write!(f, "f32({i})"), - Self::F64(i) => write!(f, "f64({i})"), - Self::V128(i) => write!(f, "v128({i:?})"), - #[cfg(feature = "debug")] - Self::Ref(i) => write!(f, "ref({i:?})"), - #[cfg(not(feature = "debug"))] - Self::Ref(_) => write!(f, "ref(...)"), - } - } -} - -impl WasmValue { - #[inline] - /// Get the matching [`ConstInstruction`] for this value. - pub fn const_instr(&self) -> alloc::boxed::Box<[ConstInstruction]> { - alloc::boxed::Box::new([match self { - Self::I32(i) => ConstInstruction::I32Const(*i), - Self::I64(i) => ConstInstruction::I64Const(*i), - Self::F32(i) => ConstInstruction::F32Const(*i), - Self::F64(i) => ConstInstruction::F64Const(*i), - Self::V128(i) => ConstInstruction::V128Const(*i), - Self::Ref(i) => ConstInstruction::Ref(*i), - }]) - } - - #[inline] - /// Get the default value for a given type. - pub const fn default_for(ty: WasmType) -> Option { - match ty { - WasmType::I32 => Some(Self::I32(0)), - WasmType::I64 => Some(Self::I64(0)), - WasmType::F32 => Some(Self::F32(0.0)), - WasmType::F64 => Some(Self::F64(0.0)), - WasmType::V128 => Some(Self::V128([0; 16])), - WasmType::Ref(ty) if ty.is_nullable() => Some(Self::Ref(RefValue::Null)), - WasmType::Ref(_) => None, - } - } - - #[inline] - /// Check if two values are equal, ignoring differences in NaN values. - pub fn eq_loose(&self, other: &Self) -> bool { - match (self, other) { - (Self::I32(a), Self::I32(b)) => a == b, - (Self::I64(a), Self::I64(b)) => a == b, - (Self::V128(a), Self::V128(b)) => a == b || Self::v128_nan_eq(*a, *b), - (Self::Ref(a), Self::Ref(b)) => a == b, - (Self::F32(a), Self::F32(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(), - (Self::F64(a), Self::F64(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(), - _ => false, - } - } - - fn v128_nan_eq(a: [u8; 16], b: [u8; 16]) -> bool { - let a_f32x4: [f32; 4] = [ - f32::from_le_bytes([a[0], a[1], a[2], a[3]]), - f32::from_le_bytes([a[4], a[5], a[6], a[7]]), - f32::from_le_bytes([a[8], a[9], a[10], a[11]]), - f32::from_le_bytes([a[12], a[13], a[14], a[15]]), - ]; - let b_f32x4: [f32; 4] = [ - f32::from_le_bytes([b[0], b[1], b[2], b[3]]), - f32::from_le_bytes([b[4], b[5], b[6], b[7]]), - f32::from_le_bytes([b[8], b[9], b[10], b[11]]), - f32::from_le_bytes([b[12], b[13], b[14], b[15]]), - ]; - - let all_nan_match = a_f32x4.iter().zip(b_f32x4.iter()).all(|(x, y)| { - if x.is_nan() && y.is_nan() { - true - } else if x.is_nan() || y.is_nan() { - false - } else { - x.to_bits() == y.to_bits() - } - }); - - if all_nan_match && a_f32x4.iter().any(|x| x.is_nan()) { - return true; - } - - let a_f64x2: [f64; 2] = [ - f64::from_le_bytes([a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]]), - f64::from_le_bytes([a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]]), - ]; - let b_f64x2: [f64; 2] = [ - f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]), - f64::from_le_bytes([b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]]), - ]; - - a_f64x2.iter().zip(b_f64x2.iter()).all(|(x, y)| { - if x.is_nan() && y.is_nan() { - true - } else if x.is_nan() || y.is_nan() { - false - } else { - x.to_bits() == y.to_bits() - } - }) && a_f64x2.iter().any(|x| x.is_nan()) - } -} +use crate::{RefType, StorageType}; /// Type of a WebAssembly value. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub enum WasmType { - /// A 32-bit integer + /// A 32-bit integer. I32, - /// A 64-bit integer + /// A 64-bit integer. I64, - /// A 32-bit float + /// A 32-bit float. F32, - /// A 64-bit float + /// A 64-bit float. F64, - /// A 128-bit vector + /// A 128-bit vector. V128, - /// A reference type + /// A reference type. Ref(RefType), } impl WasmType { #[inline] - pub const fn default_value(&self) -> Option { - WasmValue::default_for(*self) - } - - #[inline] - pub const fn is_simd(&self) -> bool { + pub const fn is_simd(self) -> bool { matches!(self, Self::V128) } } -macro_rules! impl_conversion_for_wasmvalue { - ($($t:ty => $variant:ident, $accessor:ident, $doc:literal);* $(;)?) => { - impl WasmValue { - $( - #[doc = $doc] - pub const fn $accessor(&self) -> Option<$t> { - match self { - Self::$variant(value) => Some(*value), - _ => None, - } - } - )* +impl From for WasmType { + fn from(value: StorageType) -> Self { + match value { + StorageType::I8 | StorageType::I16 => Self::I32, + StorageType::Value(value) => value, } - - $( - impl From<$t> for WasmValue { - #[inline] - fn from(i: $t) -> Self { - Self::$variant(i) - } - } - - impl TryFrom for $t { - type Error = (); - - #[inline] - fn try_from(value: WasmValue) -> Result { - if let WasmValue::$variant(i) = value { Ok(i) } else { Err(()) } - } - } - )* } } - -impl_conversion_for_wasmvalue! { - i32 => I32, as_i32, "Return the `i32` from a `WasmValue`, if it is an `I32`."; - i64 => I64, as_i64, "Return the `i64` from a `WasmValue`, if it is an `I64`."; - f32 => F32, as_f32, "Return the `f32` from a `WasmValue`, if it is a `F32`."; - f64 => F64, as_f64, "Return the `f64` from a `WasmValue`, if it is a `F64`."; - [u8; 16] => V128, as_v128, "Return the raw little-endian bytes from a `WasmValue`, if it is a `V128`."; - RefValue => Ref, as_ref, "Return the `RefValue` from a `WasmValue`, if it is a `Ref`."; -} - -macro_rules! impl_ref_conversion_for_wasmvalue { - ($($ty:ty => $variant:ident);* $(;)?) => { - $( - impl From<$ty> for WasmValue { - fn from(value: $ty) -> Self { - Self::Ref(RefValue::$variant(value)) - } - } - - impl TryFrom for $ty { - type Error = (); - - fn try_from(value: WasmValue) -> Result { - if let WasmValue::Ref(RefValue::$variant(value)) = value { Ok(value) } else { Err(()) } - } - } - )* - }; -} - -impl_ref_conversion_for_wasmvalue! { - crate::FuncRef => Func; - crate::ExternRef => Extern; - crate::AnyRef => Any; - crate::ExnRef => Exn; -} diff --git a/examples/archive.rs b/examples/archive.rs index 3f64704..3f118f2 100644 --- a/examples/archive.rs +++ b/examples/archive.rs @@ -11,13 +11,13 @@ const WASM: &str = r#" "#; fn main() -> Result<()> { - let wasm = wat::parse_str(WASM).expect("Failed to parse WAT"); + let wasm = wat::parse_str(WASM)?; let module = Parser::default().parse_module_bytes(wasm)?; - let twasm = module.serialize_twasm()?; - // Now, you could e.g. write `twasm` to a file called `add.twasm` - // and load it later in a different program. + // Serialize the optimized module for storage or distribution. + let twasm = module.serialize_twasm()?; + // Archived modules load without parsing Wasm again and should only come from trusted sources. let module = Module::try_from_twasm(&twasm)?; let mut store = Store::default(); let instance = ModuleInstance::instantiate(&mut store, &module, None)?; diff --git a/examples/basic.rs b/examples/basic.rs new file mode 100644 index 0000000..1f717c5 --- /dev/null +++ b/examples/basic.rs @@ -0,0 +1,26 @@ +use anyhow::Result; +use tinywasm::{ModuleInstance, Store}; + +const WASM: &str = r#" +(module + (func $add (param $lhs i32) (param $rhs i32) (result i32) + local.get $lhs + local.get $rhs + i32.add) + (export "add" (func $add))) +"#; + +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + + // Module is reusable, while Store owns the runtime state for this instance. + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + + // Typed handles validate parameters and results. Use func_untyped for dynamic values. + let add = instance.func::<(i32, i32), i32>(&store, "add")?; + + assert_eq!(add.call(&mut store, (1, 2))?, 3); + Ok(()) +} diff --git a/examples/exceptions.rs b/examples/exceptions.rs new file mode 100644 index 0000000..7c2f88e --- /dev/null +++ b/examples/exceptions.rs @@ -0,0 +1,28 @@ +use anyhow::{Result, bail}; +use tinywasm::{Error, ModuleInstance, Store, WasmValue}; + +const WASM: &str = r#" +(module + (tag $failure (export "failure") (param i32)) + (func (export "fail") (param i32) + local.get 0 + throw $failure)) +"#; + +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let fail = instance.func::(&store, "fail")?; + + // Uncaught guest exceptions cross the host boundary as owned ExnRef handles. + let Err(Error::Exception(exception)) = fail.call(&mut store, 42) else { + bail!("expected a guest exception"); + }; + + // The handle exposes the exception tag and typed payload values. + assert_eq!(exception.tag(&store)?, instance.tag("failure")?); + assert_eq!(exception.fields(&mut store)?, [WasmValue::I32(42)]); + Ok(()) +} diff --git a/examples/funcref_callbacks.rs b/examples/funcref_callbacks.rs deleted file mode 100644 index 959d798..0000000 --- a/examples/funcref_callbacks.rs +++ /dev/null @@ -1,123 +0,0 @@ -use anyhow::Result; -use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store, types::FuncRef}; - -const LHS: i32 = 5; -const RHS: i32 = 3; - -fn main() -> Result<()> { - run_passed_funcref_example()?; - run_returned_funcref_example()?; - Ok(()) -} - -fn run_passed_funcref_example() -> Result<()> { - // Host receives funcref and calls it via an exported proxy. - const WASM: &str = r#" - (module - (import "host" "call_this" (func $host_callback_caller (param funcref))) - (import "host" "mul" (func $host_mul (param $x i32) (param $y i32) (result i32))) - - (func $tell_host_to_call (export "tell_host_to_call") - (call $host_callback_caller (ref.func $add)) - (call $host_callback_caller (ref.func $sub)) - (call $host_callback_caller (ref.func $host_mul)) - ) - - (type $binop (func (param i32 i32) (result i32))) - - (table 3 funcref) - (elem (i32.const 0) $add $sub $host_mul) - (func $add (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add - ) - (func $sub (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.sub - ) - - (table $callback_register 1 funcref) - (func (export "call_binop_by_ref") (param funcref i32 i32) (result i32) - (table.set $callback_register (i32.const 0) (local.get 0)) - (call_indirect $callback_register (type $binop) (local.get 1)(local.get 2)(i32.const 0)) - ) - ) - "#; - - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - - let mul = HostFunction::from(|_, (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 caller = instance.func::<(), ()>(&store, "tell_host_to_call")?; - - caller.call(&mut store, ())?; - - Ok(()) -} - -fn run_returned_funcref_example() -> Result<()> { - // Wasm returns funcref values, host executes them through the same proxy. - const WASM: &str = r#" - (module - (import "host" "mul" (func $host_mul (param $x i32) (param $y i32) (result i32))) - (type $binop (func (param i32 i32) (result i32))) - (table 3 funcref) - (elem (i32.const 0) $add $sub $host_mul) - (func $add (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add - ) - (func $sub (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.sub - ) - (func $ref_to_funcs (export "what_should_host_call") (result funcref funcref funcref) - (ref.func $add) - (ref.func $sub) - (ref.func $host_mul) - ) - - (table $callback_register 1 funcref) - (func $call (export "call_binop_by_ref") (param funcref i32 i32) (result i32) - (table.set $callback_register (i32.const 0) (local.get 0)) - (call_indirect $callback_register (type $binop) (local.get 1)(local.get 2)(i32.const 0)) - ) - ) - "#; - - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - let mut imports = Imports::new(); - - let mul = HostFunction::from(|_, (lhs, rhs): (i32, i32)| -> tinywasm::Result { Ok(lhs * rhs) }); - imports.define("host", "mul", mul); - - let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; - let (add_ref, sub_ref, mul_ref) = { - let get_funcrefs = instance.func::<(), (FuncRef, FuncRef, FuncRef)>(&store, "what_should_host_call")?; - get_funcrefs.call(&mut store, ())? - }; - - let call_by_ref = instance.func::<(FuncRef, i32, i32), i32>(&store, "call_binop_by_ref")?; - for func_ref in [add_ref, sub_ref, mul_ref] { - let _result = call_by_ref.call(&mut store, (func_ref, LHS, RHS))?; - } - Ok(()) -} diff --git a/examples/gc.rs b/examples/gc.rs new file mode 100644 index 0000000..9a73d04 --- /dev/null +++ b/examples/gc.rs @@ -0,0 +1,33 @@ +use anyhow::Result; +use tinywasm::{ModuleInstance, Store, StructRef, WasmValue}; + +const WASM: &str = r#" +(module + (type $cube (struct (field (mut i32)) (field (mut i32)))) + (func $make-cube (result (ref $cube)) + i32.const 3 + i32.const 4 + struct.new $cube) + (func (export "cube") (result (ref struct)) + call $make-cube)) +"#; + +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let cube = instance.func::<(), StructRef>(&store, "cube")?.call(&mut store, ())?; + + // GC handles are Store-bound and expose typed field access through that Store. + assert_eq!(cube.fields(&mut store)?, [WasmValue::I32(3), WasmValue::I32(4)]); + cube.set_field(&mut store, 0, WasmValue::I32(5))?; + + // Cloned handles keep their guest objects live across explicit collection. + let retained = cube.clone(); + drop(cube); + store.gc()?; + + assert_eq!(retained.field(&mut store, 0)?, WasmValue::I32(5)); // still alive + Ok(()) +} diff --git a/examples/linking.rs b/examples/linking.rs index 2df7133..92c0b7d 100644 --- a/examples/linking.rs +++ b/examples/linking.rs @@ -1,7 +1,6 @@ use anyhow::Result; use tinywasm::{ModuleInstance, Store}; -// WebAssembly module defining and exporting an `add` function. const WASM_ADD: &str = r#" (module (func $add (param $lhs i32) (param $rhs i32) (result i32) @@ -11,7 +10,6 @@ const WASM_ADD: &str = r#" (export "add" (func $add))) "#; -// WebAssembly module importing an `add` function and using it. const WASM_IMPORT: &str = r#" (module (import "adder" "add" (func $add (param i32 i32) (result i32))) @@ -24,25 +22,23 @@ const WASM_IMPORT: &str = r#" "#; fn main() -> Result<()> { - let wasm_add = wat::parse_str(WASM_ADD).expect("failed to parse wat"); - let wasm_import = wat::parse_str(WASM_IMPORT).expect("failed to parse wat"); + let wasm_add = wat::parse_str(WASM_ADD)?; + let wasm_import = wat::parse_str(WASM_IMPORT)?; let add_module = tinywasm::parse_bytes(&wasm_add)?; let import_module = tinywasm::parse_bytes(&wasm_import)?; let mut store = Store::default(); - // Instantiate the `add` module. let add_instance = ModuleInstance::instantiate(&mut store, &add_module, None)?; - // Link the `adder` namespace to the `add` module's instance. + // Imports can link a module namespace and define individual host items together. let mut imports = tinywasm::Imports::new(); imports.link_module("adder", add_instance)?; - // Instantiate the `import` module with the linked imports. let import_instance = ModuleInstance::instantiate(&mut store, &import_module, Some(&imports))?; - // Call the `main` function, which uses the imported `add` function. + // Calling `main` crosses the linked module boundary to `add`. let main = import_instance.func::<(), i32>(&store, "main")?; assert_eq!(main.call(&mut store, ())?, 3); diff --git a/examples/reentrance.rs b/examples/reentrance.rs index 0084a61..cf57891 100644 --- a/examples/reentrance.rs +++ b/examples/reentrance.rs @@ -23,10 +23,11 @@ fn main() -> Result<()> { let mut store = Store::default(); let call_add_twice = HostFunction::from(|mut ctx: FuncContext<'_>, value: i32| { + // FuncContext exposes the active module and its Store to the callback. let add_one = ctx.module().func::(ctx.store(), "add_one")?; - // Use ctx.call for reentrant calls from host functions. Function::call - // starts a root invocation and cannot preserve the active call stacks. + // Use ctx.call while a host callback has an active Wasm invocation. + // Function::call only starts top-level invocations. let value = ctx.call(&add_one, value)?; ctx.call(&add_one, value) }); diff --git a/examples/references.rs b/examples/references.rs new file mode 100644 index 0000000..b02dd07 --- /dev/null +++ b/examples/references.rs @@ -0,0 +1,34 @@ +use anyhow::Result; +use tinywasm::{FuncRef, HostFunction, Imports, ModuleInstance, Store}; + +const WASM: &str = r#" +(module + (type $callback (func (param i32) (result i32))) + (import "host" "double" (func $double (type $callback))) + (elem declare func $double) + (func (export "callback") (result funcref) + ref.func $double) + (func (export "apply") (param funcref i32) (result i32) + local.get 1 + local.get 0 + ref.cast (ref $callback) + call_ref $callback)) +"#; + +fn main() -> Result<()> { + let mut store = Store::default(); + let mut imports = Imports::new(); + // Imports resolve reusable host definitions against each module's runtime types. + // HostFunction::instantiate is available when a standalone Function is needed. + imports.define("host", "double", HostFunction::from(|_, value: i32| -> tinywasm::Result { Ok(value * 2) })); + + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + // Option maps nullable funcref. Bare FuncRef maps a non-null reference. + let callback = instance.func::<(), Option>(&store, "callback")?.call(&mut store, ())?; + let apply = instance.func::<(Option, i32), i32>(&store, "apply")?; + + assert_eq!(apply.call(&mut store, (callback, 21))?, 42); + Ok(()) +} diff --git a/examples/resumable.rs b/examples/resumable.rs index 26b5f47..70b0db1 100644 --- a/examples/resumable.rs +++ b/examples/resumable.rs @@ -29,10 +29,12 @@ fn main() -> Result<()> { let instance = ModuleInstance::instantiate(&mut store, &module, None)?; let count_down = instance.func::(&store, "count_down")?; + // A resumable call returns execution state instead of running to completion. let mut execution = count_down.call_resumable(&mut store, 10_000)?; let fuel_per_round = 128; let mut fuel_rounds = 0; + // Each resume call limits one round. std builds also support wall-clock budgets. let result = loop { fuel_rounds += 1; match execution.resume_with_fuel(fuel_per_round)? { diff --git a/examples/rust.rs b/examples/rust.rs new file mode 100644 index 0000000..24b3b73 --- /dev/null +++ b/examples/rust.rs @@ -0,0 +1,226 @@ +use std::hint::black_box; + +use anyhow::{Result, anyhow}; +use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; + +/// Examples of using WebAssembly compiled from Rust with tinywasm. +/// +/// These examples are meant to be run with `cargo run --example rust `. +/// For example, `cargo run --example rust hello`. +/// +/// To run these, you first need to compile the Rust examples to WebAssembly: +/// +/// ```sh +/// ./examples/rust/build.sh +/// ``` +/// +/// This requires the `wasm32-unknown-unknown` target, `binaryen`, and `wabt` to be installed: +/// +/// `rustup target add wasm32-unknown-unknown`. +/// +/// +fn main() -> Result<()> { + pretty_env_logger::init(); + + if !std::path::Path::new("./examples/rust/out/").exists() { + return Err(anyhow!("No WebAssembly files found. See examples/rust.rs for instructions.")); + } + + let args = std::env::args().collect::>(); + if args.len() < 2 { + println!("Usage: cargo run --example rust "); + println!("Available examples:"); + println!(" hello"); + println!(" printi32"); + println!(" host_fn"); + println!(" fibonacci - calculate fibonacci(30)"); + println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); + println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); + println!(" argon2id - run argon2id(1000, 2, 1)"); + return Ok(()); + } + + match args[1].as_str() { + "hello" => hello()?, + "printi32" => printi32()?, + "fibonacci" => fibonacci()?, + "tinywasm" => tinywasm()?, + "tinywasm_no_std" => tinywasm_no_std()?, + "argon2id" => argon2id()?, + "host_fn" => host_fn()?, + "all" => { + println!("Running all examples"); + println!("\nhello.wasm:"); + hello()?; + println!("\nprinti32.wasm:"); + printi32()?; + println!("\nfibonacci.wasm:"); + fibonacci()?; + println!("\ntinywasm.wasm:"); + tinywasm()?; + println!("\ntinywasm_no_std.wasm:"); + tinywasm_no_std()?; + println!("argon2id.wasm:"); + argon2id()?; + println!("\nhost_fn.wasm:"); + host_fn()?; + } + _ => {} + } + + Ok(()) +} + +fn tinywasm() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/tinywasm.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 tinywasm_no_std() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/tinywasm_no_std.wasm")?; + let mut store = Store::default(); + + let mut imports = Imports::new(); + imports.define("env", "printi32", HostFunction::from(|_: 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(); + + // The host callback reads the guest's exported memory through FuncContext. + let print_utf8 = HostFunction::from(|ctx: FuncContext<'_>, (ptr, len): (i64, i32)| { + let mem = ctx.memory("memory")?; + let string = mem.read_string(ctx.store(), ptr as usize, len as usize)?; + println!("{string}"); + Ok(()) + }); + + let mut imports = Imports::new(); + imports.define("env", "print_utf8", print_utf8); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let arg_ptr = instance.func::<(), i32>(&store, "arg_ptr")?.call(&mut store, ())?; + let arg = b"world"; + + // Write the host argument into guest memory before calling the Rust export. + instance.memory("memory")?.copy_from_slice(&mut store, arg_ptr as usize, arg)?; + let hello = instance.func::(&store, "hello")?; + hello.call(&mut store, arg.len() as i32)?; + + Ok(()) +} + +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(|_: FuncContext<'_>, (left, right): (i64, i32)| { + assert_eq!(left, 1); + assert_eq!(right, 2); + Ok(left as i32 + right) + }); + + let mut imports = Imports::new(); + imports.define("env", "bar", bar); + + 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(()) +} + +fn printi32() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/print.opt.wasm")?; + let mut store = Store::default(); + + let printi32 = HostFunction::from(|_: FuncContext<'_>, x: i32| { + println!("{x}"); + Ok(()) + }); + + let mut imports = 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(()) +} + +fn fibonacci() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/fibonacci.opt.wasm")?; + let mut store = Store::default(); + + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let fibonacci = instance.func::(&store, "fibonacci_recursive")?; + let n = 26; + let result = fibonacci.call(&mut store, n)?; + println!("fibonacci({n}) = {result}"); + + Ok(()) +} + +fn argon2id() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/argon2id.opt.wasm")?; + let mut store = Store::default(); + + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let argon2id = instance.func::<(i32, i32, i32), i32>(&store, "argon2id")?; + argon2id.call(&mut store, (1000, 2, 1))?; + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_hello() { + hello().unwrap(); + } + + #[test] + fn test_printi32() { + printi32().unwrap(); + } + + #[test] + fn test_fibonacci() { + fibonacci().unwrap(); + } + + #[test] + fn test_tinywasm() { + tinywasm().unwrap(); + } + + #[test] + fn test_tinywasm_no_std() { + tinywasm_no_std().unwrap(); + } + + #[test] + fn test_argon2id() { + argon2id().unwrap(); + } +} diff --git a/examples/rust/README.md b/examples/rust/README.md index 8d3178a..305a29c 100644 --- a/examples/rust/README.md +++ b/examples/rust/README.md @@ -1,9 +1,9 @@ # WebAssembly Rust Examples This is a separate crate that generates WebAssembly from Rust code. -It is used by the `wasm-rust` example. +It is used by the `rust` example. Requires the `wasm32-unknown-unknown` target to be installed. -To build the example artifacts used by `cargo run --example wasm-rust -- `, run `./examples/rust/build.sh`. +To build the example artifacts used by `cargo run --example rust -- `, run `./examples/rust/build.sh`. That script also requires `binaryen` and `wabt` to be installed. diff --git a/examples/simple.rs b/examples/simple.rs deleted file mode 100644 index 0d57265..0000000 --- a/examples/simple.rs +++ /dev/null @@ -1,22 +0,0 @@ -use anyhow::Result; -use tinywasm::{ModuleInstance, Store}; - -const WASM: &str = r#" -(module - (func $add (param $lhs i32) (param $rhs i32) (result i32) - local.get $lhs - local.get $rhs - i32.add) - (export "add" (func $add))) -"#; - -fn main() -> Result<()> { - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let add = instance.func::<(i32, i32), i32>(&store, "add")?; - - assert_eq!(add.call(&mut store, (1, 2))?, 3); - Ok(()) -} diff --git a/examples/simple2.rs b/examples/simple2.rs deleted file mode 100644 index f673dfe..0000000 --- a/examples/simple2.rs +++ /dev/null @@ -1,21 +0,0 @@ -use anyhow::Result; -use tinywasm::{ModuleInstance, Store}; - -const WASM: &str = r#" -(module - (func $return (param $lhs i32) (param $rhs i64) (result i32 i64) - local.get $lhs - local.get $rhs) - (export "return" (func $return))) -"#; - -fn main() -> Result<()> { - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let add = instance.func::<(i32, i64), (i32, i64)>(&store, "return")?; - - assert_eq!(add.call(&mut store, (1, 2))?, (1, 2)); - Ok(()) -} diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs deleted file mode 100644 index 0cfb0ce..0000000 --- a/examples/wasm-rust.rs +++ /dev/null @@ -1,224 +0,0 @@ -use std::hint::black_box; - -use anyhow::{Result, anyhow}; -use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; - -/// Examples of using WebAssembly compiled from Rust with tinywasm. -/// -/// These examples are meant to be run with `cargo run --example wasm-rust `. -/// For example, `cargo run --example wasm-rust hello`. -/// -/// To run these, you first need to compile the Rust examples to WebAssembly: -/// -/// ```sh -/// ./examples/rust/build.sh -/// ``` -/// -/// This requires the `wasm32-unknown-unknown` target, `binaryen`, and `wabt` to be installed: -/// -/// `rustup target add wasm32-unknown-unknown`. -/// -/// -fn main() -> Result<()> { - pretty_env_logger::init(); - - if !std::path::Path::new("./examples/rust/out/").exists() { - return Err(anyhow!("No WebAssembly files found. See examples/wasm-rust.rs for instructions.")); - } - - let args = std::env::args().collect::>(); - if args.len() < 2 { - println!("Usage: cargo run --example wasm-rust "); - println!("Available examples:"); - println!(" hello"); - println!(" printi32"); - println!(" host_fn"); - println!(" fibonacci - calculate fibonacci(30)"); - println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); - println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); - println!(" argon2id - run argon2id(1000, 2, 1)"); - return Ok(()); - } - - match args[1].as_str() { - "hello" => hello()?, - "printi32" => printi32()?, - "fibonacci" => fibonacci()?, - "tinywasm" => tinywasm()?, - "tinywasm_no_std" => tinywasm_no_std()?, - "argon2id" => argon2id()?, - "host_fn" => host_fn()?, - "all" => { - println!("Running all examples"); - println!("\nhello.wasm:"); - hello()?; - println!("\nprinti32.wasm:"); - printi32()?; - println!("\nfibonacci.wasm:"); - fibonacci()?; - println!("\ntinywasm.wasm:"); - tinywasm()?; - println!("\ntinywasm_no_std.wasm:"); - tinywasm_no_std()?; - println!("argon2id.wasm:"); - argon2id()?; - println!("\nhost_fn.wasm:"); - host_fn()?; - } - _ => {} - } - - Ok(()) -} - -fn tinywasm() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/tinywasm.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 tinywasm_no_std() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/tinywasm_no_std.wasm")?; - let mut store = Store::default(); - - let mut imports = Imports::new(); - imports.define("env", "printi32", HostFunction::from(|_: 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(); - - 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}"); - Ok(()) - }); - - let mut imports = Imports::new(); - imports.define("env", "print_utf8", print_utf8); - - 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"; - - instance.memory("memory")?.copy_from_slice(&mut store, arg_ptr as usize, arg)?; - let hello = instance.func::(&store, "hello")?; - hello.call(&mut store, arg.len() as i32)?; - - Ok(()) -} - -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(|_: FuncContext<'_>, (left, right): (i64, i32)| { - assert_eq!(left, 1); - assert_eq!(right, 2); - Ok(left as i32 + right) - }); - - let mut imports = Imports::new(); - imports.define("env", "bar", bar); - - 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(()) -} - -fn printi32() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/print.opt.wasm")?; - let mut store = Store::default(); - - let printi32 = HostFunction::from(|_: FuncContext<'_>, x: i32| { - println!("{x}"); - Ok(()) - }); - - let mut imports = 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(()) -} - -fn fibonacci() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/fibonacci.opt.wasm")?; - let mut store = Store::default(); - - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let fibonacci = instance.func::(&store, "fibonacci_recursive")?; - let n = 26; - let result = fibonacci.call(&mut store, n)?; - println!("fibonacci({n}) = {result}"); - - Ok(()) -} - -fn argon2id() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/argon2id.opt.wasm")?; - let mut store = Store::default(); - - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let argon2id = instance.func::<(i32, i32, i32), i32>(&store, "argon2id")?; - argon2id.call(&mut store, (1000, 2, 1))?; - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_hello() { - hello().unwrap(); - } - - #[test] - fn test_printi32() { - printi32().unwrap(); - } - - #[test] - fn test_fibonacci() { - fibonacci().unwrap(); - } - - #[test] - fn test_tinywasm() { - tinywasm().unwrap(); - } - - #[test] - fn test_tinywasm_no_std() { - tinywasm_no_std().unwrap(); - } - - #[test] - fn test_argon2id() { - argon2id().unwrap(); - } -} -- 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 'crates/cli/Cargo.toml') 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 'crates/cli/Cargo.toml') 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 'crates/cli/Cargo.toml') 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 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 'crates/cli/Cargo.toml') 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