diff options
| author | Henry <mail@henrygressmann.de> | 2026-09-22 12:44:34 +0200 |
|---|---|---|
| committer | Henry <mail@henrygressmann.de> | 2026-09-22 12:44:34 +0200 |
| commit | b45a98a85c776d956a797773acd2f198c06b40ed (patch) | |
| tree | b2f28ce1dad335becfaa67e02d9ee1e5a95feb35 | |
| parent | fa7b34fb0ad7fe8afa7e78af712a40c209923eb2 (diff) | |
Signed-off-by: Henry <mail@henrygressmann.de>
| -rw-r--r-- | CHANGELOG.md | 7 | ||||
| -rw-r--r-- | crates/tinywasm/src/func/mod.rs | 13 | ||||
| -rw-r--r-- | crates/tinywasm/src/imports.rs | 112 | ||||
| -rw-r--r-- | crates/tinywasm/src/instance.rs | 17 | ||||
| -rw-r--r-- | crates/tinywasm/src/reference/store.rs | 24 | ||||
| -rw-r--r-- | crates/tinywasm/src/store/memory/vec.rs | 17 | ||||
| -rw-r--r-- | examples/doom/src/runtime.rs | 46 |
7 files changed, 163 insertions, 73 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 0059446..253f5a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ 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] + +### Added + +- Added new `Memory::data` and `Memory::data_mut` methods for direct access to linear memory. +- Added several internal methods to support a future c-api crate + ## [0.11.0] - 2026-09-19 This release adds garbage collection and typed function reference support, single-pass parsing, and an optional tail-call dispatch backend. The internal instruction representation is now 8 bytes, down from 16, and pluggable memory backends were removed for performance reasons (however, `ResourceLimiter` was added to allow, reject, or trap memory allocation and growth requests). diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs index 744356d..cf3c855 100644 --- a/crates/tinywasm/src/func/mod.rs +++ b/crates/tinywasm/src/func/mod.rs @@ -39,6 +39,19 @@ pub struct Function { } impl Function { + /// Resolves a function reference into a callable handle in its owning store. + /// + /// Returns an error if the reference belongs to another store or does not + /// identify a valid function. + pub fn from_func_ref(store: &Store, reference: FuncRef) -> Result<Self> { + let addr = reference.addr(store.id()).ok_or(crate::Trap::InvalidStore)?; + if !store.state.funcs.contains(addr) { + return Err(crate::Trap::InvalidReference.into()); + } + let module_id = if store.state.funcs.is_host(addr) { 0 } else { store.state.funcs.wasm(addr).owner }; + Ok(Self { item: StoreItem::new(store.id(), addr), module_id }) + } + /// Returns this function as a Store-aware WebAssembly function reference. pub fn as_func_ref(&self, store: &Store) -> Result<FuncRef> { self.item.validate_store(store)?; diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index 35affab..49234e6 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -170,11 +170,33 @@ impl Imports { self } - /// Returns an explicitly defined import without cloning its handle. - pub(crate) fn defined(&self, import: &Import) -> Option<&Extern> { - self.externs.get(import.module.as_ref())?.get(import.name.as_ref()) + /// Resolves names in module import order, with explicit definitions taking precedence. + pub(crate) fn resolve(&self, module: &Module) -> Result<Vec<Extern>> { + module + .imports + .iter() + .map(|import| { + if let Some(value) = + self.externs.get(import.module.as_ref()).and_then(|items| items.get(import.name.as_ref())) + { + return Ok(value.clone()); + } + let instance = + self.modules.get(import.module.as_ref()).ok_or_else(|| LinkingError::unknown_import(import))?; + let item = instance.extern_item(&import.name).map_err(|_| LinkingError::unknown_import(import))?; + Ok(match item { + crate::ExternItem::Func(value) => Extern::Function(value), + crate::ExternItem::Global(value) => Extern::Global(value), + crate::ExternItem::Memory(value) => Extern::Memory(value), + crate::ExternItem::Table(value) => Extern::Table(value), + crate::ExternItem::Tag(value) => Extern::Tag(value), + }) + }) + .collect() } +} +impl ResolvedImports { fn compare_types<T: PartialEq>(import: &Import, actual: &T, expected: &T) -> Result<()> { if expected != actual { return cold!(Err(LinkingError::incompatible_import_type(import).into())); @@ -223,12 +245,16 @@ impl Imports { Ok(()) } - pub(crate) fn link( - &self, + /// Validates and binds imports in module import order. + pub(crate) fn new( store: &mut crate::Store, module: &Module, type_addrs: &[TypeAddr], + externs: &[Extern], ) -> Result<ResolvedImports> { + if externs.len() != module.imports.len() { + return Err(crate::Error::other("ordered import count does not match module")); + } let (global_count, table_count, mem_count, func_count, tag_count) = module.imports.iter().fold((0, 0, 0, 0, 0), |(g, t, m, f, e), import| match import.kind { ImportKind::Global(_) => (g + 1, t, m, f, e), @@ -246,50 +272,42 @@ impl Imports { tags: Vec::with_capacity(tag_count + module.tags.len()), }; - for import in &*module.imports { - let val = if let Some(defined) = self.defined(import) { - match defined { - Extern::Global(global) => { - global.0.validate_store(store)?; - ExternVal::Global(global.0.addr) - } - Extern::Table(table) => { - table.0.validate_store(store)?; - ExternVal::Table(table.0.addr) - } - Extern::Memory(memory) => { - memory.0.validate_store(store)?; - ExternVal::Memory(memory.0.addr) - } - Extern::Function(func) => { - func.item.validate_store(store)?; - ExternVal::Func(func.addr()) - } - Extern::HostFunction(func) => { - let ImportKind::Function(type_idx) = import.kind else { - return cold!(Err(LinkingError::incompatible_import_type(import).into())); - }; - let expected_type_addr = type_addrs - .get(type_idx as usize) - .ok_or_else(|| LinkingError::incompatible_import_type(import))?; - let actual_ty = func.resolve_import_type(type_addrs)?; - let actual_type_addr = store.register_host_type(&actual_ty); - if !store.state.type_addr_is_subtype(actual_type_addr, *expected_type_addr) { - return cold!(Err(LinkingError::incompatible_import_type(import).into())); - } - ExternVal::Func(func.instantiate_registered(store, actual_type_addr).addr()) - } - Extern::Tag(tag) => { - tag.0.validate_store(store)?; - ExternVal::Tag(tag.0.addr) + for (import, defined) in module.imports.iter().zip(externs) { + let val = match defined { + Extern::Global(global) => { + global.0.validate_store(store)?; + ExternVal::Global(global.0.addr) + } + Extern::Table(table) => { + table.0.validate_store(store)?; + ExternVal::Table(table.0.addr) + } + Extern::Memory(memory) => { + memory.0.validate_store(store)?; + ExternVal::Memory(memory.0.addr) + } + Extern::Function(func) => { + func.item.validate_store(store)?; + ExternVal::Func(func.addr()) + } + Extern::HostFunction(func) => { + let ImportKind::Function(type_idx) = import.kind else { + return cold!(Err(LinkingError::incompatible_import_type(import).into())); + }; + let expected_type_addr = type_addrs + .get(type_idx as usize) + .ok_or_else(|| LinkingError::incompatible_import_type(import))?; + let actual_ty = func.resolve_import_type(type_addrs)?; + let actual_type_addr = store.register_host_type(&actual_ty); + if !store.state.type_addr_is_subtype(actual_type_addr, *expected_type_addr) { + return cold!(Err(LinkingError::incompatible_import_type(import).into())); } + ExternVal::Func(func.instantiate_registered(store, actual_type_addr).addr()) + } + Extern::Tag(tag) => { + tag.0.validate_store(store)?; + ExternVal::Tag(tag.0.addr) } - } else { - let Some(instance) = self.modules.get(import.module.as_ref()) else { - return cold!(Err(LinkingError::unknown_import(import).into())); - }; - instance.validate_store(store)?; - instance.export_addr(&import.name).ok_or_else(|| LinkingError::unknown_import(import))? }; if val.kind() != (&import.kind).into() { diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 31bb733..7eda501 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -173,10 +173,23 @@ impl ModuleInstance { /// /// See <https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation> pub fn instantiate_no_start(store: &mut Store, module: &Module, imports: Option<&Imports>) -> Result<Self> { + let default_imports = Imports::default(); + let imports = imports.unwrap_or(&default_imports).resolve(module)?; + Self::instantiate_inner(store, module, &imports) + } + + /// **Unstable**: This method is for internal use only and may change or be removed at any time. + #[doc(hidden)] + pub fn instantiate_ordered(store: &mut Store, module: &Module, imports: &[crate::Extern]) -> Result<Self> { + let instance = Self::instantiate_inner(store, module, imports)?; + instance.start(store)?; + Ok(instance) + } + + fn instantiate_inner(store: &mut Store, module: &Module, imports: &[crate::Extern]) -> Result<Self> { let type_addrs = store.register_module_types(&module.types); let id = store.next_module_instance_id(); - let default_imports = Imports::default(); - let mut addrs = imports.unwrap_or(&default_imports).link(store, module, &type_addrs)?; + let mut addrs = crate::imports::ResolvedImports::new(store, module, &type_addrs, imports)?; let imported_funcs = addrs.funcs.len(); addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs)); addrs.tags.extend(store.init_tags(&module.tags, &type_addrs)); diff --git a/crates/tinywasm/src/reference/store.rs b/crates/tinywasm/src/reference/store.rs index e763e70..349feb4 100644 --- a/crates/tinywasm/src/reference/store.rs +++ b/crates/tinywasm/src/reference/store.rs @@ -351,6 +351,30 @@ impl crate::std::io::Seek for MemoryCursor<'_> { } impl Memory { + /// **Unstable**: This method is for internal use only and may change or be removed at any time. + /// + /// Returns a raw mutable pointer to the memory's backing allocation. + /// Growth may invalidate the pointer. The caller must keep the store alive + /// and uphold Rust's aliasing rules when dereferencing it. + #[doc(hidden)] + pub fn data_ptr(&self, store: &mut Store) -> Result<*mut u8> { + Ok(self.instance_mut(store)?.inner.data_ptr()) + } + + /// Borrows the complete linear memory. + /// + /// The borrow prevents execution or growth through this store until it ends. + pub fn data<'a>(&self, store: &'a Store) -> Result<&'a [u8]> { + Ok(self.instance(store)?.inner.data()) + } + + /// Borrows the complete linear memory exclusively. + /// + /// The borrow prevents execution or growth through this store until it ends. + pub fn data_mut<'a>(&self, store: &'a mut Store) -> Result<&'a mut [u8]> { + Ok(self.instance_mut(store)?.inner.data_mut()) + } + /// Create a new memory in the given store. pub fn try_new(store: &mut Store, ty: MemoryType) -> Result<Self> { let addr = store.state.memories.len() as MemAddr; diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs index e8586c0..b14f54d 100644 --- a/crates/tinywasm/src/store/memory/vec.rs +++ b/crates/tinywasm/src/store/memory/vec.rs @@ -12,6 +12,23 @@ pub(crate) struct VecMemory { } impl VecMemory { + /// Returns a raw mutable pointer to the memory's backing allocation. + /// Growth may invalidate the pointer. The caller must keep the store alive + /// and uphold Rust's aliasing rules when dereferencing it. + pub(crate) fn data_ptr(&mut self) -> *mut u8 { + self.data.as_mut_ptr() + } + + /// Borrows the backing bytes. + pub(crate) fn data(&self) -> &[u8] { + &self.data + } + + /// Borrows the backing bytes exclusively. + pub(crate) fn data_mut(&mut self) -> &mut [u8] { + &mut self.data + } + /// Tries to create a new memory with `len` zero-initialized bytes. pub(crate) fn try_new(_arch: MemoryArch, len: usize, _max_len: usize) -> Result<Self, crate::Trap> { let mut data = Vec::new(); diff --git a/examples/doom/src/runtime.rs b/examples/doom/src/runtime.rs index 745e3bd..2e50a20 100644 --- a/examples/doom/src/runtime.rs +++ b/examples/doom/src/runtime.rs @@ -4,7 +4,7 @@ use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; -use anyhow::Result; +use anyhow::{Context, Result}; use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; const IMPORT_MODULE: &str = "env"; @@ -18,7 +18,6 @@ pub struct Runtime { key_down: tinywasm::FunctionTyped<i32, ()>, key_up: tinywasm::FunctionTyped<i32, ()>, memory: tinywasm::Memory, - framebuffer_bytes: Vec<u8>, } impl Runtime { @@ -41,18 +40,7 @@ impl Runtime { memory.write_cstring_bytes(&mut store, buf_ptr, &wad_path_string)?; init.call(&mut store, ())?; - let width = SCREEN_WIDTH; - let height = SCREEN_HEIGHT; - - Ok(Self { - store, - update, - framebuffer, - key_down, - key_up, - memory, - framebuffer_bytes: vec![0; width * height * 4], - }) + Ok(Self { store, update, framebuffer, key_down, key_up, memory }) } pub fn tick(&mut self) -> Result<()> { @@ -61,11 +49,15 @@ impl Runtime { } pub fn write_framebuffer(&mut self, dst: &mut [u32]) -> Result<()> { - let ptr = self.framebuffer.call(&mut self.store, ())? as usize; - self.memory.read_exact(&self.store, ptr, &mut self.framebuffer_bytes)?; - for (index, pixel) in dst.iter_mut().enumerate() { - let byte_index = index * 4; - let chunk = &self.framebuffer_bytes[byte_index..byte_index + 4]; + let ptr = self.framebuffer.call(&mut self.store, ())? as u32 as usize; + let framebuffer = self + .memory + .data(&self.store)? + .get(ptr..) + .and_then(|data| data.get(..SCREEN_WIDTH * SCREEN_HEIGHT * 4)) + .context("framebuffer is outside guest memory")?; + anyhow::ensure!(dst.len() <= SCREEN_WIDTH * SCREEN_HEIGHT, "framebuffer destination is too large"); + for (pixel, chunk) in dst.iter_mut().zip(framebuffer.chunks_exact(4)) { *pixel = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | chunk[2] as u32; } Ok(()) @@ -228,13 +220,19 @@ fn build_imports() -> Imports { imports.define( IMPORT_MODULE, "host_write", - HostFunction::from(|mut 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 state = ctx.state_mut::<HostState>().unwrap(); - let Some(file) = state.files.get_mut(&handle) else { + HostFunction::from(|ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { + let data = ctx.memory("memory")?.data(ctx.store())?; + let offset = buf_ptr as u32 as usize; + let len = count.max(0) as usize; + let data = data + .get(offset..) + .and_then(|data| data.get(..len)) + .ok_or(tinywasm::Trap::MemoryOutOfBounds { offset, len, max: data.len() })?; + let state = ctx.state::<HostState>().unwrap(); + let Some(mut file) = state.files.get(&handle) else { return Ok(-1); }; - let written = file.write(&data).map_err(|err| tinywasm::Error::Other(err.to_string()))?; + let written = file.write(data).map_err(|err| tinywasm::Error::Other(err.to_string()))?; Ok(written as i32) }), ); |
