Skip to content

Commit

Permalink
Remove the ModuleLimits pooling configuration structure (#3837)
Browse files Browse the repository at this point in the history
* Remove the `ModuleLimits` pooling configuration structure

This commit is an attempt to improve the usability of the pooling
allocator by removing the need to configure a `ModuleLimits` structure.
Internally this structure has limits on all forms of wasm constructs but
this largely bottoms out in the size of an allocation for an instance in
the instance pooling allocator. Maintaining this list of limits can be
cumbersome as modules may get tweaked over time and there's otherwise no
real reason to limit the number of globals in a module since the main
goal is to limit the memory consumption of a `VMContext` which can be
done with a memory allocation limit rather than fine-tuned control over
each maximum and minimum.

The new approach taken in this commit is to remove `ModuleLimits`. Some
fields, such as `tables`, `table_elements` , `memories`, and
`memory_pages` are moved to `InstanceLimits` since they're still
enforced at runtime. A new field `size` is added to `InstanceLimits`
which indicates, in bytes, the maximum size of the `VMContext`
allocation. If the size of a `VMContext` for a module exceeds this value
then instantiation will fail.

This involved adding a few more checks to `{Table, Memory}::new_static`
to ensure that the minimum size is able to fit in the allocation, since
previously modules were validated at compile time of the module that
everything fit and that validation no longer happens (it happens at
runtime).

A consequence of this commit is that Wasmtime will have no built-in way
to reject modules at compile time if they'll fail to be instantiated
within a particular pooling allocator configuration. Instead a module
must attempt instantiation see if a failure happens.

* Fix benchmark compiles

* Fix some doc links

* Fix a panic by ensuring modules have limited tables/memories

* Review comments

* Add back validation at `Module` time instantiation is possible

This allows for getting an early signal at compile time that a module
will never be instantiable in an engine with matching settings.

* Provide a better error message when sizes are exceeded

Improve the error message when an instance size exceeds the maximum by
providing a breakdown of where the bytes are all going and why the large
size is being requested.

* Try to fix test in qemu

* Flag new test as 64-bit only

Sizes are all specific to 64-bit right now
  • Loading branch information
alexcrichton authored Feb 25, 2022
1 parent b064e60 commit 15bb0c6
Show file tree
Hide file tree
Showing 20 changed files with 563 additions and 1,084 deletions.
9 changes: 3 additions & 6 deletions benches/instantiation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,13 +209,10 @@ fn strategies() -> impl Iterator<Item = InstanceAllocationStrategy> {
InstanceAllocationStrategy::OnDemand,
InstanceAllocationStrategy::Pooling {
strategy: Default::default(),
module_limits: ModuleLimits {
functions: 40_000,
memory_pages: 1_000,
types: 200,
..ModuleLimits::default()
instance_limits: InstanceLimits {
memory_pages: 10_000,
..Default::default()
},
instance_limits: InstanceLimits::default(),
},
])
}
Expand Down
4 changes: 2 additions & 2 deletions benches/thread_eager_init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,11 @@ fn test_setup() -> (Engine, Module) {
let mut config = Config::new();
config.allocation_strategy(InstanceAllocationStrategy::Pooling {
strategy: PoolingAllocationStrategy::NextAvailable,
module_limits: ModuleLimits {
instance_limits: InstanceLimits {
count: pool_count,
memory_pages: 1,
..Default::default()
},
instance_limits: InstanceLimits { count: pool_count },
});
let engine = Engine::new(&config).unwrap();

Expand Down
61 changes: 61 additions & 0 deletions crates/environ/src/vmoffsets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,67 @@ impl<P: PtrSize> VMOffsets<P> {
pub fn pointer_size(&self) -> u8 {
self.ptr.size()
}

/// Returns an iterator which provides a human readable description and a
/// byte size. The iterator returned will iterate over the bytes allocated
/// to the entire `VMOffsets` structure to explain where each byte size is
/// coming from.
pub fn region_sizes(&self) -> impl Iterator<Item = (&str, u32)> {
macro_rules! calculate_sizes {
($($name:ident: $desc:tt,)*) => {{
let VMOffsets {
// These fields are metadata not talking about specific
// offsets of specific fields.
ptr: _,
num_imported_functions: _,
num_imported_tables: _,
num_imported_memories: _,
num_imported_globals: _,
num_defined_tables: _,
num_defined_globals: _,
num_defined_memories: _,
num_defined_functions: _,

// used as the initial size below
size,

// exhaustively match teh rest of the fields with input from
// the macro
$($name,)*
} = *self;

// calculate the size of each field by relying on the inputs to
// the macro being in reverse order and determining the size of
// the field as the offset from the field to the last field.
let mut last = size;
$(
assert!($name <= last);
let tmp = $name;
let $name = last - $name;
last = tmp;
)*
assert_eq!(last, 0);
IntoIterator::into_iter([$(($desc, $name),)*])
}};
}

calculate_sizes! {
defined_anyfuncs: "module functions",
defined_globals: "defined globals",
defined_memories: "defined memories",
defined_tables: "defined tables",
imported_globals: "imported globals",
imported_memories: "imported memories",
imported_tables: "imported tables",
imported_functions: "imported functions",
signature_ids: "module types",
builtin_functions: "jit builtin functions state",
store: "jit store state",
externref_activations_table: "jit host externref state",
epoch_ptr: "jit current epoch state",
interrupts: "jit interrupt state",
}
}
}

impl<P: PtrSize> From<VMOffsetsFields<P>> for VMOffsets<P> {
Expand Down
121 changes: 27 additions & 94 deletions crates/fuzzing/src/generators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,88 +60,48 @@ impl PoolingAllocationStrategy {
}
}
}

/// Configuration for `wasmtime::ModuleLimits`.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ModuleLimits {
imported_functions: u32,
imported_tables: u32,
imported_memories: u32,
imported_globals: u32,
types: u32,
functions: u32,
tables: u32,
memories: u32,
/// The maximum number of globals that can be defined in a module.
pub globals: u32,
table_elements: u32,
memory_pages: u64,
/// Configuration for `wasmtime::PoolingAllocationStrategy`.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[allow(missing_docs)]
pub struct InstanceLimits {
pub count: u32,
pub memories: u32,
pub tables: u32,
pub memory_pages: u64,
pub table_elements: u32,
pub size: usize,
}

impl ModuleLimits {
fn to_wasmtime(&self) -> wasmtime::ModuleLimits {
wasmtime::ModuleLimits {
imported_functions: self.imported_functions,
imported_tables: self.imported_tables,
imported_memories: self.imported_memories,
imported_globals: self.imported_globals,
types: self.types,
functions: self.functions,
tables: self.tables,
impl InstanceLimits {
fn to_wasmtime(&self) -> wasmtime::InstanceLimits {
wasmtime::InstanceLimits {
count: self.count,
memories: self.memories,
globals: self.globals,
table_elements: self.table_elements,
tables: self.tables,
memory_pages: self.memory_pages,
table_elements: self.table_elements,
size: self.size,
}
}
}

impl<'a> Arbitrary<'a> for ModuleLimits {
impl<'a> Arbitrary<'a> for InstanceLimits {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
const MAX_IMPORTS: u32 = 1000;
const MAX_TYPES: u32 = 1000;
const MAX_FUNCTIONS: u32 = 1000;
const MAX_COUNT: u32 = 100;

const MAX_TABLES: u32 = 10;
const MAX_MEMORIES: u32 = 10;
const MAX_GLOBALS: u32 = 1000;
const MAX_ELEMENTS: u32 = 1000;
const MAX_MEMORY_PAGES: u64 = 160; // 10 MiB
const MAX_SIZE: usize = 1 << 20; // 1 MiB

Ok(Self {
imported_functions: u.int_in_range(0..=MAX_IMPORTS)?,
imported_tables: u.int_in_range(0..=MAX_IMPORTS)?,
imported_memories: u.int_in_range(0..=MAX_IMPORTS)?,
imported_globals: u.int_in_range(0..=MAX_IMPORTS)?,
types: u.int_in_range(0..=MAX_TYPES)?,
functions: u.int_in_range(0..=MAX_FUNCTIONS)?,
tables: u.int_in_range(0..=MAX_TABLES)?,
memories: u.int_in_range(0..=MAX_MEMORIES)?,
globals: u.int_in_range(0..=MAX_GLOBALS)?,
table_elements: u.int_in_range(0..=MAX_ELEMENTS)?,
memory_pages: u.int_in_range(0..=MAX_MEMORY_PAGES)?,
})
}
}

/// Configuration for `wasmtime::PoolingAllocationStrategy`.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct InstanceLimits {
/// The maximum number of instances that can be instantiated in the pool at a time.
pub count: u32,
}

impl InstanceLimits {
fn to_wasmtime(&self) -> wasmtime::InstanceLimits {
wasmtime::InstanceLimits { count: self.count }
}
}

impl<'a> Arbitrary<'a> for InstanceLimits {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
const MAX_COUNT: u32 = 100;

Ok(Self {
count: u.int_in_range(1..=MAX_COUNT)?,
size: u.int_in_range(0..=MAX_SIZE)?,
})
}
}
Expand All @@ -155,8 +115,6 @@ pub enum InstanceAllocationStrategy {
Pooling {
/// The pooling strategy to use.
strategy: PoolingAllocationStrategy,
/// The module limits.
module_limits: ModuleLimits,
/// The instance limits.
instance_limits: InstanceLimits,
},
Expand All @@ -168,11 +126,9 @@ impl InstanceAllocationStrategy {
InstanceAllocationStrategy::OnDemand => wasmtime::InstanceAllocationStrategy::OnDemand,
InstanceAllocationStrategy::Pooling {
strategy,
module_limits,
instance_limits,
} => wasmtime::InstanceAllocationStrategy::Pooling {
strategy: strategy.to_wasmtime(),
module_limits: module_limits.to_wasmtime(),
instance_limits: instance_limits.to_wasmtime(),
},
}
Expand Down Expand Up @@ -203,7 +159,7 @@ impl<'a> Arbitrary<'a> for Config {
// If using the pooling allocator, constrain the memory and module configurations
// to the module limits.
if let InstanceAllocationStrategy::Pooling {
module_limits: limits,
instance_limits: limits,
..
} = &config.wasmtime.strategy
{
Expand All @@ -223,14 +179,6 @@ impl<'a> Arbitrary<'a> for Config {
};

let cfg = &mut config.module_config.config;
cfg.max_imports = limits.imported_functions.min(
limits
.imported_globals
.min(limits.imported_memories.min(limits.imported_tables)),
) as usize;
cfg.max_types = limits.types as usize;
cfg.max_funcs = limits.functions as usize;
cfg.max_globals = limits.globals as usize;
cfg.max_memories = limits.memories as usize;
cfg.max_tables = limits.tables as usize;
cfg.max_memory_pages = limits.memory_pages;
Expand Down Expand Up @@ -343,21 +291,13 @@ impl Config {
config.simd_enabled = false;
config.memory64_enabled = false;

// If using the pooling allocator, update the module limits too
// If using the pooling allocator, update the instance limits too
if let InstanceAllocationStrategy::Pooling {
module_limits: limits,
instance_limits: limits,
..
} = &mut self.wasmtime.strategy
{
// No imports
limits.imported_functions = 0;
limits.imported_tables = 0;
limits.imported_memories = 0;
limits.imported_globals = 0;

// One type, one function, and one single-page memory
limits.types = 1;
limits.functions = 1;
// One single-page memory
limits.memories = 1;
limits.memory_pages = 1;

Expand Down Expand Up @@ -385,13 +325,6 @@ impl Config {

if let Some(default_fuel) = default_fuel {
module.ensure_termination(default_fuel);

// Bump the allowed global count by 1
if let InstanceAllocationStrategy::Pooling { module_limits, .. } =
&mut self.wasmtime.strategy
{
module_limits.globals += 1;
}
}

Ok(module)
Expand All @@ -408,7 +341,7 @@ impl Config {
config.max_memories = 1;

if let InstanceAllocationStrategy::Pooling {
module_limits: limits,
instance_limits: limits,
..
} = &mut self.wasmtime.strategy
{
Expand Down
4 changes: 1 addition & 3 deletions crates/runtime/src/instance/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ use wasmtime_environ::{
mod pooling;

#[cfg(feature = "pooling-allocator")]
pub use self::pooling::{
InstanceLimits, ModuleLimits, PoolingAllocationStrategy, PoolingInstanceAllocator,
};
pub use self::pooling::{InstanceLimits, PoolingAllocationStrategy, PoolingInstanceAllocator};

/// Represents a request for a new runtime instance.
pub struct InstanceAllocationRequest<'a> {
Expand Down
Loading

0 comments on commit 15bb0c6

Please sign in to comment.