summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md2
-rw-r--r--Cargo.lock18
-rw-r--r--README.md3
-rw-r--r--crates/parser/Cargo.toml11
-rw-r--r--crates/parser/src/lib.rs3
-rw-r--r--crates/parser/src/module.rs16
-rw-r--r--crates/parser/src/parallel.rs5
-rw-r--r--crates/tinywasm/Cargo.toml7
-rw-r--r--crates/tinywasm/src/engine.rs15
-rw-r--r--crates/tinywasm/src/func/context.rs3
-rw-r--r--crates/tinywasm/src/func/host.rs52
-rw-r--r--crates/tinywasm/src/func/mod.rs16
-rw-r--r--crates/tinywasm/src/func/resume.rs13
-rw-r--r--crates/tinywasm/src/instance.rs11
-rw-r--r--crates/tinywasm/src/interpreter/executor.rs35
-rw-r--r--crates/tinywasm/src/lib.rs6
-rw-r--r--crates/tinywasm/src/reference/managed.rs25
-rw-r--r--crates/tinywasm/src/shared.rs9
-rw-r--r--crates/tinywasm/src/store/function.rs7
-rw-r--r--crates/tinywasm/src/store/gc/object.rs13
-rw-r--r--crates/tinywasm/src/store/gc/roots.rs11
-rw-r--r--crates/tinywasm/src/store/mod.rs12
-rw-r--r--crates/tinywasm/src/store/state.rs4
-rw-r--r--crates/tinywasm/tests/managed_exceptions.rs3
-rw-r--r--crates/tinywasm/tests/memory.rs22
-rw-r--r--crates/types/Cargo.toml15
-rw-r--r--crates/types/src/archive.rs21
-rw-r--r--crates/types/src/lib.rs28
-rw-r--r--crates/types/src/types.rs6
29 files changed, 244 insertions, 148 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bad8caf..a786aa0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `ResourceLimiter` callbacks for memory and table allocation or growth
- A default `validate` Cargo feature & parser option to skip wasm validation
- Optional parse-time operand deduplication to reduce `.twasm` archive size
+- Optional `send` support for moving stores and store-local handles across threads
+- Optional portable atomic shared pointers and counters for targets without native compare-and-swap
### Changed
diff --git a/Cargo.lock b/Cargo.lock
index ac0895a..1663c7c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -571,6 +571,22 @@ dependencies = [
]
[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"
+dependencies = [
+ "portable-atomic",
+ "serde",
+]
+
+[[package]]
name = "postcard"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -864,6 +880,7 @@ version = "0.11.0-pre.0"
dependencies = [
"libm",
"log",
+ "portable-atomic",
"tinywasm-cli",
"tinywasm-parser",
"tinywasm-types",
@@ -919,6 +936,7 @@ name = "tinywasm-types"
version = "0.11.0-pre.0"
dependencies = [
"log",
+ "portable-atomic-util",
"postcard",
"serde",
]
diff --git a/README.md b/README.md
index 70578dd..8b400de 100644
--- a/README.md
+++ b/README.md
@@ -57,9 +57,10 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin
- **`debug`:** Derives `Debug` for runtime types. Enabled by default.
- **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default.
- **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`).
+- **`send`:** Makes stores and store-local handles movable across threads
- **`simd-x86`:** Enables x86-specific SIMD intrinsics and uses `unsafe` internally.
-With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`, making it usable in `no_std + alloc` environments.
+With default features disabled, `tinywasm` supports `no_std + alloc` and depends only on `libm`.
Use [`Engine`](https://docs.rs/tinywasm/latest/tinywasm/engine/struct.Engine.html) and [`engine::Config`](https://docs.rs/tinywasm/latest/tinywasm/engine/struct.Config.html) for non-default fuel accounting, stack sizing, or GC collection thresholds. A configured `ResourceLimiter` can allow, reject, or trap memory and table allocation or growth requests, and GC object allocations.
diff --git a/crates/parser/Cargo.toml b/crates/parser/Cargo.toml
index 561ac45..042eeda 100644
--- a/crates/parser/Cargo.toml
+++ b/crates/parser/Cargo.toml
@@ -17,7 +17,18 @@ wasmparser = { workspace = true, features = ["simd"] }
[features]
default = ["log", "parallel", "std", "validate"]
+
+# enable integration with the log crate
log = ["dep:log"]
+
+# parse and validate function bodies in parallel (requires std)
parallel = ["std"]
+
+# support targets without native atomic CAS
+portable-atomic = ["tinywasm-types/portable-atomic"]
+
+# enable standard library support
std = ["tinywasm-types/std", "wasmparser/std"]
+
+# validate WebAssembly while parsing
validate = ["wasmparser/features", "wasmparser/validate"]
diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs
index 262cc07..3369f7b 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -292,7 +292,8 @@ impl Parser {
}
let section_end = buffer_offset + section_size;
- let section_bytes = alloc::sync::Arc::<[u8]>::from(buffer[buffer_offset..section_end].to_vec());
+ let section_bytes =
+ tinywasm_types::Shared::<[u8]>::from(buffer[buffer_offset..section_end].to_vec());
reader.queue_owned_code_section(count, parser.offset(), section_bytes, validator.as_mut())?;
parser.skip_section();
buffer_offset = section_end;
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index c076035..bfb28ce 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -3,7 +3,7 @@ use crate::log::debug;
use crate::validation::{FuncToValidate, ValidatorResources};
use crate::validation::{FuncValidatorAllocations, Validator};
use crate::{ParseError, ParserOptions, Result, conversion::*, optimize};
-use alloc::{boxed::Box, format, string::ToString, sync::Arc, vec::Vec};
+use alloc::{boxed::Box, format, string::ToString, vec::Vec};
use core::marker::PhantomData;
use core::ops::Range;
use tinywasm_types::*;
@@ -37,7 +37,7 @@ pub(crate) fn optimize_function_code(
pub(crate) struct ModuleReader<'a> {
func_validator_allocations: Option<FuncValidatorAllocations>,
operators_reader_allocations: Option<OperatorsReaderAllocations>,
- translation_metadata: Option<Arc<crate::visit::ModuleMetadata>>,
+ translation_metadata: Option<crate::visit::ModuleMetadata>,
has_code_section: bool,
has_type_section: bool,
@@ -48,7 +48,7 @@ pub(crate) struct ModuleReader<'a> {
pub(crate) types: TypeSection,
pub(crate) code_type_addrs: Box<[u32]>,
code_results: Box<[ValueCounts]>,
- pub(crate) exports: Arc<[Export]>,
+ pub(crate) exports: Shared<[Export]>,
pub(crate) code: Vec<OptimizedFunctionCode>,
pub(crate) globals: Box<[Global]>,
pub(crate) tables: Box<[TableDefinition]>,
@@ -68,7 +68,7 @@ pub(crate) struct ModuleReader<'a> {
impl<'a> ModuleReader<'a> {
fn translation_metadata(&mut self) -> &crate::visit::ModuleMetadata {
if self.translation_metadata.is_none() {
- self.translation_metadata = Some(Arc::new(crate::visit::ModuleMetadata::new(
+ self.translation_metadata = Some(crate::visit::ModuleMetadata::new(
&self.types,
&self.code_type_addrs,
&self.imports,
@@ -76,9 +76,9 @@ impl<'a> ModuleReader<'a> {
&self.memory_types,
&self.tables,
&self.tags,
- )));
+ ));
}
- self.translation_metadata.as_deref().unwrap()
+ self.translation_metadata.as_ref().unwrap()
}
pub(crate) fn process_payload(&mut self, payload: Payload<'_>, validator: Option<&mut Validator>) -> Result<()> {
@@ -435,7 +435,7 @@ impl<'a> ModuleReader<'a> {
&mut self,
count: u32,
body_offset: u64,
- section_bytes: Arc<[u8]>,
+ section_bytes: Shared<[u8]>,
validator: Option<&mut Validator>,
) -> Result<()> {
#[cfg(feature = "validate")]
@@ -545,7 +545,7 @@ impl<'a> ModuleReader<'a> {
self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing");
let params = ValueCounts::from_iter(ty.params());
- Ok(Arc::new(WasmFunction {
+ Ok(Shared::new(WasmFunction {
instructions: code.instructions.into_boxed_slice(),
data: code.data,
locals: code.locals,
diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs
index 9b96c7a..4ad16cf 100644
--- a/crates/parser/src/parallel.rs
+++ b/crates/parser/src/parallel.rs
@@ -1,10 +1,9 @@
use crate::module::{OptimizedFunctionCode, optimize_function_code};
use crate::validation::{FuncToValidate, FuncValidatorAllocations, ValidatorResources};
use crate::{ParseError, ParserOptions, Result, conversion};
-use alloc::sync::Arc;
use alloc::vec::Vec;
use core::ops::Range;
-use tinywasm_types::ValueCounts;
+use tinywasm_types::{Shared, ValueCounts};
use wasmparser::OperatorsReaderAllocations;
pub(crate) enum FunctionBodyInput<'a> {
@@ -15,7 +14,7 @@ pub(crate) enum FunctionBodyInput<'a> {
pub(crate) struct OwnedFunctionBody {
// A deferred stream code section is copied once, then shared by all queued
// function jobs from that section.
- pub section_bytes: Arc<[u8]>,
+ pub section_bytes: Shared<[u8]>,
pub body_range: Range<usize>,
pub body_offset: u64,
}
diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml
index eb5dd94..954ae40 100644
--- a/crates/tinywasm/Cargo.toml
+++ b/crates/tinywasm/Cargo.toml
@@ -88,6 +88,7 @@ name = "test-wasm-wide-arithmetic"
[dependencies]
libm = { version = "0.2", default-features = false }
log = { workspace = true, optional = true }
+portable-atomic = { version = "1.15.0", default-features = false, optional = true }
tinywasm-parser = { workspace = true, optional = true }
tinywasm-types = { workspace = true }
@@ -111,6 +112,9 @@ default = [
log = ["dep:log", "tinywasm-parser?/log", "tinywasm-types/log"]
std = ["tinywasm-parser?/std", "tinywasm-types/std"]
+# make stores, instances, references, and host callbacks movable across threads
+send = []
+
# support for parsing WebAssembly
parser = ["dep:tinywasm-parser"]
@@ -120,6 +124,9 @@ validate = ["parser", "tinywasm-parser/validate"]
# parallelize function parsing/validation across threads (requires std)
parallel-parser = ["parser", "tinywasm-parser?/parallel"]
+# support targets without native atomic CAS
+portable-atomic = ["dep:portable-atomic", "tinywasm-parser?/portable-atomic", "tinywasm-types/portable-atomic"]
+
# support for "archiving" tinywasm bytecode
archive = ["tinywasm-types/archive"]
diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs
index f1feae6..4fc74d5 100644
--- a/crates/tinywasm/src/engine.rs
+++ b/crates/tinywasm/src/engine.rs
@@ -1,10 +1,12 @@
-use alloc::sync::Arc;
+use alloc::boxed::Box;
use crate::ResourceLimiter;
+use crate::shared::StoreShared;
/// Global configuration for the WebAssembly interpreter
///
-/// Can be cheaply cloned and shared across multiple executions and threads.
+/// Can be cheaply cloned across stores. With the `send` feature, it can also be
+/// moved and shared across threads.
///
/// ## Example
/// ```rust
@@ -117,7 +119,7 @@ pub struct Config {
/// Fuel accounting policy used by budgeted execution. Defaults to [`FuelPolicy::PerInstruction`].
pub fuel_policy: FuelPolicy,
/// Resource limiter shared across all stores created from this engine. Defaults to `None`.
- pub resource_limiter: Option<Arc<dyn ResourceLimiter>>,
+ pub resource_limiter: Option<StoreShared<dyn ResourceLimiter>>,
/// Initial number of GC heap bytes that triggers collection.
/// Defaults to 1 MiB.
pub gc_collection_threshold: usize,
@@ -168,8 +170,11 @@ impl Config {
}
/// Set the resource limiter shared across all stores created from this engine.
- pub fn with_resource_limiter(mut self, limiter: Arc<dyn ResourceLimiter>) -> Self {
- self.resource_limiter = Some(limiter);
+ ///
+ /// The limiter is converted to TinyWasm's internal shared pointer. Pass the
+ /// limiter value directly rather than wrapping it in `Rc` or `Arc`.
+ pub fn with_resource_limiter(mut self, limiter: impl ResourceLimiter + 'static) -> Self {
+ self.resource_limiter = Some(StoreShared::from(Box::new(limiter) as Box<dyn ResourceLimiter>));
self
}
diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs
index 7e289f6..0b9e1f9 100644
--- a/crates/tinywasm/src/func/context.rs
+++ b/crates/tinywasm/src/func/context.rs
@@ -119,7 +119,8 @@ impl FuncContext<'_> {
}
func.func.item.validate_store(self.store)?;
let func_instance = self.store.state.get_func(func.func.addr()).clone();
- if matches!(&func_instance.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) {
+ if matches!(&func_instance.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none())
+ {
let ty = self.store.state.get_canonical_func_type(func_instance.type_addr);
let (param_count, result_count) = (ty.params().len(), ty.results().len());
self.store.with_scratch_values(param_count + result_count, |store, values| {
diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs
index 8f36761..1dcf3c1 100644
--- a/crates/tinywasm/src/func/host.rs
+++ b/crates/tinywasm/src/func/host.rs
@@ -1,18 +1,38 @@
-use alloc::{boxed::Box, sync::Arc, vec::Vec};
+use alloc::{boxed::Box, vec::Vec};
use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType};
use super::{FromWasmValues, FuncContext, IntoWasmValues, ToWasmTypes};
+use crate::shared::StoreShared;
use crate::store::FuncValueTypes;
use crate::{Function, FunctionInstance, Result, Store, WasmValue};
+/// Trait bounds required for a host callback in the current build mode.
+#[doc(hidden)]
+#[cfg(not(feature = "send"))]
+pub trait HostFunctionCallback {}
+#[cfg(not(feature = "send"))]
+impl<T: ?Sized> HostFunctionCallback for T {}
+
+/// Trait bounds required for a host callback in the current build mode.
+#[doc(hidden)]
+#[cfg(feature = "send")]
+pub trait HostFunctionCallback: Send + Sync {}
+#[cfg(feature = "send")]
+impl<T: Send + Sync + ?Sized> HostFunctionCallback for T {}
+
/// A reusable host function definition.
+///
+/// Host functions accept thread-local callback state by default. With the
+/// `send` feature, callbacks must implement `Send + Sync` and host function
+/// definitions can be moved and shared across threads.
#[derive(Clone)]
-pub struct HostFunction(Arc<HostFunctionInner>);
+pub struct HostFunction(StoreShared<HostFunctionInner>);
impl HostFunction {
/// Instantiates the function with an already registered canonical type.
pub(crate) fn instantiate_registered(&self, store: &mut Store, type_addr: TypeAddr) -> Function {
- let addr = store.add_func(FunctionInstance { type_addr, kind: crate::store::FunctionKind::Host(self.clone()) });
+ let addr = store
+ .add_func(FunctionInstance { type_addr, inner: crate::store::FunctionInstanceInner::Host(self.clone()) });
Function { item: crate::StoreItem::new(store.store_id(), addr), module_id: 0 }
}
@@ -155,11 +175,11 @@ impl HostFunction {
/// # Ok(())
/// # }
/// ```
- pub fn from_untyped(
- ty: &FuncType,
- func: impl Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()> + Send + Sync + 'static,
- ) -> Self {
- Self(Arc::new(HostFunctionInner { ty: ty.clone(), callback: HostCallback::Untyped(Box::new(func)) }))
+ pub fn from_untyped<F>(ty: &FuncType, func: F) -> Self
+ where
+ F: Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()> + HostFunctionCallback + 'static,
+ {
+ Self(StoreShared::new(HostFunctionInner { ty: ty.clone(), callback: HostCallback::Untyped(Box::new(func)) }))
}
/// Create a new typed host function.
@@ -190,14 +210,15 @@ impl HostFunction {
/// # Ok(())
/// # }
/// ```
- pub fn from<P, R>(func: impl Fn(FuncContext<'_>, P) -> Result<R> + Send + Sync + 'static) -> Self
+ pub fn from<F, P, R>(func: F) -> Self
where
+ F: Fn(FuncContext<'_>, P) -> Result<R> + HostFunctionCallback + 'static,
P: FromWasmValues + ToWasmTypes + 'static,
R: IntoWasmValues + ToWasmTypes + 'static,
{
let ty = FuncType::new(&P::wasm_types(), &R::wasm_types());
let func = TypedHostCallbackImpl { func, marker: core::marker::PhantomData };
- Self(Arc::new(HostFunctionInner { ty, callback: HostCallback::Typed(Box::new(func)) }))
+ Self(StoreShared::new(HostFunctionInner { ty, callback: HostCallback::Typed(Box::new(func)) }))
}
}
@@ -211,8 +232,17 @@ enum HostCallback {
Typed(Box<dyn TypedHostCallback>),
}
+#[cfg(not(feature = "send"))]
+type UntypedHostCallback = dyn Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()>;
+#[cfg(feature = "send")]
type UntypedHostCallback = dyn Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()> + Send + Sync;
+#[cfg(not(feature = "send"))]
+pub(crate) trait TypedHostCallback {
+ fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()>;
+ fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()>;
+}
+#[cfg(feature = "send")]
pub(crate) trait TypedHostCallback: Send + Sync {
fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()>;
fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()>;
@@ -225,7 +255,7 @@ struct TypedHostCallbackImpl<F, P, R> {
impl<F, P, R> TypedHostCallback for TypedHostCallbackImpl<F, P, R>
where
- F: Fn(FuncContext<'_>, P) -> Result<R> + Send + Sync,
+ F: Fn(FuncContext<'_>, P) -> Result<R> + HostFunctionCallback,
P: FromWasmValues,
R: IntoWasmValues,
{
diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs
index c29b3db..2fbc22f 100644
--- a/crates/tinywasm/src/func/mod.rs
+++ b/crates/tinywasm/src/func/mod.rs
@@ -13,6 +13,8 @@ mod resume;
mod values;
pub use context::FuncContext;
pub use host::HostFunction;
+#[doc(hidden)]
+pub use host::HostFunctionCallback;
pub use resume::{ExecProgress, FuncExecution, FuncExecutionTyped};
pub use values::{FromWasmValues, IntoWasmValues, ToWasmType, ToWasmTypes};
@@ -122,12 +124,12 @@ impl Function {
) -> Result<()> {
let instance = store.state.get_func(self.addr());
let type_addr = instance.type_addr;
- match &instance.kind {
- crate::store::FunctionKind::Host(host) => {
+ match &instance.inner {
+ crate::store::FunctionInstanceInner::Host(host) => {
let host = host.clone();
host.call_values(store, self.module_id, type_addr, params, results)
}
- crate::store::FunctionKind::Wasm(wasm) => {
+ crate::store::FunctionInstanceInner::Wasm(wasm) => {
let wasm_params = wasm.func.params;
let wasm_locals = wasm.func.locals;
store
@@ -156,15 +158,15 @@ impl Function {
stack_base: StackBase,
) -> Result<Option<CallFrame>> {
store.push_typed_values::<false>(instance.type_addr, params, stack_base)?;
- match &instance.kind {
- crate::store::FunctionKind::Wasm(wasm) => {
+ match &instance.inner {
+ crate::store::FunctionInstanceInner::Wasm(wasm) => {
let locals_base = store
.value_stack
.enter_locals(&wasm.func.params, &wasm.func.locals)
.inspect_err(|_| store.value_stack.truncate_to_base(stack_base))?;
Ok(Some(CallFrame::new(self.addr(), locals_base, wasm.func.locals)))
}
- crate::store::FunctionKind::Host(host) => {
+ crate::store::FunctionInstanceInner::Host(host) => {
host.typed_callback()
.expect("typed host function")
.call_stack(store, self.module_id, instance.type_addr)
@@ -209,7 +211,7 @@ impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> {
pub fn call(&self, store: &mut Store, params: P) -> Result<R> {
self.func.item.validate_store(store)?;
let func = store.state.get_func(self.func.addr()).clone();
- if matches!(&func.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) {
+ if matches!(&func.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) {
let ty = store.state.get_canonical_func_type(func.type_addr);
let (param_count, result_count) = (ty.params().len(), ty.results().len());
store.with_scratch_values(param_count + result_count, |store, values| {
diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs
index 6772eb8..cc461a7 100644
--- a/crates/tinywasm/src/func/resume.rs
+++ b/crates/tinywasm/src/func/resume.rs
@@ -62,18 +62,17 @@ impl Function {
store.enter_execution()?;
let result: Result<FuncExecutionState> = (|| {
let func_instance = store.state.get_func(self.addr()).clone();
- match &func_instance.kind {
- crate::store::FunctionKind::Host(host_func) => {
+ match &func_instance.inner {
+ crate::store::FunctionInstanceInner::Host(host_func) => {
host_func.clone().call_values(store, self.module_id, func_instance.type_addr, params, results)?;
Ok(FuncExecutionState::Completed(Some(CallResult::Written)))
}
- crate::store::FunctionKind::Wasm(wasm_func) => {
+ crate::store::FunctionInstanceInner::Wasm(wasm_func) => {
store.call_stack.clear();
store.value_stack.clear();
- let locals = wasm_func.func.locals;
store.push_wasm_values(params.iter().cloned())?;
- let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &locals)?;
- let callframe = CallFrame::new(self.addr(), locals_base, locals);
+ let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)?;
+ let callframe = CallFrame::new(self.addr(), locals_base, wasm_func.func.locals);
Ok(FuncExecutionState::Running { callframe, root_func_addr: self.addr() })
}
@@ -205,7 +204,7 @@ impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> {
pub fn call_resumable<'store>(&self, store: &'store mut Store, params: P) -> Result<FuncExecutionTyped<'store, R>> {
self.func.item.validate_store(store)?;
let func = store.state.get_func(self.func.addr()).clone();
- if matches!(&func.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) {
+ if matches!(&func.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) {
let result = self.call(store, params)?;
let execution = ExecutionCore { store, state: FuncExecutionState::Completed(None) };
return Ok(FuncExecutionTyped { execution, result: Some(result) });
diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs
index 4a92212..bd78a57 100644
--- a/crates/tinywasm/src/instance.rs
+++ b/crates/tinywasm/src/instance.rs
@@ -1,9 +1,10 @@
-use alloc::{boxed::Box, format, rc::Rc, sync::Arc};
+use alloc::{boxed::Box, format};
use core::hint::cold_path;
use tinywasm_types::*;
use crate::func::{FromWasmValues, IntoWasmValues, ToWasmTypes};
use crate::reference::StoreId;
+use crate::shared::StoreShared;
use crate::store::MemoryInstance;
use crate::{
Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Tag, Trap, WasmValue,
@@ -41,12 +42,12 @@ pub enum ExternItem {
/// # }
/// ```
///
-/// Backed by an Rc, so cloning is cheap
+/// Cloning an instance handle is cheap.
///
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#module-instances>
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
-pub struct ModuleInstance(Rc<ModuleInstanceInner>);
+pub struct ModuleInstance(StoreShared<ModuleInstanceInner>);
#[cfg_attr(feature = "debug", derive(Debug))]
struct ModuleInstanceInner {
@@ -61,7 +62,7 @@ struct ModuleInstanceInner {
elem_addrs: Box<[ElemAddr]>,
data_addrs: Box<[DataAddr]>,
func_start: Option<FuncAddr>,
- exports: Arc<[Export]>,
+ exports: Shared<[Export]>,
}
impl ModuleInstance {
@@ -206,7 +207,7 @@ impl ModuleInstance {
exports: module.exports.clone(),
};
- let instance = ModuleInstance(Rc::new(instance));
+ let instance = ModuleInstance(StoreShared::new(instance));
store.add_instance(instance.clone());
if let Some(trap) = elem_trapped.or(data_trapped) {
diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs
index 76c6364..4824b63 100644
--- a/crates/tinywasm/src/interpreter/executor.rs
+++ b/crates/tinywasm/src/interpreter/executor.rs
@@ -8,7 +8,6 @@ use super::no_std_floats::NoStdFloatExt;
use alloc::boxed::Box;
use alloc::vec::Vec;
-use alloc::sync::Arc;
use interpreter::stack::CallFrame;
use tinywasm_types::*;
@@ -24,7 +23,7 @@ const FUEL_COST_CALL_TOTAL: u32 = 5;
pub(crate) struct Executor<'store, const BUDGETED: bool> {
cf: CallFrame,
- func: Arc<WasmFunction>,
+ func: Shared<WasmFunction>,
module: ModuleInstance,
store: &'store mut Store,
call_stack_base: u32,
@@ -1020,7 +1019,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
fn exec_call(
&mut self,
- wasm_func: Arc<WasmFunction>,
+ wasm_func: Shared<WasmFunction>,
owner: ModuleInstanceId,
func_addr: FuncAddr,
return_instr_ptr: usize,
@@ -1030,11 +1029,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
};
self.store.call_stack.push(self.cf, return_instr_ptr)?;
- let locals = wasm_func.locals;
- if !Arc::ptr_eq(&self.func, &wasm_func) {
+ self.cf = CallFrame::new(func_addr, locals_base, wasm_func.locals);
+ if !Shared::ptr_eq(&self.func, &wasm_func) {
self.func = wasm_func;
}
- self.cf = CallFrame::new(func_addr, locals_base, locals);
if owner != self.module.id() {
self.set_module(owner);
}
@@ -1044,7 +1042,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
fn exec_return_call(
&mut self,
- wasm_func: Arc<WasmFunction>,
+ wasm_func: Shared<WasmFunction>,
owner: ModuleInstanceId,
func_addr: FuncAddr,
) -> Result<(), Trap> {
@@ -1052,11 +1050,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else {
return cold!(Err(Trap::CallStackOverflow));
};
- let locals = wasm_func.locals;
- if !Arc::ptr_eq(&self.func, &wasm_func) {
+ self.cf = CallFrame::new(func_addr, locals_base, wasm_func.locals);
+ if !Shared::ptr_eq(&self.func, &wasm_func) {
self.func = wasm_func;
}
- self.cf = CallFrame::new(func_addr, locals_base, locals);
if owner != self.module.id() {
self.set_module(owner);
}
@@ -1108,12 +1105,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
let addr = self.module.resolve_func_addr(v);
let func = self.store.state.get_func(addr);
- match &func.kind {
- crate::store::FunctionKind::Wasm(wasm_func) => {
+ match &func.inner {
+ crate::store::FunctionInstanceInner::Wasm(wasm_func) => {
self.exec_call(wasm_func.func.clone(), wasm_func.owner, addr, return_instr_ptr)?;
Ok(ControlFlow::Continue(0))
}
- crate::store::FunctionKind::Host(host_func) => {
+ crate::store::FunctionInstanceInner::Host(host_func) => {
self.exec_call_host::<false>(host_func.clone(), func.type_addr, return_instr_ptr)
}
}
@@ -1123,12 +1120,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
let addr = self.module.resolve_func_addr(v);
let func = self.store.state.get_func(addr);
- match &func.kind {
- crate::store::FunctionKind::Wasm(wasm_func) => {
+ match &func.inner {
+ crate::store::FunctionInstanceInner::Wasm(wasm_func) => {
self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, addr)?;
Ok(ControlFlow::Continue(0))
}
- crate::store::FunctionKind::Host(host_func) => {
+ crate::store::FunctionInstanceInner::Host(host_func) => {
self.exec_call_host::<true>(host_func.clone(), func.type_addr, 0)
}
}
@@ -1192,12 +1189,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()),
}));
}
- match &func.kind {
- crate::store::FunctionKind::Wasm(wasm_func) => match IS_RETURN_CALL {
+ match &func.inner {
+ crate::store::FunctionInstanceInner::Wasm(wasm_func) => match IS_RETURN_CALL {
true => self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, func_addr),
false => self.exec_call(wasm_func.func.clone(), wasm_func.owner, func_addr, return_instr_ptr),
},
- crate::store::FunctionKind::Host(host_func) => {
+ crate::store::FunctionInstanceInner::Host(host_func) => {
return self.exec_call_host::<IS_RETURN_CALL>(host_func.clone(), func.type_addr, return_instr_ptr);
}
}?;
diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs
index 15ccd0e..d89bfa1 100644
--- a/crates/tinywasm/src/lib.rs
+++ b/crates/tinywasm/src/lib.rs
@@ -90,6 +90,9 @@ mod macros;
mod std;
extern crate alloc;
+#[cfg(all(not(feature = "portable-atomic"), not(target_has_atomic = "32")))]
+compile_error!("tinywasm requires native 32-bit atomics; enable the `portable-atomic` feature");
+
// log for logging (optional).
#[cfg(feature = "log")]
#[expect(clippy::single_component_path_imports)]
@@ -111,7 +114,7 @@ mod error;
pub use error::*;
pub use func::{
ExecProgress, FromWasmValues, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped,
- HostFunction, IntoWasmValues, ToWasmType, ToWasmTypes,
+ HostFunction, HostFunctionCallback, IntoWasmValues, ToWasmType, ToWasmTypes,
};
pub use imports::*;
pub use instance::{ExternItem, ModuleInstance};
@@ -122,6 +125,7 @@ mod func;
mod imports;
mod instance;
mod reference;
+mod shared;
mod store;
mod interpreter;
diff --git a/crates/tinywasm/src/reference/managed.rs b/crates/tinywasm/src/reference/managed.rs
index 1e5f38a..79bd0b9 100644
--- a/crates/tinywasm/src/reference/managed.rs
+++ b/crates/tinywasm/src/reference/managed.rs
@@ -1,7 +1,7 @@
-use alloc::sync::Arc;
-use core::sync::atomic::{AtomicU32, Ordering};
+use tinywasm_types::Shared;
use crate::interpreter::ValueRef;
+use crate::shared::{AtomicU32, Ordering};
use crate::{Result, Store, Trap};
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
@@ -10,7 +10,9 @@ pub(crate) struct StoreId(u32);
impl StoreId {
pub(crate) fn fresh() -> Self {
static NEXT: AtomicU32 = AtomicU32::new(0);
- next_store_id(&NEXT)
+ let id = NEXT.fetch_add(1, Ordering::Relaxed);
+ assert_ne!(id, u32::MAX, "Store identity space exhausted");
+ StoreId(id)
}
pub(crate) const fn get(self) -> u32 {
@@ -18,13 +20,6 @@ impl StoreId {
}
}
-fn next_store_id(counter: &AtomicU32) -> StoreId {
- let id = counter
- .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
- .expect("Store identity space exhausted");
- StoreId(id)
-}
-
#[cfg(feature = "debug")]
impl core::fmt::Debug for StoreId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
@@ -47,7 +42,7 @@ pub(crate) struct RootedItem {
pub(crate) store: StoreId,
pub(crate) value: ValueRef,
pub(crate) kind: ReferentKind,
- pub(crate) _token: Option<Arc<()>>,
+ pub(crate) _token: Option<Shared<()>>,
}
impl PartialEq for RootedItem {
@@ -221,14 +216,6 @@ mod tests {
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/shared.rs b/crates/tinywasm/src/shared.rs
new file mode 100644
index 0000000..97f42b7
--- /dev/null
+++ b/crates/tinywasm/src/shared.rs
@@ -0,0 +1,9 @@
+#[cfg(not(feature = "send"))]
+pub(crate) use alloc::rc::Rc as StoreShared;
+#[cfg(feature = "send")]
+pub(crate) use tinywasm_types::Shared as StoreShared;
+
+#[cfg(not(feature = "portable-atomic"))]
+pub(crate) use core::sync::atomic::{AtomicU32, Ordering};
+#[cfg(feature = "portable-atomic")]
+pub(crate) use portable_atomic::{AtomicU32, Ordering};
diff --git a/crates/tinywasm/src/store/function.rs b/crates/tinywasm/src/store/function.rs
index 3c716a7..88fff5d 100644
--- a/crates/tinywasm/src/store/function.rs
+++ b/crates/tinywasm/src/store/function.rs
@@ -1,4 +1,3 @@
-use alloc::sync::Arc;
use tinywasm_types::*;
use crate::func::HostFunction;
@@ -10,12 +9,12 @@ use crate::func::HostFunction;
#[cfg_attr(feature = "debug", derive(Debug))]
pub(crate) struct FunctionInstance {
pub(crate) type_addr: TypeAddr,
- pub(crate) kind: FunctionKind,
+ pub(crate) inner: FunctionInstanceInner,
}
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
-pub(crate) enum FunctionKind {
+pub(crate) enum FunctionInstanceInner {
/// A host function
Host(HostFunction),
@@ -26,6 +25,6 @@ pub(crate) enum FunctionKind {
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub(crate) struct WasmFunctionInstance {
- pub(crate) func: Arc<WasmFunction>,
+ pub(crate) func: Shared<WasmFunction>,
pub(crate) owner: ModuleInstanceId,
}
diff --git a/crates/tinywasm/src/store/gc/object.rs b/crates/tinywasm/src/store/gc/object.rs
index cf27cd5..b92e07a 100644
--- a/crates/tinywasm/src/store/gc/object.rs
+++ b/crates/tinywasm/src/store/gc/object.rs
@@ -1,11 +1,11 @@
-use alloc::{boxed::Box, sync::Arc, vec::Vec};
+use alloc::{boxed::Box, vec::Vec};
use core::mem::size_of;
-use core::sync::atomic::{AtomicU32, Ordering};
use tinywasm_types::{TagAddr, TypeAddr};
use crate::engine::Config;
use crate::interpreter::{RuntimeValue, ValueRef};
+use crate::shared::{AtomicU32, Ordering, StoreShared};
use crate::{ResourceLimiter, Trap};
use super::{AllocError, Arena, Handle, Trace};
@@ -35,7 +35,7 @@ impl Trace for GcObject {
pub(crate) struct GcHeap {
objects: Arena<GcObject>,
directory: Vec<(u32, Handle)>,
- resource_limiter: Option<Arc<dyn ResourceLimiter>>,
+ resource_limiter: Option<StoreShared<dyn ResourceLimiter>>,
}
impl Default for GcHeap {
@@ -114,11 +114,10 @@ impl GcHeap {
) -> Result<ValueRef, Trap> {
let element_size = size_of::<RuntimeValue>() + if trace_references { size_of::<Option<Handle>>() } else { 0 };
let out_of_line_bytes = values.len().checked_mul(element_size).ok_or(Trap::OutOfMemory)?;
- let key =
- NEXT_GC_REF.try_update(Ordering::Relaxed, Ordering::Relaxed, |key| (key < (1 << 30)).then_some(key + 1));
- let Ok(key) = key else {
+ let key = NEXT_GC_REF.fetch_add(1, Ordering::Relaxed);
+ if key >= 1 << 30 {
return Err(Trap::OutOfMemory);
- };
+ }
let references = if trace_references {
let mut references = Vec::new();
references.try_reserve_exact(values.len()).map_err(|_| Trap::OutOfMemory)?;
diff --git a/crates/tinywasm/src/store/gc/roots.rs b/crates/tinywasm/src/store/gc/roots.rs
index 7107295..ea6c47a 100644
--- a/crates/tinywasm/src/store/gc/roots.rs
+++ b/crates/tinywasm/src/store/gc/roots.rs
@@ -1,4 +1,5 @@
-use alloc::{sync::Arc, sync::Weak, vec::Vec};
+use alloc::vec::Vec;
+use tinywasm_types::{Shared, WeakShared};
use crate::Trap;
use crate::interpreter::ValueRef;
@@ -10,7 +11,7 @@ pub(crate) struct Roots {
struct Root {
value: ValueRef,
- token: Weak<()>,
+ token: WeakShared<()>,
}
impl Roots {
@@ -24,7 +25,7 @@ impl Roots {
self.entries.try_reserve(needed).map_err(|_| Trap::OutOfMemory)
}
- pub(crate) fn insert(&mut self, value: ValueRef) -> Result<Arc<()>, Trap> {
+ pub(crate) fn insert(&mut self, value: ValueRef) -> Result<Shared<()>, Trap> {
if self.free.is_empty() && self.entries.len() == self.entries.capacity() {
self.remove_dead();
}
@@ -37,8 +38,8 @@ impl Roots {
index
};
- let token = Arc::new(());
- self.entries[index as usize] = Some(Root { value, token: Arc::downgrade(&token) });
+ let token = Shared::new(());
+ self.entries[index as usize] = Some(Root { value, token: Shared::downgrade(&token) });
Ok(token)
}
diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs
index 91895b4..57c7575 100644
--- a/crates/tinywasm/src/store/mod.rs
+++ b/crates/tinywasm/src/store/mod.rs
@@ -41,7 +41,6 @@ pub(crate) use {data::*, element::*, function::*, global::*, table::*, tag::*};
///
/// # Example
/// ```rust
-/// use std::sync::Arc;
/// use tinywasm::engine::Config;
/// use tinywasm::types::{MemoryArch, MemoryType};
/// use tinywasm::{Engine, Memory, ResourceLimiter, Store};
@@ -59,7 +58,7 @@ pub(crate) use {data::*, element::*, function::*, global::*, table::*, tag::*};
/// }
/// }
///
-/// let config = Config::new().with_resource_limiter(Arc::new(MemoryLimit(64 * 1024)));
+/// let config = Config::new().with_resource_limiter(MemoryLimit(64 * 1024));
/// let mut store = Store::new(Engine::new(config));
/// let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?;
/// assert_eq!(memory.grow(&mut store, 1)?, None);
@@ -506,7 +505,7 @@ impl Store {
/// Add functions to the store, returning their addresses in the store
pub(crate) fn init_funcs(
&mut self,
- funcs: &[alloc::sync::Arc<WasmFunction>],
+ funcs: &[Shared<WasmFunction>],
owner: ModuleInstanceId,
module_type_idxs: &[TypeAddr],
type_addrs: &[TypeAddr],
@@ -516,9 +515,10 @@ impl Store {
self.state.funcs.reserve_exact(funcs.len());
for (func, &type_idx) in funcs.iter().cloned().zip(module_type_idxs) {
let type_addr = type_addrs[type_idx as usize];
- self.state
- .funcs
- .push(FunctionInstance { type_addr, kind: FunctionKind::Wasm(WasmFunctionInstance { func, owner }) });
+ self.state.funcs.push(FunctionInstance {
+ type_addr,
+ inner: FunctionInstanceInner::Wasm(WasmFunctionInstance { func, owner }),
+ });
}
start..start + funcs.len() as FuncAddr
}
diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs
index 11ea70d..769fc8b 100644
--- a/crates/tinywasm/src/store/state.rs
+++ b/crates/tinywasm/src/store/state.rs
@@ -309,8 +309,8 @@ impl State {
/// Get a wasm function at the actual index in the store, panicking if it's a host function (which should be guaranteed by the validator)
pub(crate) fn get_wasm_func(&self, addr: FuncAddr) -> &WasmFunctionInstance {
- match self.funcs.get(addr as usize).map(|func| &func.kind) {
- Some(FunctionKind::Wasm(wasm_func)) => wasm_func,
+ match self.funcs.get(addr as usize).map(|func| &func.inner) {
+ Some(FunctionInstanceInner::Wasm(wasm_func)) => wasm_func,
_ => unreachable!("invalid wasm function address: {addr}"),
}
}
diff --git a/crates/tinywasm/tests/managed_exceptions.rs b/crates/tinywasm/tests/managed_exceptions.rs
index bb75459..ecb6a12 100644
--- a/crates/tinywasm/tests/managed_exceptions.rs
+++ b/crates/tinywasm/tests/managed_exceptions.rs
@@ -125,8 +125,7 @@ impl ResourceLimiter for GcUsage {
#[test]
fn dropped_exception_roots_release_counted_gc_bytes() {
let usage = Arc::new(Mutex::new(Vec::new()));
- let config =
- Config::new().with_gc_collection_threshold(usize::MAX).with_resource_limiter(Arc::new(GcUsage(usage.clone())));
+ let config = Config::new().with_gc_collection_threshold(usize::MAX).with_resource_limiter(GcUsage(usage.clone()));
let mut store = Store::new(Engine::new(config));
let instance = instantiate(&mut store);
let catch = instance.func_untyped(&store, "catch-scalar").unwrap();
diff --git a/crates/tinywasm/tests/memory.rs b/crates/tinywasm/tests/memory.rs
index 819fe85..608b9e1 100644
--- a/crates/tinywasm/tests/memory.rs
+++ b/crates/tinywasm/tests/memory.rs
@@ -1,14 +1,10 @@
-extern crate alloc;
-
-use alloc::sync::Arc;
-
use tinywasm::engine::Config;
use tinywasm::types::{MemoryArch, MemoryType, RefType, RefValue, TableType};
use tinywasm::{Engine, Memory, ModuleInstance, ResourceLimiter, Store, Table, Trap};
type TestResult<T = ()> = Result<T, Box<dyn core::error::Error>>;
-fn store_with_limiter(limiter: Arc<dyn ResourceLimiter>) -> Store {
+fn store_with_limiter(limiter: impl ResourceLimiter + 'static) -> Store {
let engine = Engine::new(Config::new().with_resource_limiter(limiter));
Store::new(engine)
}
@@ -83,7 +79,7 @@ impl ResourceLimiter for TrapGrowth {
#[test]
fn resource_limiter_can_reject_growth() -> TestResult {
- let mut store = store_with_limiter(Arc::new(DenyGrowth));
+ let mut store = store_with_limiter(DenyGrowth);
let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?;
assert_eq!(memory.grow(&mut store, 1)?, None);
@@ -103,7 +99,7 @@ fn resource_limiter_rejects_guest_memory_grow() -> TestResult {
"#,
)?;
let module = tinywasm::parse_bytes(&wasm)?;
- let mut store = store_with_limiter(Arc::new(DenyGrowth));
+ let mut store = store_with_limiter(DenyGrowth);
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
let grow = instance.func::<(), i32>(&store, "grow")?;
@@ -123,7 +119,7 @@ fn resource_limiter_can_trap_guest_memory_grow() -> TestResult {
"#,
)?;
let module = tinywasm::parse_bytes(&wasm)?;
- let mut store = store_with_limiter(Arc::new(TrapGrowth));
+ let mut store = store_with_limiter(TrapGrowth);
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
let grow = instance.func::<(), i32>(&store, "grow")?;
@@ -133,7 +129,7 @@ fn resource_limiter_can_trap_guest_memory_grow() -> TestResult {
#[test]
fn resource_limiter_rejects_host_memory_initial_size() {
- let mut store = store_with_limiter(Arc::new(DenyAll));
+ let mut store = store_with_limiter(DenyAll);
let result = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None));
assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory))));
@@ -143,7 +139,7 @@ fn resource_limiter_rejects_host_memory_initial_size() {
fn resource_limiter_rejects_module_memory_initial_size() -> TestResult {
let wasm = wat::parse_str("(module (memory 1))")?;
let module = tinywasm::parse_bytes(&wasm)?;
- let mut store = store_with_limiter(Arc::new(DenyAll));
+ let mut store = store_with_limiter(DenyAll);
let result = ModuleInstance::instantiate(&mut store, &module, None);
assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory))));
@@ -152,7 +148,7 @@ fn resource_limiter_rejects_module_memory_initial_size() -> TestResult {
#[test]
fn resource_limiter_rejects_table_initial_size() {
- let mut store = store_with_limiter(Arc::new(DenyAll));
+ let mut store = store_with_limiter(DenyAll);
let result = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into());
assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory))));
@@ -168,7 +164,7 @@ fn table_rejects_initial_size_above_maximum() {
#[test]
fn resource_limiter_can_reject_table_growth() -> TestResult {
- let mut store = store_with_limiter(Arc::new(DenyGrowth));
+ let mut store = store_with_limiter(DenyGrowth);
let table = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?;
assert_eq!(table.grow(&mut store, 1, RefValue::Null.into())?, None);
@@ -178,7 +174,7 @@ fn resource_limiter_can_reject_table_growth() -> TestResult {
#[test]
fn resource_limiter_can_trap_table_growth() -> TestResult {
- let mut store = store_with_limiter(Arc::new(TrapGrowth));
+ let mut store = store_with_limiter(TrapGrowth);
let table = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?;
assert!(matches!(table.grow(&mut store, 1, RefValue::Null.into()), Err(tinywasm::Error::Trap(Trap::Unreachable))));
diff --git a/crates/types/Cargo.toml b/crates/types/Cargo.toml
index 3587143..7f701cf 100644
--- a/crates/types/Cargo.toml
+++ b/crates/types/Cargo.toml
@@ -12,13 +12,24 @@ categories.workspace = true
[dependencies]
log = { workspace = true, optional = true }
+portable-atomic-util = { version = "0.2.7", default-features = false, features = ["alloc"], optional = true }
postcard = { version = "1.1", default-features = false, features = ["alloc"], optional = true }
-serde = { version = "1.0", default-features = false, features = ["alloc", "rc"], optional = true }
+serde = { version = "1.0", default-features = false, features = ["alloc"], optional = true }
[features]
default = ["archive", "debug", "log", "std"]
-archive = ["dep:postcard", "dep:serde"]
+# support serializing and deserializing twasm archives
+archive = ["dep:postcard", "dep:serde", "serde/rc", "portable-atomic-util?/serde"]
+
+# derive Debug for runtime and module types
debug = []
+
+# enable integration with the log crate
log = ["dep:log"]
+
+# enable standard library support
std = ["serde?/std"]
+
+# support targets without native atomic CAS
+portable-atomic = ["dep:portable-atomic-util"]
diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs
index b568155..db13ab0 100644
--- a/crates/types/src/archive.rs
+++ b/crates/types/src/archive.rs
@@ -66,10 +66,10 @@ mod tests {
use super::*;
use crate::{
AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, RefType,
- V128Operand, WasmFunction, WasmType,
+ Shared, V128Operand, WasmFunction, WasmType,
};
use crate::{OperandIdx, OperandType};
- use alloc::{boxed::Box, sync::Arc, vec};
+ use alloc::boxed::Box;
#[test]
fn test_invalid_magic() {
@@ -92,9 +92,9 @@ mod tests {
let bytes = [0x00, 0x01, 0x02, 0x03, 0x7f, 0x80, 0xfe, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x90];
let mut function = WasmFunction::default();
let constant = OperandIdx::new(0);
- function.data.operands128 = vec![V128Operand { value: bytes }.encode()].into_boxed_slice();
- function.instructions = vec![Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)].into();
- let module = Module::from(ModuleInner { funcs: Box::new([Arc::new(function)]), ..ModuleInner::default() });
+ function.data.operands128 = Box::new([V128Operand { value: bytes }.encode()]);
+ function.instructions = Box::new([Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)]);
+ let module = Module::from(ModuleInner { funcs: Box::new([Shared::new(function)]), ..ModuleInner::default() });
let archive = module.serialize_twasm().expect("serialize archive");
assert_eq!(&archive[..6], b"TWAS06");
@@ -114,21 +114,20 @@ mod tests {
fn const_reference_expressions_round_trip_archive() {
let null_type = RefType::new_abstract(true, AbstractHeapType::Extern);
let module = Module::from(ModuleInner {
- globals: vec![
+ globals: Box::new([
Global {
ty: GlobalType::new(WasmType::Ref(null_type), false),
- init: vec![ConstInstruction::RefNull(null_type)].into_boxed_slice(),
+ init: Box::new([ConstInstruction::RefNull(null_type)]),
},
Global {
ty: GlobalType::new(WasmType::Ref(RefType::FUNCREF), false),
- init: vec![ConstInstruction::RefFunc(ModuleFuncIdx::new(7))].into_boxed_slice(),
+ init: Box::new([ConstInstruction::RefFunc(ModuleFuncIdx::new(7))]),
},
Global {
ty: GlobalType::new(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::I31)), false),
- init: vec![ConstInstruction::I32Const(42), ConstInstruction::RefI31].into_boxed_slice(),
+ init: Box::new([ConstInstruction::I32Const(42), ConstInstruction::RefI31]),
},
- ]
- .into_boxed_slice(),
+ ]),
..ModuleInner::default()
});
diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs
index 686433d..9f363d3 100644
--- a/crates/types/src/lib.rs
+++ b/crates/types/src/lib.rs
@@ -9,9 +9,27 @@
//! Types used by [`tinywasm`](https://docs.rs/tinywasm) and [`tinywasm_parser`](https://docs.rs/tinywasm_parser).
extern crate alloc;
-use alloc::{boxed::Box, sync::Arc};
+use alloc::boxed::Box;
use core::ops::{Deref, Range};
+#[cfg(all(not(feature = "portable-atomic"), not(target_has_atomic = "ptr")))]
+compile_error!(
+ "this target does not support atomic operations, enable the `portable-atomic` feature to use `portable-atomic`"
+);
+
+/// An atomically reference-counted pointer.
+#[cfg(not(feature = "portable-atomic"))]
+pub use alloc::sync::Arc as Shared;
+/// A non-owning pointer paired with [`Shared`].
+#[cfg(not(feature = "portable-atomic"))]
+pub use alloc::sync::Weak as WeakShared;
+/// An atomically reference-counted pointer.
+#[cfg(feature = "portable-atomic")]
+pub use portable_atomic_util::Arc as Shared;
+/// A non-owning pointer paired with [`Shared`].
+#[cfg(feature = "portable-atomic")]
+pub use portable_atomic_util::Weak as WeakShared;
+
// Memory defaults
const MEM_PAGE_SIZE: u64 = 65536;
const fn max_page_count(arch: MemoryArch, page_size: u64) -> u64 {
@@ -56,11 +74,11 @@ pub mod archive {
#[derive(Clone, Default, PartialEq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-pub struct Module(Arc<ModuleInner>);
+pub struct Module(Shared<ModuleInner>);
impl From<ModuleInner> for Module {
fn from(inner: ModuleInner) -> Self {
- Self(Arc::new(inner))
+ Self(Shared::new(inner))
}
}
@@ -85,7 +103,7 @@ pub struct ModuleInner {
/// Optimized WebAssembly functions
///
/// Contains data from to the `code`, `func`, and `type` sections of the original WebAssembly module.
- pub funcs: Box<[Arc<WasmFunction>]>,
+ pub funcs: Box<[Shared<WasmFunction>]>,
/// The dense type definitions, indexed by `TypeAddr`.
///
@@ -98,7 +116,7 @@ pub struct ModuleInner {
/// Exported items of the WebAssembly module.
///
/// Corresponds to the `export` section of the original WebAssembly module.
- pub exports: Arc<[Export]>,
+ pub exports: Shared<[Export]>,
/// Global components of the WebAssembly module.
///
diff --git a/crates/types/src/types.rs b/crates/types/src/types.rs
index 12386f1..273c762 100644
--- a/crates/types/src/types.rs
+++ b/crates/types/src/types.rs
@@ -1,6 +1,6 @@
-use alloc::{boxed::Box, sync::Arc};
+use alloc::boxed::Box;
-use crate::{TypeAddr, WasmType};
+use crate::{Shared, TypeAddr, WasmType};
/// The dense type index space of a WebAssembly module.
///
@@ -106,7 +106,7 @@ impl CompositeType {
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
pub struct FuncType {
- data: Arc<[WasmType]>,
+ data: Shared<[WasmType]>,
param_count: u16,
}