summaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorHenry <mail@henrygressmann.de>2026-08-23 14:12:59 +0200
committerHenry <mail@henrygressmann.de>2026-08-23 14:12:59 +0200
commit41b1072bc7fcda3b30cda942c4d801bec30ad6e0 (patch)
tree61e8db6688f12dd78f45532ecf52c062aca446f5 /crates
parent951c8070169e8bd970940029156f305e741aecdb (diff)
feat: add ResourceLimiter::gc_growing
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates')
-rw-r--r--crates/tinywasm/src/store/gc/arena.rs11
-rw-r--r--crates/tinywasm/src/store/gc/object.rs41
-rw-r--r--crates/tinywasm/src/store/mod.rs20
-rw-r--r--crates/tinywasm/src/store/state.rs11
-rw-r--r--crates/tinywasm/tests/gc_refs.rs1
5 files changed, 59 insertions, 25 deletions
diff --git a/crates/tinywasm/src/store/gc/arena.rs b/crates/tinywasm/src/store/gc/arena.rs
index 6238466..56170ce 100644
--- a/crates/tinywasm/src/store/gc/arena.rs
+++ b/crates/tinywasm/src/store/gc/arena.rs
@@ -63,7 +63,7 @@ pub(crate) struct Arena<T> {
free_head: Option<u32>,
worklist: Vec<u32>,
len: usize,
- allocated_bytes: usize,
+ pub(super) allocated_bytes: usize,
collection_threshold: usize,
next_collection: usize,
}
@@ -86,7 +86,7 @@ impl<T> Arena<T> {
///
/// The byte count must remain valid while the value is in the arena.
pub(crate) fn alloc(&mut self, value: T, out_of_line_bytes: usize) -> Result<Handle, AllocError> {
- let bytes = size_of::<Slot<T>>().checked_add(out_of_line_bytes).ok_or(AllocError)?;
+ let bytes = Self::allocation_size(out_of_line_bytes).ok_or(AllocError)?;
let allocated_bytes = self.allocated_bytes.checked_add(bytes).ok_or(AllocError)?;
let handle = if let Some(index) = self.free_head {
@@ -156,11 +156,14 @@ impl<T> Arena<T> {
/// Returns whether an allocation of this size should trigger collection.
pub(crate) fn should_collect(&self, out_of_line_bytes: usize) -> bool {
- size_of::<Slot<T>>()
- .checked_add(out_of_line_bytes)
+ Self::allocation_size(out_of_line_bytes)
.and_then(|bytes| self.allocated_bytes.checked_add(bytes))
.is_none_or(|bytes| bytes >= self.next_collection)
}
+
+ pub(super) fn allocation_size(out_of_line_bytes: usize) -> Option<usize> {
+ size_of::<Slot<T>>().checked_add(out_of_line_bytes)
+ }
}
impl<T: Trace> Arena<T> {
diff --git a/crates/tinywasm/src/store/gc/object.rs b/crates/tinywasm/src/store/gc/object.rs
index 4af64c9..ca22338 100644
--- a/crates/tinywasm/src/store/gc/object.rs
+++ b/crates/tinywasm/src/store/gc/object.rs
@@ -1,11 +1,13 @@
-use alloc::{boxed::Box, vec::Vec};
+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 crate::engine::Config;
use crate::interpreter::{TinyWasmValue, ValueRef};
+use crate::{ResourceLimiter, Trap};
use super::{AllocError, Arena, Handle, Trace};
@@ -29,18 +31,24 @@ pub(crate) struct GcHeap {
objects: Arena<GcObject>,
directory: Vec<(u32, Handle)>,
pinned: RefCell<Vec<Handle>>,
+ resource_limiter: Option<Arc<dyn ResourceLimiter>>,
}
impl Default for GcHeap {
fn default() -> Self {
- Self::new(1024 * 1024)
+ Self::new(&Config::default())
}
}
impl GcHeap {
/// Creates a heap with the configured allocation threshold.
- pub(crate) const fn new(collection_threshold: usize) -> Self {
- Self { objects: Arena::new(collection_threshold), directory: Vec::new(), pinned: RefCell::new(Vec::new()) }
+ pub(crate) fn new(config: &Config) -> Self {
+ Self {
+ objects: Arena::new(config.gc_collection_threshold),
+ directory: Vec::new(),
+ pinned: RefCell::new(Vec::new()),
+ resource_limiter: config.resource_limiter.clone(),
+ }
}
#[inline]
@@ -67,15 +75,25 @@ impl GcHeap {
type_addr: TypeAddr,
values: Vec<TinyWasmValue>,
trace_references: bool,
- ) -> Result<ValueRef, AllocError> {
+ ) -> Result<ValueRef, Trap> {
+ let element_size = size_of::<TinyWasmValue>() + 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 allocation_size = Arena::<GcObject>::allocation_size(out_of_line_bytes).ok_or(Trap::OutOfMemory)?;
+ let desired = self.objects.allocated_bytes.checked_add(allocation_size).ok_or(Trap::OutOfMemory)?;
+ if let Some(limiter) = &self.resource_limiter
+ && !limiter.gc_growing(self.objects.allocated_bytes, desired, None)?
+ {
+ return Err(Trap::OutOfMemory);
+ }
+
let key =
NEXT_GC_REF.try_update(Ordering::Relaxed, Ordering::Relaxed, |key| (key < (1 << 30)).then_some(key + 1));
let Ok(key) = key else {
- return Err(AllocError);
+ return Err(Trap::OutOfMemory);
};
let references = if trace_references {
let mut references = Vec::new();
- references.try_reserve_exact(values.len()).map_err(|_| AllocError)?;
+ references.try_reserve_exact(values.len()).map_err(|_| Trap::OutOfMemory)?;
references.extend(values.iter().map(|value| match value {
TinyWasmValue::ValueRef(value) => self.handle(*value),
_ => None,
@@ -84,11 +102,9 @@ impl GcHeap {
} else {
None
};
- let element_size = size_of::<TinyWasmValue>() + if trace_references { size_of::<Option<Handle>>() } else { 0 };
- let out_of_line_bytes = values.len().checked_mul(element_size).ok_or(AllocError)?;
let object = GcObject { type_addr, values: values.into_boxed_slice(), references };
- self.directory.try_reserve(1).map_err(|_| AllocError)?;
- let handle = self.objects.alloc(object, out_of_line_bytes)?;
+ 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))
}
@@ -149,8 +165,7 @@ impl GcHeap {
pub(crate) fn should_collect(&self, value_count: usize, trace_references: bool) -> bool {
let element_size = size_of::<TinyWasmValue>() + if trace_references { size_of::<Option<Handle>>() } else { 0 };
- let bytes = value_count.saturating_mul(element_size);
- self.objects.should_collect(bytes)
+ self.objects.should_collect(value_count.saturating_mul(element_size))
}
/// Reclaims objects unreachable from runtime and permanent host roots.
diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs
index f0e426f..2ddd43c 100644
--- a/crates/tinywasm/src/store/mod.rs
+++ b/crates/tinywasm/src/store/mod.rs
@@ -35,8 +35,8 @@ static STORE_ID: AtomicU32 = AtomicU32::new(0);
///
/// Configure a limiter with
/// [`Config::with_resource_limiter`](crate::engine::Config::with_resource_limiter). It currently
-/// controls guest linear-memory and table allocation and growth. It does not account for stacks,
-/// GC storage, runtime metadata, or other host allocations.
+/// controls guest linear-memory, table, and GC heap growth. It does not account for stacks, runtime
+/// metadata, temporary buffers, backing-capacity overhead, or other host allocations.
///
/// # Example
/// ```rust
@@ -94,6 +94,20 @@ pub trait ResourceLimiter: Send + Sync {
) -> core::result::Result<bool, Trap> {
Ok(true)
}
+
+ /// Returns whether a GC object allocation is allowed.
+ ///
+ /// 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.
+ fn gc_growing(
+ &self,
+ _current: usize,
+ _desired: usize,
+ _maximum: Option<usize>,
+ ) -> core::result::Result<bool, Trap> {
+ Ok(true)
+ }
}
/// Runtime state used by WebAssembly instances and host functions.
@@ -150,7 +164,7 @@ impl 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 state = State::new(engine.config().gc_collection_threshold);
+ let state = State::new(engine.config());
Self {
id,
module_instances: Vec::new(),
diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs
index 601bb6a..f93a59a 100644
--- a/crates/tinywasm/src/store/state.rs
+++ b/crates/tinywasm/src/store/state.rs
@@ -1,6 +1,7 @@
use alloc::vec::Vec;
use super::*;
+use crate::engine::Config;
/// Global state that can be manipulated by WebAssembly programs
///
@@ -18,11 +19,11 @@ pub(crate) struct State {
pub(crate) exceptions: Vec<ExceptionInstance>,
pub(crate) elements: Vec<ElementInstance>,
pub(crate) data: Vec<DataInstance>,
- pub(crate) gc: Box<gc::GcHeap>,
+ pub(crate) gc: gc::GcHeap,
}
impl State {
- pub(crate) fn new(gc_collection_threshold: usize) -> Self {
+ pub(crate) fn new(config: &Config) -> Self {
Self {
canonical_types: Vec::new(),
canonical_rec_group_lengths: Vec::new(),
@@ -34,7 +35,7 @@ impl State {
exceptions: Vec::new(),
elements: Vec::new(),
data: Vec::new(),
- gc: Box::new(gc::GcHeap::new(gc_collection_threshold)),
+ gc: gc::GcHeap::new(config),
}
}
@@ -120,7 +121,7 @@ impl State {
}));
cold_err!(self.gc.collect(roots)).map_err(|_| Trap::OutOfMemory)?;
}
- cold_err!(self.gc.alloc(type_addr, values, trace_references)).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.
@@ -441,6 +442,6 @@ impl State {
impl Default for State {
fn default() -> Self {
- Self::new(1024 * 1024)
+ Self::new(&Config::default())
}
}
diff --git a/crates/tinywasm/tests/gc_refs.rs b/crates/tinywasm/tests/gc_refs.rs
index d3f2994..ce92300 100644
--- a/crates/tinywasm/tests/gc_refs.rs
+++ b/crates/tinywasm/tests/gc_refs.rs
@@ -1,3 +1,4 @@
+
use tinywasm::types::{ExternRef, RefValue, WasmValue};
use tinywasm::{Engine, ExecProgress, ModuleInstance, Store, engine::Config};