Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Enforce limits on component model handles within a store (#14732)

Alex Crichton28c6adad203e
diff --git a/crates/cli-flags/src/lib.rs b/crates/cli-flags/src/lib.rs
index c551fc30b7..3e819466e2 100644
--- a/crates/cli-flags/src/lib.rs
+++ b/crates/cli-flags/src/lib.rs
@@ -629,6 +629,10 @@ wasmtime_option_group! {
pub max_resources: Option<usize>,
/// Fuel to use for all hostcalls to limit guest<->host data transfer.
pub hostcall_fuel: Option<usize>,
+ /// Maximum number of simultaneously-live component-model handles (e.g.
+ /// resources, streams, futures) per store; allocating past it traps.
+ /// (default: 100000)
+ pub max_component_handles: Option<usize>,
/// Maximum value, in bytes, for a wasi-random 0.2
/// `get{,-insecure}-random-bytes` `len` parameter. Calls with a value
/// exceeding this limit will trap.
diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rs
index f490788d1b..72fb80538a 100644
--- a/crates/wasmtime/src/runtime/component/concurrent.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent.rs
@@ -63,7 +63,9 @@ use crate::prelude::*;
use crate::store::{Store, StoreId, StoreInner, StoreOpaque, StoreToken};
#[cfg(feature = "gc")]
use crate::vm::GcRootsList;
-use crate::vm::component::{CallContext, ComponentInstance, CurrentScope, InstanceState, Scope};
+use crate::vm::component::{
+ CallContext, ComponentInstance, CurrentScope, HandleCounter, InstanceState, Scope,
+};
use crate::vm::{
AlwaysMut, SendSyncPtr, UncaughtException, VMFuncRef, VMLazyThread, VMMemoryDefinition, VMStore,
};
@@ -2179,6 +2181,18 @@ impl StoreOpaque {
.instance_state(instance.index)
}
+ /// Same as `instance_state`, but also returns the store's `HandleCounter`
+ /// for inserting into or removing from the instance's handle tables.
+ fn instance_state_and_handle_counter(
+ &mut self,
+ instance: RuntimeInstance,
+ ) -> (&mut InstanceState, &mut HandleCounter) {
+ let (component, counter) = self
+ .store_data_mut()
+ .component_instance_and_handle_counter_mut(instance.instance);
+ (component.instance_state(instance.index), counter)
+ }
+
/// Configure the currently running `thread`.
///
/// This will save off any state necessary for the previous thread, if
@@ -2568,9 +2582,10 @@ impl StoreOpaque {
let thread_data = state.get_mut(guest_thread.thread)?;
let sync_call_set = thread_data.sync_call_set;
if let Some(guest_id) = thread_data.instance_rep {
- self.instance_state(runtime_instance)
+ let (state, counter) = self.instance_state_and_handle_counter(runtime_instance);
+ state
.thread_handle_table()
- .guest_thread_remove(guest_id)?;
+ .guest_thread_remove(counter, guest_id)?;
}
let state = self.concurrent_state_mut()?;
@@ -3603,11 +3618,10 @@ impl Instance {
// It hasn't returned yet, but the caller is calling via an
// async-lowered import, so we generate a handle for the task
// waitable and return the status.
- let handle = store
- .0
- .instance_state(caller_instance)
+ let (state, counter) = store.0.instance_state_and_handle_counter(caller_instance);
+ let handle = state
.handle_table()
- .subtask_insert_guest(guest_thread.task.rep())?;
+ .subtask_insert_guest(counter, guest_thread.task.rep())?;
store
.0
.concurrent_state_mut()?
@@ -3801,11 +3815,10 @@ impl Instance {
let state = store.0.concurrent_state_mut()?;
state.push_future(future);
let instance = state.get_mut(caller.task)?.instance;
- let handle = store
- .0
- .instance_state(instance)
+ let (state, counter) = store.0.instance_state_and_handle_counter(instance);
+ let handle = state
.handle_table()
- .subtask_insert_host(task.rep())?;
+ .subtask_insert_host(counter, task.rep())?;
store.0.concurrent_state_mut()?.get_mut(task)?.common.handle = Some(handle);
log::trace!("assign {task:?} handle {handle} for {caller:?} instance {instance:?}");
@@ -3945,10 +3958,11 @@ impl Instance {
caller_instance: RuntimeComponentInstanceIndex,
) -> Result<u32> {
let set = store.concurrent_state_mut()?.push(WaitableSet::default())?;
- let handle = store
- .instance_state(self.runtime_instance(caller_instance))
+ let (state, counter) =
+ store.instance_state_and_handle_counter(self.runtime_instance(caller_instance));
+ let handle = state
.handle_table()
- .waitable_set_insert(set.rep())?;
+ .waitable_set_insert(counter, set.rep())?;
log::trace!("new waitable set {set:?} (handle {handle})");
Ok(handle)
}
@@ -3960,10 +3974,9 @@ impl Instance {
caller_instance: RuntimeComponentInstanceIndex,
set: u32,
) -> Result<()> {
- let rep = store
- .instance_state(self.runtime_instance(caller_instance))
- .handle_table()
- .waitable_set_remove(set)?;
+ let (state, counter) =
+ store.instance_state_and_handle_counter(self.runtime_instance(caller_instance));
+ let rep = state.handle_table().waitable_set_remove(counter, set)?;
log::trace!("drop waitable set {rep} (handle {set})");
@@ -4024,10 +4037,9 @@ impl Instance {
) -> Result<()> {
self.waitable_join(store, caller_instance, task_id, 0)?;
- let (rep, is_host) = store
- .instance_state(self.runtime_instance(caller_instance))
- .handle_table()
- .subtask_remove(task_id)?;
+ let (state, counter) =
+ store.instance_state_and_handle_counter(self.runtime_instance(caller_instance));
+ let (rep, is_host) = state.handle_table().subtask_remove(counter, task_id)?;
let concurrent_state = store.concurrent_state_mut()?;
let waitable = if is_host {
@@ -4321,10 +4333,11 @@ impl Instance {
store: &mut StoreOpaque,
runtime_instance: RuntimeComponentInstanceIndex,
) -> Result<u32> {
- let guest_id = store
- .instance_state(self.runtime_instance(runtime_instance))
+ let (state, counter) =
+ store.instance_state_and_handle_counter(self.runtime_instance(runtime_instance));
+ let guest_id = state
.thread_handle_table()
- .guest_thread_insert(thread_id.rep())?;
+ .guest_thread_insert(counter, thread_id.rep())?;
store
.concurrent_state_mut()?
.get_mut(thread_id)?
@@ -6966,10 +6979,12 @@ mod tests {
state,
group,
})?;
- let handle = store_opaque
- .instance_state(instance.runtime_instance(RuntimeComponentInstanceIndex::from_u32(0)))
+ let (state, counter) = store_opaque.instance_state_and_handle_counter(
+ instance.runtime_instance(RuntimeComponentInstanceIndex::from_u32(0)),
+ );
+ let handle = state
.handle_table()
- .subtask_insert_host(task.rep())?;
+ .subtask_insert_host(counter, task.rep())?;
let common = &mut store_opaque.concurrent_state_mut()?.get_mut(task)?.common;
common.handle = Some(handle);
common.event = event;
diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
index 02665b8a09..8c56cdf230 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
@@ -13,7 +13,7 @@ use crate::component::{
use crate::prelude::*;
use crate::store::{StoreOpaque, StoreToken};
use crate::try_mutex::{TryMutex, TryMutexGuard};
-use crate::vm::component::{ComponentInstance, HandleTable, TransmitLocalState};
+use crate::vm::component::{ComponentInstance, HandleCounter, HandleTable, TransmitLocalState};
use crate::vm::{AlwaysMut, VMStore};
use crate::{AsContext, AsContextMut, StoreContextMut, ValRaw};
use crate::{
@@ -1482,8 +1482,8 @@ pub(super) fn lift_index_to_future(
match ty {
InterfaceType::Future(src) => {
let id = {
- let (state, instance) = cx.concurrent_state_and_instance_mut();
- lift_index_to_transmit(instance, state, TransmitIndex::Future(src), index)?
+ let (state, instance, counter) = cx.concurrent_state_and_instance_mut();
+ lift_index_to_transmit(instance, counter, state, TransmitIndex::Future(src), index)?
};
cx.host_resource_lower_own(id.rep(), None, None)
}
@@ -1838,8 +1838,8 @@ pub(super) fn lift_index_to_stream(
match ty {
InterfaceType::Stream(src) => {
let id = {
- let (state, instance) = cx.concurrent_state_and_instance_mut();
- lift_index_to_transmit(instance, state, TransmitIndex::Stream(src), index)?
+ let (state, instance, counter) = cx.concurrent_state_and_instance_mut();
+ lift_index_to_transmit(instance, counter, state, TransmitIndex::Stream(src), index)?
};
cx.host_resource_lower_own(id.rep(), None, None)
}
@@ -2043,8 +2043,13 @@ pub(crate) fn lower_error_context_to_index<U>(
) -> Result<u32> {
match ty {
InterfaceType::ErrorContext(dst) => {
- let tbl = cx.instance_mut().table_for_error_context(dst);
- tbl.error_context_insert(rep)
+ let (instance, counter) = cx
+ .instance_handle()
+ .id()
+ .get_mut_and_handle_counter(cx.store.0);
+ instance
+ .table_for_error_context(dst)
+ .error_context_insert(counter, rep)
}
_ => func::bad_type_info(),
}
@@ -3283,10 +3288,13 @@ impl Instance {
ty: TransmitIndex,
writer: u32,
) -> Result<()> {
- let table = self.id().get_mut(store).table_for_transmit(ty);
+ let (instance, counter) = self.id().get_mut_and_handle_counter(store);
+ let table = instance.table_for_transmit(ty);
let (transmit_rep, is_done) = match ty {
- TransmitIndex::Future(ty) => table.future_remove_writable(ty, writer)?,
- TransmitIndex::Stream(ty) => (table.stream_remove_writable(ty, writer)?, false),
+ TransmitIndex::Future(ty) => table.future_remove_writable(counter, ty, writer)?,
+ TransmitIndex::Stream(ty) => {
+ (table.stream_remove_writable(counter, ty, writer)?, false)
+ }
};
let id = TableId::<TransmitHandle>::new(transmit_rep);
@@ -4332,10 +4340,11 @@ impl Instance {
ty: TransmitIndex,
reader: u32,
) -> Result<()> {
- let table = self.id().get_mut(store).table_for_transmit(ty);
+ let (instance, counter) = self.id().get_mut_and_handle_counter(store);
+ let table = instance.table_for_transmit(ty);
let (rep, _is_done) = match ty {
- TransmitIndex::Stream(ty) => table.stream_remove_readable(ty, reader)?,
- TransmitIndex::Future(ty) => table.future_remove_readable(ty, reader)?,
+ TransmitIndex::Stream(ty) => table.stream_remove_readable(counter, ty, reader)?,
+ TransmitIndex::Future(ty) => table.future_remove_readable(counter, ty, reader)?,
};
let kind = match ty {
TransmitIndex::Stream(_) => TransmitKind::Stream,
@@ -4380,11 +4389,10 @@ impl Instance {
// Here we reflect the newly created global concurrent error context state into the
// component instance's locally tracked count, along with the appropriate key into the global
// ref tracking data structures to enable later lookup
- let local_idx = self
- .id()
- .get_mut(store)
+ let (instance, counter) = self.id().get_mut_and_handle_counter(store);
+ let local_idx = instance
.table_for_error_context(ty)
- .error_context_insert(table_id.rep())?;
+ .error_context_insert(counter, table_id.rep())?;
Ok(local_idx)
}
@@ -4514,15 +4522,16 @@ impl Instance {
.concurrent_state_mut()?
.new_transmit(TransmitOrigin::guest(self.id().instance(), ty))?;
- let table = self.id().get_mut(store).table_for_transmit(ty);
+ let (instance, counter) = self.id().get_mut_and_handle_counter(store);
+ let table = instance.table_for_transmit(ty);
let (read_handle, write_handle) = match ty {
TransmitIndex::Future(ty) => (
- table.future_insert_read(ty, read.rep())?,
- table.future_insert_write(ty, write.rep())?,
+ table.future_insert_read(counter, ty, read.rep())?,
+ table.future_insert_write(counter, ty, write.rep())?,
),
TransmitIndex::Stream(ty) => (
- table.stream_insert_read(ty, read.rep())?,
- table.stream_insert_write(ty, write.rep())?,
+ table.stream_insert_read(counter, ty, read.rep())?,
+ table.stream_insert_write(counter, ty, write.rep())?,
),
};
@@ -4543,11 +4552,11 @@ impl Instance {
ty: TypeComponentLocalErrorContextTableIndex,
error_context: u32,
) -> Result<()> {
- let instance = self.id().get_mut(store);
+ let (instance, counter) = self.id().get_mut_and_handle_counter(store);
let local_handle_table = instance.table_for_error_context(ty);
- let rep = local_handle_table.error_context_drop(error_context)?;
+ let rep = local_handle_table.error_context_drop(counter, error_context)?;
let global_ref_count_idx = TypeComponentGlobalErrorContextTableIndex::from_u32(rep);
@@ -4596,8 +4605,8 @@ impl Instance {
ty: TransmitIndex,
src_idx: u32,
) -> Result<TableId<TransmitHandle>> {
- let (state, _, _, instance) = store.lift_context_parts(self);
- lift_index_to_transmit(instance, state.concurrent_state_mut(), ty, src_idx)
+ let (state, _, counter, _, instance) = store.lift_context_parts(self);
+ lift_index_to_transmit(instance, counter, state.concurrent_state_mut(), ty, src_idx)
}
fn lower_transmit_to_index(
@@ -4606,8 +4615,8 @@ impl Instance {
ty: TransmitIndex,
id: TableId<TransmitHandle>,
) -> Result<u32> {
- let (state, _, _, instance) = store.lift_context_parts(self);
- lower_transmit_to_index(instance, state.concurrent_state_mut(), ty, id)
+ let (state, _, counter, _, instance) = store.lift_context_parts(self);
+ lower_transmit_to_index(instance, counter, state.concurrent_state_mut(), ty, id)
}
/// Implements the `future.new` intrinsic.
@@ -4670,14 +4679,14 @@ impl Instance {
src: TypeComponentLocalErrorContextTableIndex,
dst: TypeComponentLocalErrorContextTableIndex,
) -> Result<u32> {
- let mut instance = self.id().get_mut(store);
+ let (mut instance, counter) = self.id().get_mut_and_handle_counter(store);
let rep = instance
.as_mut()
.table_for_error_context(src)
.error_context_rep(src_idx)?;
let dst_idx = instance
.table_for_error_context(dst)
- .error_context_insert(rep)?;
+ .error_context_insert(counter, rep)?;
// Update the global (cross-subcomponent) count for error contexts
// as the new component has essentially created a new reference that will
@@ -4704,14 +4713,15 @@ impl Instance {
/// expected type of future/stream.
fn lift_index_to_transmit(
instance: Pin<&mut ComponentInstance>,
+ counter: &mut HandleCounter,
concurrent_state: &mut ConcurrentState,
ty: TransmitIndex,
src_idx: u32,
) -> Result<TableId<TransmitHandle>> {
let handle_table = instance.table_for_transmit(ty);
let (rep, is_done) = match ty {
- TransmitIndex::Future(idx) => handle_table.future_remove_readable(idx, src_idx)?,
- TransmitIndex::Stream(idx) => handle_table.stream_remove_readable(idx, src_idx)?,
+ TransmitIndex::Future(idx) => handle_table.future_remove_readable(counter, idx, src_idx)?,
+ TransmitIndex::Stream(idx) => handle_table.stream_remove_readable(counter, idx, src_idx)?,
};
let desc = match ty {
TransmitIndex::Future(_) => "future",
@@ -4742,6 +4752,7 @@ fn lift_index_to_transmit(
/// an instance.
fn lower_transmit_to_index(
instance: Pin<&mut ComponentInstance>,
+ counter: &mut HandleCounter,
concurrent_state: &mut ConcurrentState,
ty: TransmitIndex,
id: TableId<TransmitHandle>,
@@ -4750,8 +4761,8 @@ fn lower_transmit_to_index(
debug_assert_eq!(concurrent_state.get_mut(state)?.read_handle, id);
let handle_table = instance.table_for_transmit(ty);
let handle = match ty {
- TransmitIndex::Future(idx) => handle_table.future_insert_read(idx, id.rep()),
- TransmitIndex::Stream(idx) => handle_table.stream_insert_read(idx, id.rep()),
+ TransmitIndex::Future(idx) => handle_table.future_insert_read(counter, idx, id.rep()),
+ TransmitIndex::Stream(idx) => handle_table.stream_insert_read(counter, idx, id.rep()),
}?;
concurrent_state.get_mut(id)?.common.handle = Some(handle);
Ok(handle)
diff --git a/crates/wasmtime/src/runtime/component/func/options.rs b/crates/wasmtime/src/runtime/component/func/options.rs
index ea64642b3a..de59c9f47c 100644
--- a/crates/wasmtime/src/runtime/component/func/options.rs
+++ b/crates/wasmtime/src/runtime/component/func/options.rs
@@ -6,7 +6,9 @@ use crate::component::resources::{HostResourceData, HostResourceIndex, HostResou
use crate::component::store::ComponentTaskState;
use crate::component::{Instance, ResourceType, RuntimeInstance};
use crate::prelude::*;
-use crate::runtime::vm::component::{ComponentInstance, CurrentScope, HandleTable, ResourceTables};
+use crate::runtime::vm::component::{
+ ComponentInstance, CurrentScope, HandleCounter, HandleTable, ResourceTables,
+};
use crate::runtime::vm::{UncaughtException, VMFuncRef};
use crate::store::{StoreId, StoreOpaque};
use alloc::sync::Arc;
@@ -344,6 +346,7 @@ pub struct LiftContext<'a> {
instance_handle: Instance,
host_table: &'a mut HandleTable,
+ handle_counter: &'a mut HandleCounter,
host_resource_data: &'a mut HostResourceData,
task_state: &'a mut ComponentTaskState,
@@ -375,7 +378,7 @@ impl<'a> LiftContext<'a> {
// at this time.
let memory =
instance_handle.options_memory(unsafe { &*(store as *const StoreOpaque) }, options);
- let (task_state, host_table, host_resource_data, instance) =
+ let (task_state, host_table, handle_counter, host_resource_data, instance) =
store.lift_context_parts(instance_handle);
let (component, instance) = instance.component_and_self();
@@ -389,6 +392,7 @@ impl<'a> LiftContext<'a> {
instance_handle,
task_state,
host_table,
+ handle_counter,
host_resource_data,
hostcall_fuel,
})
@@ -433,10 +437,15 @@ impl<'a> LiftContext<'a> {
#[cfg(feature = "component-model-async")]
pub(crate) fn concurrent_state_and_instance_mut(
&mut self,
- ) -> (&mut ConcurrentState, Pin<&mut ComponentInstance>) {
+ ) -> (
+ &mut ConcurrentState,
+ Pin<&mut ComponentInstance>,
+ &mut HandleCounter,
+ ) {
(
self.task_state.concurrent_state_mut(),
self.instance.as_mut(),
+ self.handle_counter,
)
}
@@ -497,6 +506,7 @@ impl<'a> LiftContext<'a> {
HostResourceTables::from_parts(
ResourceTables {
host_table: self.host_table,
+ handle_counter: self.handle_counter,
task_state: self.task_state,
guest: Some(self.instance.as_mut().instance_states()),
current_scope: self.current_scope,
diff --git a/crates/wasmtime/src/runtime/component/store.rs b/crates/wasmtime/src/runtime/component/store.rs
index 7081aed92d..ff390ee22b 100644
--- a/crates/wasmtime/src/runtime/component/store.rs
+++ b/crates/wasmtime/src/runtime/component/store.rs
@@ -2,7 +2,7 @@ use crate::prelude::*;
use crate::runtime::component::{HostResourceData, Instance};
use crate::runtime::vm;
use crate::runtime::vm::component::{
- CallContext, ComponentInstance, HandleTable, OwnedComponentInstance, Scope,
+ CallContext, ComponentInstance, HandleCounter, HandleTable, OwnedComponentInstance, Scope,
};
use crate::store::{StoreData, StoreId, StoreOpaque};
use crate::{AsContext, AsContextMut, Engine, Store, StoreContextMut, bail_bug};
@@ -26,6 +26,12 @@ use crate::{
/// host doesn't mean that it's automatically susceptible to DoS for example.
const DEFAULT_HOSTCALL_FUEL: usize = 128 << 20;
+/// Default per-store cap on simultaneously-live component-model handles.
+///
+/// A guest creates these directly (e.g. `resource.new`), so leaving them
+/// unbounded is a DoS vector.
+const DEFAULT_MAX_COMPONENT_HANDLES: usize = 100_000;
+
/// Extensions to `Store` which are only relevant for component-related
/// information.
pub struct ComponentStoreData {
@@ -40,6 +46,11 @@ pub struct ComponentStoreData {
/// resources in the instance allocator.
num_component_instances: usize,
+ /// Live-handle counter for every `HandleTable` in this store (the
+ /// `component_host_table` below and each instance's tables). See
+ /// `HandleCounter`.
+ handle_counter: HandleCounter,
+
/// Runtime state for components used in the handling of resources, borrow,
/// and calls. These also interact with the `ResourceAny` type and its
/// internal representation.
@@ -87,6 +98,7 @@ impl ComponentStoreData {
trapped: false,
num_component_instances: 0,
component_host_table: Default::default(),
+ handle_counter: HandleCounter::new(DEFAULT_MAX_COMPONENT_HANDLES),
host_resource_data: Default::default(),
task_state: if engine.tunables().concurrency_support {
#[cfg(feature = "component-model-async")]
@@ -233,6 +245,21 @@ impl StoreComponentInstanceId {
self.from_data_get_mut(store.store_data_mut())
}
+ /// Same as `get_mut`, but also returns the store's `HandleCounter`.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `self` does not belong to `store`.
+ #[cfg(feature = "component-model-async")]
+ pub(crate) fn get_mut_and_handle_counter<'a>(
+ &self,
+ store: &'a mut StoreOpaque,
+ ) -> (Pin<&'a mut ComponentInstance>, &'a mut HandleCounter) {
+ let store = store.store_data_mut();
+ self.assert_belongs_to(store.id());
+ store.component_instance_and_handle_counter_mut(self.instance)
+ }
+
/// Return a mutable `ComponentInstance` and a `ModuleRegistry`
/// from the store.
///
@@ -280,6 +307,18 @@ impl StoreData {
) -> Pin<&mut ComponentInstance> {
self.components.instances[id].as_mut().unwrap().get_mut()
}
+
+ #[cfg(feature = "component-model-async")]
+ pub(crate) fn component_instance_and_handle_counter_mut(
+ &mut self,
+ id: ComponentInstanceId,
+ ) -> (Pin<&mut ComponentInstance>, &mut HandleCounter) {
+ let data = &mut self.components;
+ (
+ data.instances[id].as_mut().unwrap().get_mut(),
+ &mut data.handle_counter,
+ )
+ }
}
impl StoreOpaque {
@@ -370,6 +409,7 @@ impl StoreOpaque {
) -> (
&mut ComponentTaskState,
&mut HandleTable,
+ &mut HandleCounter,
&mut HostResourceData,
Pin<&mut ComponentInstance>,
) {
@@ -379,6 +419,7 @@ impl StoreOpaque {
(
&mut data.task_state,
&mut data.component_host_table,
+ &mut data.handle_counter,
&mut data.host_resource_data,
data.instances[instance.instance]
.as_mut()
@@ -420,6 +461,7 @@ impl StoreOpaque {
Ok((
vm::component::ResourceTables {
host_table: &mut data.component_host_table,
+ handle_counter: &mut data.handle_counter,
task_state: &mut data.task_state,
guest,
current_scope,
@@ -455,6 +497,14 @@ impl StoreOpaque {
self.component_data_mut().hostcall_fuel = fuel;
}
+ pub(crate) fn max_component_handles(&self) -> usize {
+ self.component_data().handle_counter.limit()
+ }
+
+ pub(crate) fn set_max_component_handles(&mut self, limit: usize) {
+ self.component_data_mut().handle_counter.set_limit(limit);
+ }
+
#[cfg(feature = "component-model-async")]
fn concurrent_resource_table(&mut self) -> Option<&mut ResourceTable> {
if self.concurrency_support() {
@@ -518,6 +568,35 @@ impl<T> Store<T> {
self.as_context_mut().set_hostcall_fuel(fuel)
}
+ /// Returns the maximum number of simultaneously-live component-model handles
+ /// permitted in this store.
+ ///
+ /// This is either the default amount if it hasn't been configured or
+ /// returns the last value passed to [`Store::set_max_component_handles`].
+ ///
+ /// See [`Store::set_max_component_handles`] for more details.
+ pub fn max_component_handles(&self) -> usize {
+ self.as_context().0.max_component_handles()
+ }
+
+ /// Sets the maximum number of simultaneously-live component-model handles
+ /// permitted in this store.
+ ///
+ /// Operations such as `resource.new` let a guest allocate handles in
+ /// host-side tables without host code in the loop, across as many instances
+ /// as it likes. This store-wide limit caps that as a DoS mitigation;
+ /// allocating past it traps.
+ ///
+ /// The limit counts *live* handles, so dropping a handle (e.g. via
+ /// `resource.drop`) returns budget and steady-state churn is unaffected.
+ /// Lowering it below the current live count does not trap existing handles,
+ /// only blocks new allocations until the count falls back under it.
+ ///
+ /// The default value for this is 100,000 handles.
+ pub fn set_max_component_handles(&mut self, limit: usize) {
+ self.as_context_mut().set_max_component_handles(limit)
+ }
+
/// Returns the underlying [`ResourceTable`] that the implementation of
/// concurrency in the component model is using.
///
@@ -541,6 +620,16 @@ impl<T> StoreContextMut<'_, T> {
self.0.set_hostcall_fuel(fuel)
}
+ /// See [`Store::max_component_handles`].
+ pub fn max_component_handles(&self) -> usize {
+ self.0.max_component_handles()
+ }
+
+ /// See [`Store::set_max_component_handles`].
+ pub fn set_max_component_handles(&mut self, limit: usize) {
+ self.0.set_max_component_handles(limit)
+ }
+
/// See [`Store::concurrent_resource_table`].
#[cfg(feature = "component-model-async")]
pub fn concurrent_resource_table(&mut self) -> Option<&mut ResourceTable> {
diff --git a/crates/wasmtime/src/runtime/vm/component.rs b/crates/wasmtime/src/runtime/vm/component.rs
index a0864b822a..040ac44657 100644
--- a/crates/wasmtime/src/runtime/vm/component.rs
+++ b/crates/wasmtime/src/runtime/vm/component.rs
@@ -42,7 +42,7 @@ mod handle_table;
mod libcalls;
mod resources;
-pub use self::handle_table::{HandleTable, RemovedResource};
+pub use self::handle_table::{HandleCounter, HandleTable, RemovedResource};
#[cfg(feature = "component-model-async")]
pub use self::handle_table::{ThreadHandleTable, TransmitLocalState, Waitable};
pub use self::resources::{
diff --git a/crates/wasmtime/src/runtime/vm/component/handle_table.rs b/crates/wasmtime/src/runtime/vm/component/handle_table.rs
index 50c9b6d019..d2e4571a41 100644
--- a/crates/wasmtime/src/runtime/vm/component/handle_table.rs
+++ b/crates/wasmtime/src/runtime/vm/component/handle_table.rs
@@ -9,6 +9,32 @@ use wasmtime_environ::component::{TypeFutureTableIndex, TypeStreamTableIndex};
/// currently and keeps the upper bits free for use in the component and ABI.
const MAX_HANDLE: u32 = 1 << 28;
+/// Live-handle count for all `HandleTable`s in a store.
+///
+/// The count tracks live handles (incremented in `insert`, decremented in
+/// `remove`), since freed slots are reused.
+pub struct HandleCounter {
+ live: usize,
+ limit: usize,
+}
+
+impl HandleCounter {
+ /// Creates a counter with no live handles and the given `limit`.
+ pub fn new(limit: usize) -> HandleCounter {
+ HandleCounter { live: 0, limit }
+ }
+
+ /// Returns the configured limit on simultaneously-live handles.
+ pub fn limit(&self) -> usize {
+ self.limit
+ }
+
+ /// Updates the limit. Does not retroactively trap tables already over it.
+ pub fn set_limit(&mut self, limit: usize) {
+ self.limit = limit;
+ }
+}
+
/// Represents the state of a stream or future handle from the perspective of a
/// given component instance.
#[derive(Debug, Eq, PartialEq)]
@@ -141,7 +167,7 @@ impl HandleTable {
.all(|slot| matches!(slot, Slot::Free { .. }))
}
- fn insert(&mut self, slot: Slot) -> Result<u32> {
+ fn insert(&mut self, counter: &mut HandleCounter, slot: Slot) -> Result<u32> {
let next = self.next;
// The component model reserves index 0 as never allocatable so add one
@@ -155,6 +181,12 @@ impl HandleTable {
bail!("cannot allocate another handle: index overflow");
}
+ // Also enforce the store-wide cap; `MAX_HANDLE` alone scales with the
+ // guest-controlled instance count. See `HandleCounter`.
+ if counter.live >= counter.limit {
+ bail!("cannot allocate another handle: store handle limit exceeded");
+ }
+
if next as usize == self.slots.len() {
self.slots.push(Slot::Free {
next: next.checked_add(1).unwrap(),
@@ -165,14 +197,21 @@ impl HandleTable {
_ => unreachable!(),
};
+ // Count the handle only once its slot is committed; pairs with the
+ // decrement in `remove`.
+ counter.live += 1;
+
Ok(next + 1)
}
- fn remove(&mut self, idx: u32) -> Result<()> {
+ fn remove(&mut self, counter: &mut HandleCounter, idx: u32) -> Result<()> {
let to_fill = Slot::Free { next: self.next };
+ // Decrement only after this `?`: `get_mut` rejects a freed slot, so a
+ // failed removal must not touch the counter.
let slot = self.get_mut(idx)?;
*slot = to_fill;
self.next = idx - 1;
+ counter.live -= 1;
Ok(())
}
@@ -195,22 +234,37 @@ impl HandleTable {
/// Inserts a new `own` resource into this table whose type/rep are
/// specified by `resource`.
- pub fn resource_own_insert(&mut self, resource: TypedResource) -> Result<u32> {
- self.insert(Slot::ResourceOwn {
- resource,
- lend_count: 0,
- })
+ pub fn resource_own_insert(
+ &mut self,
+ counter: &mut HandleCounter,
+ resource: TypedResource,
+ ) -> Result<u32> {
+ self.insert(
+ counter,
+ Slot::ResourceOwn {
+ resource,
+ lend_count: 0,
+ },
+ )
}
/// Inserts a new `borrow` resource into this table whose type/rep are
/// specified by `resource`. The `scope` specified is used by
/// `CallContexts` to manage lending information.
- pub fn resource_borrow_insert(&mut self, resource: TypedResource, scope: Scope) -> Result<u32> {
- self.insert(Slot::ResourceBorrow {
- resource,
- scope,
- lend_count: 0,
- })
+ pub fn resource_borrow_insert(
+ &mut self,
+ counter: &mut HandleCounter,
+ resource: TypedResource,
+ scope: Scope,
+ ) -> Result<u32> {
+ self.insert(
+ counter,
+ Slot::ResourceBorrow {
+ resource,
+ scope,
+ lend_count: 0,
+ },
+ )
}
/// Returns the internal "rep" of the resource specified by `idx`.
@@ -269,7 +323,11 @@ impl HandleTable {
/// This can fail if `idx` doesn't point to a resource, points to a
/// resource (own or borrow) which is currently lent out, or points to a
/// resource of the wrong type.
- pub fn remove_resource(&mut self, idx: TypedResourceIndex) -> Result<RemovedResource> {
+ pub fn remove_resource(
+ &mut self,
+ counter: &mut HandleCounter,
+ idx: TypedResourceIndex,
+ ) -> Result<RemovedResource> {
let ret = match self.get_mut(idx.raw_index())? {
Slot::ResourceOwn {
resource,
@@ -296,7 +354,7 @@ impl HandleTable {
}
_ => bail!("index {} is not a resource", idx.raw_index()),
};
- self.remove(idx.raw_index())?;
+ self.remove(counter, idx.raw_index())?;
Ok(ret)
}
@@ -304,24 +362,40 @@ impl HandleTable {
/// into this table.
///
/// Returns the table-local index of the stream.
- pub fn stream_insert_read(&mut self, ty: TypeStreamTableIndex, rep: u32) -> Result<u32> {
- self.insert(Slot::Stream {
- rep,
- ty,
- state: TransmitLocalState::Read { done: false },
- })
+ pub fn stream_insert_read(
+ &mut self,
+ counter: &mut HandleCounter,
+ ty: TypeStreamTableIndex,
+ rep: u32,
+ ) -> Result<u32> {
+ self.insert(
+ counter,
+ Slot::Stream {
+ rep,
+ ty,
+ state: TransmitLocalState::Read { done: false },
+ },
+ )
}
/// Inserts a writable-end stream of type `ty` and with the specified `rep`
/// into this table.
///
/// Returns the table-local index of the stream.
- pub fn stream_insert_write(&mut self, ty: TypeStreamTableIndex, rep: u32) -> Result<u32> {
- self.insert(Slot::Stream {
- rep,
- ty,
- state: TransmitLocalState::Write { done: false },
- })
+ pub fn stream_insert_write(
+ &mut self,
+ counter: &mut HandleCounter,
+ ty: TypeStreamTableIndex,
+ rep: u32,
+ ) -> Result<u32> {
+ self.insert(
+ counter,
+ Slot::Stream {
+ rep,
+ ty,
+ state: TransmitLocalState::Write { done: false },
+ },
+ )
}
/// Returns the `rep` and `state` associated with the stream pointed to by
@@ -354,6 +428,7 @@ impl HandleTable {
/// "done" or the writable end was witnessed as being done.
pub fn stream_remove_readable(
&mut self,
+ counter: &mut HandleCounter,
expected_ty: TypeStreamTableIndex,
idx: u32,
) -> Result<(u32, bool)> {
@@ -375,13 +450,14 @@ impl HandleTable {
}
_ => bail!("handle is not a stream"),
};
- self.remove(idx)?;
+ self.remove(counter, idx)?;
Ok(ret)
}
/// Removes the writable stream handle from `idx`, returning its `rep`.
pub fn stream_remove_writable(
&mut self,
+ counter: &mut HandleCounter,
expected_ty: TypeStreamTableIndex,
idx: u32,
) -> Result<u32> {
@@ -403,7 +479,7 @@ impl HandleTable {
}
_ => bail!("handle is not a stream"),
};
- self.remove(idx)?;
+ self.remove(counter, idx)?;
Ok(ret)
}
@@ -411,24 +487,40 @@ impl HandleTable {
/// into this table.
///
/// Returns the table-local index of the future.
- pub fn future_insert_read(&mut self, ty: TypeFutureTableIndex, rep: u32) -> Result<u32> {
- self.insert(Slot::Future {
- rep,
- ty,
- state: TransmitLocalState::Read { done: false },
- })
+ pub fn future_insert_read(
+ &mut self,
+ counter: &mut HandleCounter,
+ ty: TypeFutureTableIndex,
+ rep: u32,
+ ) -> Result<u32> {
+ self.insert(
+ counter,
+ Slot::Future {
+ rep,
+ ty,
+ state: TransmitLocalState::Read { done: false },
+ },
+ )
}
/// Inserts a writable-end future of type `ty` and with the specified `rep`
/// into this table.
///
/// Returns the table-local index of the future.
- pub fn future_insert_write(&mut self, ty: TypeFutureTableIndex, rep: u32) -> Result<u32> {
- self.insert(Slot::Future {
- rep,
- ty,
- state: TransmitLocalState::Write { done: false },
- })
+ pub fn future_insert_write(
+ &mut self,
+ counter: &mut HandleCounter,
+ ty: TypeFutureTableIndex,
+ rep: u32,
+ ) -> Result<u32> {
+ self.insert(
+ counter,
+ Slot::Future {
+ rep,
+ ty,
+ state: TransmitLocalState::Write { done: false },
+ },
+ )
}
/// Returns the `rep` and `state` associated with the future pointed to by
@@ -461,6 +553,7 @@ impl HandleTable {
/// "done" or the writable end was witnessed as being done.
pub fn future_remove_readable(
&mut self,
+ counter: &mut HandleCounter,
expected_ty: TypeFutureTableIndex,
idx: u32,
) -> Result<(u32, bool)> {
@@ -482,7 +575,7 @@ impl HandleTable {
}
_ => bail!("handle is not a future"),
};
- self.remove(idx)?;
+ self.remove(counter, idx)?;
Ok(ret)
}
@@ -491,6 +584,7 @@ impl HandleTable {
/// value or was notified that the readable end was dropped).
pub fn future_remove_writable(
&mut self,
+ counter: &mut HandleCounter,
expected_ty: TypeFutureTableIndex,
idx: u32,
) -> Result<(u32, bool)> {
@@ -512,14 +606,14 @@ impl HandleTable {
}
_ => bail!("handle is not a future"),
};
- self.remove(idx)?;
+ self.remove(counter, idx)?;
Ok(ret)
}
/// Inserts the error-context `rep` into this table, returning the index it
/// now resides at.
- pub fn error_context_insert(&mut self, rep: u32) -> Result<u32> {
- self.insert(Slot::ErrorContext { rep })
+ pub fn error_context_insert(&mut self, counter: &mut HandleCounter, rep: u32) -> Result<u32> {
+ self.insert(counter, Slot::ErrorContext { rep })
}
/// Returns the `rep` of an error-context pointed to by `idx`.
@@ -533,23 +627,23 @@ impl HandleTable {
/// Drops the error-context pointed to by `idx`.
///
/// Returns the internal `rep`.
- pub fn error_context_drop(&mut self, idx: u32) -> Result<u32> {
+ pub fn error_context_drop(&mut self, counter: &mut HandleCounter, idx: u32) -> Result<u32> {
let rep = match self.get_mut(idx)? {
Slot::ErrorContext { rep } => *rep,
_ => bail!("handle is not an error-context"),
};
- self.remove(idx)?;
+ self.remove(counter, idx)?;
Ok(rep)
}
/// Inserts `rep` as a guest subtask into this table.
- pub fn subtask_insert_guest(&mut self, rep: u32) -> Result<u32> {
- self.insert(Slot::GuestTask { rep })
+ pub fn subtask_insert_guest(&mut self, counter: &mut HandleCounter, rep: u32) -> Result<u32> {
+ self.insert(counter, Slot::GuestTask { rep })
}
/// Inserts `rep` as a host subtask into this table.
- pub fn subtask_insert_host(&mut self, rep: u32) -> Result<u32> {
- self.insert(Slot::HostTask { rep })
+ pub fn subtask_insert_host(&mut self, counter: &mut HandleCounter, rep: u32) -> Result<u32> {
+ self.insert(counter, Slot::HostTask { rep })
}
/// Returns the `rep` of the subtask at `idx` as well as if it's a host
@@ -563,19 +657,19 @@ impl HandleTable {
}
/// Removes the subtask set at `idx`, returning its `rep`.
- pub fn subtask_remove(&mut self, idx: u32) -> Result<(u32, bool)> {
+ pub fn subtask_remove(&mut self, counter: &mut HandleCounter, idx: u32) -> Result<(u32, bool)> {
let ret = match self.get_mut(idx)? {
Slot::GuestTask { rep } => (*rep, false),
Slot::HostTask { rep } => (*rep, true),
_ => bail!("handle is not a subtask"),
};
- self.remove(idx)?;
+ self.remove(counter, idx)?;
Ok(ret)
}
/// Inserts `rep` as a waitable set into this table.
- pub fn waitable_set_insert(&mut self, rep: u32) -> Result<u32> {
- self.insert(Slot::WaitableSet { rep })
+ pub fn waitable_set_insert(&mut self, counter: &mut HandleCounter, rep: u32) -> Result<u32> {
+ self.insert(counter, Slot::WaitableSet { rep })
}
/// Returns the `rep` of an waitable-set pointed to by `idx`.
@@ -587,12 +681,12 @@ impl HandleTable {
}
/// Removes the waitable set at `idx`, returning its `rep`.
- pub fn waitable_set_remove(&mut self, idx: u32) -> Result<u32> {
+ pub fn waitable_set_remove(&mut self, counter: &mut HandleCounter, idx: u32) -> Result<u32> {
let ret = match self.get_mut(idx)? {
Slot::WaitableSet { rep } => *rep,
_ => bail!("handle is not a waitable-set"),
};
- self.remove(idx)?;
+ self.remove(counter, idx)?;
Ok(ret)
}
@@ -617,8 +711,8 @@ pub struct ThreadHandleTable(HandleTable);
impl ThreadHandleTable {
/// Inserts the guest thread `rep` into this table, returning the index it
/// now resides at.
- pub fn guest_thread_insert(&mut self, rep: u32) -> Result<u32> {
- self.0.insert(Slot::GuestThread { rep })
+ pub fn guest_thread_insert(&mut self, counter: &mut HandleCounter, rep: u32) -> Result<u32> {
+ self.0.insert(counter, Slot::GuestThread { rep })
}
/// Returns the `rep` of a guest thread pointed to by `idx`.
@@ -632,12 +726,12 @@ impl ThreadHandleTable {
/// Removes the guest thread pointed to by `idx`.
///
/// Returns the internal `rep`.
- pub fn guest_thread_remove(&mut self, idx: u32) -> Result<u32> {
+ pub fn guest_thread_remove(&mut self, counter: &mut HandleCounter, idx: u32) -> Result<u32> {
let rep = match self.0.get_mut(idx)? {
Slot::GuestThread { rep } => *rep,
_ => bail!("handle is not a guest thread"),
};
- self.0.remove(idx)?;
+ self.0.remove(counter, idx)?;
Ok(rep)
}
}
diff --git a/crates/wasmtime/src/runtime/vm/component/resources.rs b/crates/wasmtime/src/runtime/vm/component/resources.rs
index a8039af1a0..b2fbc17257 100644
--- a/crates/wasmtime/src/runtime/vm/component/resources.rs
+++ b/crates/wasmtime/src/runtime/vm/component/resources.rs
@@ -20,7 +20,7 @@
//! about ABI details can be found in lifting/lowering throughout Wasmtime,
//! namely in the `Resource<T>` and `ResourceAny` types.
-use super::{HandleTable, InstanceState, RemovedResource};
+use super::{HandleCounter, HandleTable, InstanceState, RemovedResource};
use crate::bail_bug;
use crate::component::store::ComponentTaskState;
use crate::prelude::*;
@@ -69,6 +69,10 @@ pub struct ResourceTables<'a> {
/// type.
pub host_table: &'a mut HandleTable,
+ /// The store-wide live-handle counter, charged by every insertion into and
+ /// removal from any of the tables above.
+ pub handle_counter: &'a mut HandleCounter,
+
/// Task information about calls actively in use to track information such
/// as borrow counts.
pub task_state: &'a mut ComponentTaskState,
@@ -204,39 +208,47 @@ impl CallContext {
}
impl ResourceTables<'_> {
- fn table_for_resource(&mut self, resource: &TypedResource) -> &mut HandleTable {
- match resource {
- TypedResource::Host(_) => self.host_table,
+ fn table_for_resource(
+ &mut self,
+ resource: &TypedResource,
+ ) -> (&mut HandleTable, &mut HandleCounter) {
+ let table = match resource {
+ TypedResource::Host(_) => &mut *self.host_table,
TypedResource::Component { ty, .. } => {
let (states, types) = self.guest.as_mut().unwrap();
states[types[*ty].unwrap_concrete_instance()].handle_table()
}
- }
+ };
+ (table, &mut *self.handle_counter)
}
- fn table_for_index(&mut self, index: &TypedResourceIndex) -> &mut HandleTable {
- match index {
- TypedResourceIndex::Host(_) => self.host_table,
+ fn table_for_index(
+ &mut self,
+ index: &TypedResourceIndex,
+ ) -> (&mut HandleTable, &mut HandleCounter) {
+ let table = match index {
+ TypedResourceIndex::Host(_) => &mut *self.host_table,
TypedResourceIndex::Component { ty, .. } => {
let (states, types) = self.guest.as_mut().unwrap();
states[types[*ty].unwrap_concrete_instance()].handle_table()
}
- }
+ };
+ (table, &mut *self.handle_counter)
}
/// Implementation of the `resource.new` canonical intrinsic.
///
/// Note that this is the same as `resource_lower_own`.
pub fn resource_new(&mut self, resource: TypedResource) -> Result<u32> {
- self.table_for_resource(&resource)
- .resource_own_insert(resource)
+ let (table, counter) = self.table_for_resource(&resource);
+ table.resource_own_insert(counter, resource)
}
/// Implementation of the `resource.rep` canonical intrinsic.
///
/// This one's one of the simpler ones: "just get the rep please"
pub fn resource_rep(&mut self, index: TypedResourceIndex) -> Result<u32> {
- self.table_for_index(&index).resource_rep(index)
+ self.table_for_index(&index).0.resource_rep(index)
}
/// Implementation of the `resource.drop` canonical intrinsic minus the
@@ -253,7 +265,8 @@ impl ResourceTables<'_> {
/// to run. If `None` is returned then that means a `borrow` handle was
/// removed and no destructor is necessary.
pub fn resource_drop(&mut self, index: TypedResourceIndex) -> Result<Option<u32>> {
- match self.table_for_index(&index).remove_resource(index)? {
+ let (table, counter) = self.table_for_index(&index);
+ match table.remove_resource(counter, index)? {
RemovedResource::Own { rep } => Ok(Some(rep)),
RemovedResource::Borrow { scope } => {
self.task_state.call_context(scope)?.borrow_count -= 1;
@@ -272,8 +285,8 @@ impl ResourceTables<'_> {
///
/// This is an implementation of the canonical ABI `lower_own` function.
pub fn resource_lower_own(&mut self, resource: TypedResource) -> Result<u32> {
- self.table_for_resource(&resource)
- .resource_own_insert(resource)
+ let (table, counter) = self.table_for_resource(&resource);
+ table.resource_own_insert(counter, resource)
}
/// Attempts to remove an "own" handle from the specified table and its
@@ -285,7 +298,8 @@ impl ResourceTables<'_> {
///
/// This is an implementation of the canonical ABI `lift_own` function.
pub fn resource_lift_own(&mut self, index: TypedResourceIndex) -> Result<u32> {
- match self.table_for_index(&index).remove_resource(index)? {
+ let (table, counter) = self.table_for_index(&index);
+ match table.remove_resource(counter, index)? {
RemovedResource::Own { rep } => Ok(rep),
RemovedResource::Borrow { .. } => bail!("cannot lift own resource from a borrow"),
}
@@ -347,7 +361,7 @@ impl ResourceTables<'_> {
// tasks. Ideally the `lenders.push` would be skipped for sync tasks but
// that requires a bit more plumbing and also appropriately tracking the
// `lend_count` and such. For now this treats own/borrow the same way.
- let rep = self.table_for_index(&index).resource_lend(index)?;
+ let rep = self.table_for_index(&index).0.resource_lend(index)?;
self.current_scope()?.lenders.push(index);
Ok(rep)
}
@@ -368,8 +382,8 @@ impl ResourceTables<'_> {
let scope = self.materialize_current_scope()?;
let cx = self.task_state.call_context(scope)?;
cx.borrow_count = cx.borrow_count.checked_add(1).unwrap();
- self.table_for_resource(&resource)
- .resource_borrow_insert(resource, scope)
+ let (table, counter) = self.table_for_resource(&resource);
+ table.resource_borrow_insert(counter, resource, scope)
}
/// Validates that the current scope can be exited.
@@ -388,6 +402,7 @@ impl ResourceTables<'_> {
// due to the dynamic tracking of borrows and such employed for
// resources.
self.table_for_index(&lender)
+ .0
.resource_undo_lend(lender)
.unwrap();
}
diff --git a/src/common.rs b/src/common.rs
index 0b1ef29196..09ca97e1c2 100644
--- a/src/common.rs
+++ b/src/common.rs
@@ -515,6 +515,9 @@ impl RunCommon {
if let Some(fuel) = self.common.wasi.hostcall_fuel {
store.set_hostcall_fuel(fuel);
}
+ if let Some(max) = self.common.wasi.max_component_handles {
+ store.set_max_component_handles(max);
+ }
*limits(store.data_mut()) = self.store_limits();
store.limiter(move |t| limits(t));
diff --git a/tests/all/component_model.rs b/tests/all/component_model.rs
index 9abc8d782e..8a3303a08d 100644
--- a/tests/all/component_model.rs
+++ b/tests/all/component_model.rs
@@ -15,6 +15,7 @@ mod call_hook;
mod dynamic;
mod fixed_length_list;
mod func;
+mod handle_table_limit;
mod import;
mod instance;
mod linker;
diff --git a/tests/all/component_model/handle_table_limit.rs b/tests/all/component_model/handle_table_limit.rs
new file mode 100644
index 0000000000..850db29096
--- /dev/null
+++ b/tests/all/component_model/handle_table_limit.rs
@@ -0,0 +1,146 @@
+//! Tests for the store-level cap on the number of simultaneously-live
+//! component-model handles.
+
+#![cfg(not(miri))]
+
+use super::engine;
+use crate::ErrorExt;
+use wasmtime::component::{Component, Linker};
+use wasmtime::{Result, Store};
+
+/// Two instances of one sub-component, each with its own handle table, so the
+/// per-store nature of the cap can be exercised. `sprayN(n)` allocates `n` live
+/// handles; `churnN(n)` allocates and drops one `n` times, staying at one live.
+const COMPONENT: &str = r#"
+(component
+ (component $C
+ (type $r (resource (rep i32)))
+ (core func $new (canon resource.new $r))
+ (core func $drop (canon resource.drop $r))
+ (core module $m
+ (import "" "new" (func $new (param i32) (result i32)))
+ (import "" "drop" (func $drop (param i32)))
+ (func (export "spray") (param $n i32) (result i32)
+ (local $i i32)
+ (loop $l
+ (if (i32.lt_u (local.get $i) (local.get $n))
+ (then
+ (drop (call $new (local.get $i)))
+ (local.set $i (i32.add (local.get $i) (i32.const 1)))
+ (br $l))))
+ (local.get $i))
+ (func (export "churn") (param $n i32) (result i32)
+ (local $i i32)
+ (loop $l
+ (if (i32.lt_u (local.get $i) (local.get $n))
+ (then
+ (call $drop (call $new (local.get $i)))
+ (local.set $i (i32.add (local.get $i) (i32.const 1)))
+ (br $l))))
+ (local.get $i)))
+ (core instance $i (instantiate $m
+ (with "" (instance
+ (export "new" (func $new))
+ (export "drop" (func $drop))))))
+ (func (export "spray") (param "n" u32) (result u32)
+ (canon lift (core func $i "spray")))
+ (func (export "churn") (param "n" u32) (result u32)
+ (canon lift (core func $i "churn"))))
+
+ (instance $i0 (instantiate $C))
+ (export "spray0" (func $i0 "spray"))
+ (export "churn0" (func $i0 "churn"))
+ (instance $i1 (instantiate $C))
+ (export "spray1" (func $i1 "spray"))
+ (export "churn1" (func $i1 "churn"))
+)
+"#;
+
+/// The cap is per store, not per table: two instances whose combined (but not
+/// individual) allocations cross the limit. The old per-table `MAX_HANDLE` check
+/// would let this pass.
+#[test]
+fn cap_is_per_store_not_per_table() -> Result<()> {
+ let engine = engine();
+ let component = Component::new(&engine, COMPONENT)?;
+ let linker = Linker::new(&engine);
+
+ let mut store = Store::new(&engine, ());
+ store.set_max_component_handles(20);
+
+ let instance = linker.instantiate(&mut store, &component)?;
+ let spray0 = instance.get_typed_func::<(u32,), (u32,)>(&mut store, "spray0")?;
+ let spray1 = instance.get_typed_func::<(u32,), (u32,)>(&mut store, "spray1")?;
+
+ // 12 is under the limit of 20, so this alone succeeds.
+ let (n,) = spray0.call(&mut store, (12,))?;
+ assert_eq!(n, 12);
+
+ // Another 12 in the second instance's own table trips the shared limit; a
+ // per-table cap would allow it.
+ spray1
+ .call(&mut store, (12,))
+ .unwrap_err()
+ .assert_contains("store handle limit exceeded");
+
+ Ok(())
+}
+
+/// Raising the limit admits a spray a tight limit rejects.
+#[test]
+fn knob_raises_the_limit() -> Result<()> {
+ let engine = engine();
+ let component = Component::new(&engine, COMPONENT)?;
+ let linker = Linker::new(&engine);
+
+ // Tight limit: spraying past it traps.
+ let mut store = Store::new(&engine, ());
+ store.set_max_component_handles(10);
+ assert_eq!(store.max_component_handles(), 10);
+ let instance = linker.instantiate(&mut store, &component)?;
+ let spray0 = instance.get_typed_func::<(u32,), (u32,)>(&mut store, "spray0")?;
+ spray0
+ .call(&mut store, (50,))
+ .unwrap_err()
+ .assert_contains("store handle limit exceeded");
+
+ // Generous limit: the same spray succeeds.
+ let mut store = Store::new(&engine, ());
+ store.set_max_component_handles(1_000);
+ assert_eq!(store.max_component_handles(), 1_000);
+ let instance = linker.instantiate(&mut store, &component)?;
+ let spray0 = instance.get_typed_func::<(u32,), (u32,)>(&mut store, "spray0")?;
+ let (n,) = spray0.call(&mut store, (50,))?;
+ assert_eq!(n, 50);
+
+ Ok(())
+}
+
+/// The cap counts live handles, not cumulative allocations: churning well past
+/// the limit succeeds because each handle is dropped. Catches a missing
+/// decrement in `remove`.
+#[test]
+fn freeing_handles_returns_budget() -> Result<()> {
+ let engine = engine();
+ let component = Component::new(&engine, COMPONENT)?;
+ let linker = Linker::new(&engine);
+
+ let mut store = Store::new(&engine, ());
+ let limit = 100;
+ store.set_max_component_handles(limit);
+
+ let instance = linker.instantiate(&mut store, &component)?;
+ let churn0 = instance.get_typed_func::<(u32,), (u32,)>(&mut store, "churn0")?;
+
+ // Far more allocations than the limit, each dropped, so live count stays low.
+ let total = u32::try_from(limit).unwrap() * 100;
+ let (n,) = churn0.call(&mut store, (total,))?;
+ assert_eq!(n, total);
+
+ // The budget is fully available again afterward.
+ let spray0 = instance.get_typed_func::<(u32,), (u32,)>(&mut store, "spray0")?;
+ let (n,) = spray0.call(&mut store, (50,))?;
+ assert_eq!(n, 50);
+
+ Ok(())
+}