1 //! Implements the pooling instance allocator.
2 //!
3 //! The pooling instance allocator maps memory in advance and allocates
4 //! instances, memories, tables, and stacks from a pool of available resources.
5 //! Using the pooling instance allocator can speed up module instantiation when
6 //! modules can be constrained based on configurable limits
7 //! ([`InstanceLimits`]). Each new instance is stored in a "slot"; as instances
8 //! are allocated and freed, these slots are either filled or emptied:
9 //!
10 //! ```text
11 //! ┌──────┬──────┬──────┬──────┬──────┐
12 //! │Slot 0│Slot 1│Slot 2│Slot 3│......│
13 //! └──────┴──────┴──────┴──────┴──────┘
14 //! ```
15 //!
16 //! Each slot has a "slot ID"--an index into the pool. Slot IDs are handed out
17 //! by the [`index_allocator`] module. Note that each kind of pool-allocated
18 //! item is stored in its own separate pool: [`memory_pool`], [`table_pool`],
19 //! [`stack_pool`]. See those modules for more details.
20 
21 mod decommit_queue;
22 mod index_allocator;
23 mod memory_pool;
24 mod table_pool;
25 
26 #[cfg(feature = "gc")]
27 mod gc_heap_pool;
28 
29 #[cfg(all(feature = "async"))]
30 mod generic_stack_pool;
31 #[cfg(all(feature = "async", unix, not(miri)))]
32 mod unix_stack_pool;
33 
34 #[cfg(all(feature = "async"))]
35 cfg_if::cfg_if! {
36     if #[cfg(all(unix, not(miri), not(asan)))] {
37         use unix_stack_pool as stack_pool;
38     } else {
39         use generic_stack_pool as stack_pool;
40     }
41 }
42 
43 use self::decommit_queue::DecommitQueue;
44 use self::memory_pool::MemoryPool;
45 use self::table_pool::TablePool;
46 use super::{
47     InstanceAllocationRequest, InstanceAllocatorImpl, MemoryAllocationIndex, TableAllocationIndex,
48 };
49 use crate::prelude::*;
50 use crate::runtime::vm::{
51     instance::Instance,
52     mpk::{self, MpkEnabled, ProtectionKey, ProtectionMask},
53     CompiledModuleId, Memory, Table,
54 };
55 use std::borrow::Cow;
56 use std::fmt::Display;
57 use std::sync::{Mutex, MutexGuard};
58 use std::{
59     mem,
60     sync::atomic::{AtomicU64, Ordering},
61 };
62 use wasmtime_environ::{
63     DefinedMemoryIndex, DefinedTableIndex, HostPtr, MemoryPlan, Module, TablePlan, Tunables,
64     VMOffsets,
65 };
66 
67 #[cfg(feature = "gc")]
68 use super::GcHeapAllocationIndex;
69 #[cfg(feature = "gc")]
70 use crate::runtime::vm::{GcHeap, GcRuntime};
71 #[cfg(feature = "gc")]
72 use gc_heap_pool::GcHeapPool;
73 
74 #[cfg(feature = "async")]
75 use stack_pool::StackPool;
76 
77 #[cfg(feature = "component-model")]
78 use wasmtime_environ::{
79     component::{Component, VMComponentOffsets},
80     StaticModuleIndex,
81 };
82 
83 fn round_up_to_pow2(n: usize, to: usize) -> usize {
84     debug_assert!(to > 0);
85     debug_assert!(to.is_power_of_two());
86     (n + to - 1) & !(to - 1)
87 }
88 
89 /// Instance-related limit configuration for pooling.
90 ///
91 /// More docs on this can be found at `wasmtime::PoolingAllocationConfig`.
92 #[derive(Debug, Copy, Clone)]
93 pub struct InstanceLimits {
94     /// The maximum number of component instances that may be allocated
95     /// concurrently.
96     pub total_component_instances: u32,
97 
98     /// The maximum size of a component's `VMComponentContext`, not including
99     /// any of its inner core modules' `VMContext` sizes.
100     pub component_instance_size: usize,
101 
102     /// The maximum number of core module instances that may be allocated
103     /// concurrently.
104     pub total_core_instances: u32,
105 
106     /// The maximum number of core module instances that a single component may
107     /// transitively contain.
108     pub max_core_instances_per_component: u32,
109 
110     /// The maximum number of Wasm linear memories that a component may
111     /// transitively contain.
112     pub max_memories_per_component: u32,
113 
114     /// The maximum number of tables that a component may transitively contain.
115     pub max_tables_per_component: u32,
116 
117     /// The total number of linear memories in the pool, across all instances.
118     pub total_memories: u32,
119 
120     /// The total number of tables in the pool, across all instances.
121     pub total_tables: u32,
122 
123     /// The total number of async stacks in the pool, across all instances.
124     #[cfg(feature = "async")]
125     pub total_stacks: u32,
126 
127     /// Maximum size of a core instance's `VMContext`.
128     pub core_instance_size: usize,
129 
130     /// Maximum number of tables per instance.
131     pub max_tables_per_module: u32,
132 
133     /// Maximum number of table elements per table.
134     pub table_elements: u32,
135 
136     /// Maximum number of linear memories per instance.
137     pub max_memories_per_module: u32,
138 
139     /// Maximum byte size of a linear memory, must be smaller than
140     /// `static_memory_reservation` in `Tunables`.
141     pub max_memory_size: usize,
142 
143     /// The total number of GC heaps in the pool, across all instances.
144     #[cfg(feature = "gc")]
145     pub total_gc_heaps: u32,
146 }
147 
148 impl Default for InstanceLimits {
149     fn default() -> Self {
150         // See doc comments for `wasmtime::PoolingAllocationConfig` for these
151         // default values
152         Self {
153             total_component_instances: 1000,
154             component_instance_size: 1 << 20, // 1 MiB
155             total_core_instances: 1000,
156             max_core_instances_per_component: 20,
157             max_memories_per_component: 20,
158             max_tables_per_component: 20,
159             total_memories: 1000,
160             total_tables: 1000,
161             #[cfg(feature = "async")]
162             total_stacks: 1000,
163             core_instance_size: 1 << 20, // 1 MiB
164             max_tables_per_module: 1,
165             // NB: in #8504 it was seen that a C# module in debug module can
166             // have 10k+ elements.
167             table_elements: 20_000,
168             max_memories_per_module: 1,
169             max_memory_size: 1 << 32, // 4G,
170             #[cfg(feature = "gc")]
171             total_gc_heaps: 1000,
172         }
173     }
174 }
175 
176 /// Configuration options for the pooling instance allocator supplied at
177 /// construction.
178 #[derive(Copy, Clone, Debug)]
179 pub struct PoolingInstanceAllocatorConfig {
180     /// See `PoolingAllocatorConfig::max_unused_warm_slots` in `wasmtime`
181     pub max_unused_warm_slots: u32,
182     /// The target number of decommits to do per batch. This is not precise, as
183     /// we can queue up decommits at times when we aren't prepared to
184     /// immediately flush them, and so we may go over this target size
185     /// occasionally.
186     pub decommit_batch_size: usize,
187     /// The size, in bytes, of async stacks to allocate (not including the guard
188     /// page).
189     pub stack_size: usize,
190     /// The limits to apply to instances allocated within this allocator.
191     pub limits: InstanceLimits,
192     /// Whether or not async stacks are zeroed after use.
193     pub async_stack_zeroing: bool,
194     /// If async stack zeroing is enabled and the host platform is Linux this is
195     /// how much memory to zero out with `memset`.
196     ///
197     /// The rest of memory will be zeroed out with `madvise`.
198     pub async_stack_keep_resident: usize,
199     /// How much linear memory, in bytes, to keep resident after resetting for
200     /// use with the next instance. This much memory will be `memset` to zero
201     /// when a linear memory is deallocated.
202     ///
203     /// Memory exceeding this amount in the wasm linear memory will be released
204     /// with `madvise` back to the kernel.
205     ///
206     /// Only applicable on Linux.
207     pub linear_memory_keep_resident: usize,
208     /// Same as `linear_memory_keep_resident` but for tables.
209     pub table_keep_resident: usize,
210     /// Whether to enable memory protection keys.
211     pub memory_protection_keys: MpkEnabled,
212     /// How many memory protection keys to allocate.
213     pub max_memory_protection_keys: usize,
214 }
215 
216 impl Default for PoolingInstanceAllocatorConfig {
217     fn default() -> PoolingInstanceAllocatorConfig {
218         PoolingInstanceAllocatorConfig {
219             max_unused_warm_slots: 100,
220             decommit_batch_size: 1,
221             stack_size: 2 << 20,
222             limits: InstanceLimits::default(),
223             async_stack_zeroing: false,
224             async_stack_keep_resident: 0,
225             linear_memory_keep_resident: 0,
226             table_keep_resident: 0,
227             memory_protection_keys: MpkEnabled::Disable,
228             max_memory_protection_keys: 16,
229         }
230     }
231 }
232 
233 /// An error returned when the pooling allocator cannot allocate a table,
234 /// memory, etc... because the maximum number of concurrent allocations for that
235 /// entity has been reached.
236 #[derive(Debug)]
237 pub struct PoolConcurrencyLimitError {
238     limit: usize,
239     kind: Cow<'static, str>,
240 }
241 
242 impl std::error::Error for PoolConcurrencyLimitError {}
243 
244 impl Display for PoolConcurrencyLimitError {
245     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246         let limit = self.limit;
247         let kind = &self.kind;
248         write!(f, "maximum concurrent limit of {limit} for {kind} reached")
249     }
250 }
251 
252 impl PoolConcurrencyLimitError {
253     fn new(limit: usize, kind: impl Into<Cow<'static, str>>) -> Self {
254         Self {
255             limit,
256             kind: kind.into(),
257         }
258     }
259 }
260 
261 /// Implements the pooling instance allocator.
262 ///
263 /// This allocator internally maintains pools of instances, memories, tables,
264 /// and stacks.
265 ///
266 /// Note: the resource pools are manually dropped so that the fault handler
267 /// terminates correctly.
268 #[derive(Debug)]
269 pub struct PoolingInstanceAllocator {
270     decommit_batch_size: usize,
271     limits: InstanceLimits,
272 
273     // The number of live core module and component instances at any given
274     // time. Note that this can temporarily go over the configured limit. This
275     // doesn't mean we have actually overshot, but that we attempted to allocate
276     // a new instance and incremented the counter, we've seen (or are about to
277     // see) that the counter is beyond the configured threshold, and are going
278     // to decrement the counter and return an error but haven't done so yet. See
279     // the increment trait methods for more details.
280     live_core_instances: AtomicU64,
281     live_component_instances: AtomicU64,
282 
283     decommit_queue: Mutex<DecommitQueue>,
284     memories: MemoryPool,
285     tables: TablePool,
286 
287     #[cfg(feature = "gc")]
288     gc_heaps: GcHeapPool,
289 
290     #[cfg(feature = "async")]
291     stacks: StackPool,
292 }
293 
294 #[cfg(debug_assertions)]
295 impl Drop for PoolingInstanceAllocator {
296     fn drop(&mut self) {
297         // NB: when cfg(not(debug_assertions)) it is okay that we don't flush
298         // the queue, as the sub-pools will unmap those ranges anyways, so
299         // there's no point in decommitting them. But we do need to flush the
300         // queue when debug assertions are enabled to make sure that all
301         // entities get returned to their associated sub-pools and we can
302         // differentiate between a leaking slot and an enqueued-for-decommit
303         // slot.
304         let queue = self.decommit_queue.lock().unwrap();
305         self.flush_decommit_queue(queue);
306 
307         debug_assert_eq!(self.live_component_instances.load(Ordering::Acquire), 0);
308         debug_assert_eq!(self.live_core_instances.load(Ordering::Acquire), 0);
309 
310         debug_assert!(self.memories.is_empty());
311         debug_assert!(self.tables.is_empty());
312 
313         #[cfg(feature = "gc")]
314         debug_assert!(self.gc_heaps.is_empty());
315 
316         #[cfg(feature = "async")]
317         debug_assert!(self.stacks.is_empty());
318     }
319 }
320 
321 impl PoolingInstanceAllocator {
322     /// Creates a new pooling instance allocator with the given strategy and limits.
323     pub fn new(config: &PoolingInstanceAllocatorConfig, tunables: &Tunables) -> Result<Self> {
324         Ok(Self {
325             decommit_batch_size: config.decommit_batch_size,
326             limits: config.limits,
327             live_component_instances: AtomicU64::new(0),
328             live_core_instances: AtomicU64::new(0),
329             decommit_queue: Mutex::new(DecommitQueue::default()),
330             memories: MemoryPool::new(config, tunables)?,
331             tables: TablePool::new(config)?,
332             #[cfg(feature = "gc")]
333             gc_heaps: GcHeapPool::new(config)?,
334             #[cfg(feature = "async")]
335             stacks: StackPool::new(config)?,
336         })
337     }
338 
339     fn core_instance_size(&self) -> usize {
340         round_up_to_pow2(self.limits.core_instance_size, mem::align_of::<Instance>())
341     }
342 
343     fn validate_table_plans(&self, module: &Module) -> Result<()> {
344         self.tables.validate(module)
345     }
346 
347     fn validate_memory_plans(&self, module: &Module) -> Result<()> {
348         self.memories.validate(module)
349     }
350 
351     fn validate_core_instance_size(&self, offsets: &VMOffsets<HostPtr>) -> Result<()> {
352         let layout = Instance::alloc_layout(offsets);
353         if layout.size() <= self.core_instance_size() {
354             return Ok(());
355         }
356 
357         // If this `module` exceeds the allocation size allotted to it then an
358         // error will be reported here. The error of "required N bytes but
359         // cannot allocate that" is pretty opaque, however, because it's not
360         // clear what the breakdown of the N bytes are and what to optimize
361         // next. To help provide a better error message here some fancy-ish
362         // logic is done here to report the breakdown of the byte request into
363         // the largest portions and where it's coming from.
364         let mut message = format!(
365             "instance allocation for this module \
366              requires {} bytes which exceeds the configured maximum \
367              of {} bytes; breakdown of allocation requirement:\n\n",
368             layout.size(),
369             self.core_instance_size(),
370         );
371 
372         let mut remaining = layout.size();
373         let mut push = |name: &str, bytes: usize| {
374             assert!(remaining >= bytes);
375             remaining -= bytes;
376 
377             // If the `name` region is more than 5% of the allocation request
378             // then report it here, otherwise ignore it. We have less than 20
379             // fields so we're guaranteed that something should be reported, and
380             // otherwise it's not particularly interesting to learn about 5
381             // different fields that are all 8 or 0 bytes. Only try to report
382             // the "major" sources of bytes here.
383             if bytes > layout.size() / 20 {
384                 message.push_str(&format!(
385                     " * {:.02}% - {} bytes - {}\n",
386                     ((bytes as f32) / (layout.size() as f32)) * 100.0,
387                     bytes,
388                     name,
389                 ));
390             }
391         };
392 
393         // The `Instance` itself requires some size allocated to it.
394         push("instance state management", mem::size_of::<Instance>());
395 
396         // Afterwards the `VMContext`'s regions are why we're requesting bytes,
397         // so ask it for descriptions on each region's byte size.
398         for (desc, size) in offsets.region_sizes() {
399             push(desc, size as usize);
400         }
401 
402         // double-check we accounted for all the bytes
403         assert_eq!(remaining, 0);
404 
405         bail!("{}", message)
406     }
407 
408     #[cfg(feature = "component-model")]
409     fn validate_component_instance_size(
410         &self,
411         offsets: &VMComponentOffsets<HostPtr>,
412     ) -> Result<()> {
413         if usize::try_from(offsets.size_of_vmctx()).unwrap() <= self.limits.component_instance_size
414         {
415             return Ok(());
416         }
417 
418         // TODO: Add context with detailed accounting of what makes up all the
419         // `VMComponentContext`'s space like we do for module instances.
420         bail!(
421             "instance allocation for this component requires {} bytes of `VMComponentContext` \
422              space which exceeds the configured maximum of {} bytes",
423             offsets.size_of_vmctx(),
424             self.limits.component_instance_size
425         )
426     }
427 
428     fn flush_decommit_queue(&self, mut locked_queue: MutexGuard<'_, DecommitQueue>) -> bool {
429         // Take the queue out of the mutex and drop the lock, to minimize
430         // contention.
431         let queue = mem::take(&mut *locked_queue);
432         drop(locked_queue);
433         queue.flush(self)
434     }
435 
436     /// Execute `f` and if it returns `Err(PoolConcurrencyLimitError)`, then try
437     /// flushing the decommit queue. If flushing the queue freed up slots, then
438     /// try running `f` again.
439     fn with_flush_and_retry<T>(&self, mut f: impl FnMut() -> Result<T>) -> Result<T> {
440         f().or_else(|e| {
441             if e.is::<PoolConcurrencyLimitError>() {
442                 let queue = self.decommit_queue.lock().unwrap();
443                 if self.flush_decommit_queue(queue) {
444                     return f();
445                 }
446             }
447 
448             Err(e)
449         })
450     }
451 
452     fn merge_or_flush(&self, mut local_queue: DecommitQueue) {
453         match local_queue.raw_len() {
454             // If we didn't enqueue any regions for decommit, then we must have
455             // either memset the whole entity or eagerly remapped it to zero
456             // because we don't have linux's `madvise(DONTNEED)` semantics. In
457             // either case, the entity slot is ready for reuse immediately.
458             0 => {
459                 local_queue.flush(self);
460             }
461 
462             // We enqueued at least our batch size of regions for decommit, so
463             // flush the local queue immediately. Don't bother inspecting (or
464             // locking!) the shared queue.
465             n if n >= self.decommit_batch_size => {
466                 local_queue.flush(self);
467             }
468 
469             // If we enqueued some regions for decommit, but did not reach our
470             // batch size, so we don't want to flush it yet, then merge the
471             // local queue into the shared queue.
472             n => {
473                 debug_assert!(n < self.decommit_batch_size);
474                 let mut shared_queue = self.decommit_queue.lock().unwrap();
475                 shared_queue.append(&mut local_queue);
476                 // And if the shared queue now has at least as many regions
477                 // enqueued for decommit as our batch size, then we can flush
478                 // it.
479                 if shared_queue.raw_len() >= self.decommit_batch_size {
480                     self.flush_decommit_queue(shared_queue);
481                 }
482             }
483         }
484     }
485 }
486 
487 unsafe impl InstanceAllocatorImpl for PoolingInstanceAllocator {
488     #[cfg(feature = "component-model")]
489     fn validate_component_impl<'a>(
490         &self,
491         component: &Component,
492         offsets: &VMComponentOffsets<HostPtr>,
493         get_module: &'a dyn Fn(StaticModuleIndex) -> &'a Module,
494     ) -> Result<()> {
495         self.validate_component_instance_size(offsets)?;
496 
497         let mut num_core_instances = 0;
498         let mut num_memories = 0;
499         let mut num_tables = 0;
500         for init in &component.initializers {
501             use wasmtime_environ::component::GlobalInitializer::*;
502             use wasmtime_environ::component::InstantiateModule;
503             match init {
504                 InstantiateModule(InstantiateModule::Import(_, _)) => {
505                     num_core_instances += 1;
506                     // Can't statically account for the total vmctx size, number
507                     // of memories, and number of tables in this component.
508                 }
509                 InstantiateModule(InstantiateModule::Static(static_module_index, _)) => {
510                     let module = get_module(*static_module_index);
511                     let offsets = VMOffsets::new(HostPtr, &module);
512                     self.validate_module_impl(module, &offsets)?;
513                     num_core_instances += 1;
514                     num_memories += module.memory_plans.len() - module.num_imported_memories;
515                     num_tables += module.table_plans.len() - module.num_imported_tables;
516                 }
517                 LowerImport { .. }
518                 | ExtractMemory(_)
519                 | ExtractRealloc(_)
520                 | ExtractPostReturn(_)
521                 | Resource(_) => {}
522             }
523         }
524 
525         if num_core_instances
526             > usize::try_from(self.limits.max_core_instances_per_component).unwrap()
527         {
528             bail!(
529                 "The component transitively contains {num_core_instances} core module instances, \
530                  which exceeds the configured maximum of {}",
531                 self.limits.max_core_instances_per_component
532             );
533         }
534 
535         if num_memories > usize::try_from(self.limits.max_memories_per_component).unwrap() {
536             bail!(
537                 "The component transitively contains {num_memories} Wasm linear memories, which \
538                  exceeds the configured maximum of {}",
539                 self.limits.max_memories_per_component
540             );
541         }
542 
543         if num_tables > usize::try_from(self.limits.max_tables_per_component).unwrap() {
544             bail!(
545                 "The component transitively contains {num_tables} tables, which exceeds the \
546                  configured maximum of {}",
547                 self.limits.max_tables_per_component
548             );
549         }
550 
551         Ok(())
552     }
553 
554     fn validate_module_impl(&self, module: &Module, offsets: &VMOffsets<HostPtr>) -> Result<()> {
555         self.validate_memory_plans(module)?;
556         self.validate_table_plans(module)?;
557         self.validate_core_instance_size(offsets)?;
558         Ok(())
559     }
560 
561     fn increment_component_instance_count(&self) -> Result<()> {
562         let old_count = self.live_component_instances.fetch_add(1, Ordering::AcqRel);
563         if old_count >= u64::from(self.limits.total_component_instances) {
564             self.decrement_component_instance_count();
565             return Err(PoolConcurrencyLimitError::new(
566                 usize::try_from(self.limits.total_component_instances).unwrap(),
567                 "component instances",
568             )
569             .into());
570         }
571         Ok(())
572     }
573 
574     fn decrement_component_instance_count(&self) {
575         self.live_component_instances.fetch_sub(1, Ordering::AcqRel);
576     }
577 
578     fn increment_core_instance_count(&self) -> Result<()> {
579         let old_count = self.live_core_instances.fetch_add(1, Ordering::AcqRel);
580         if old_count >= u64::from(self.limits.total_core_instances) {
581             self.decrement_core_instance_count();
582             return Err(PoolConcurrencyLimitError::new(
583                 usize::try_from(self.limits.total_core_instances).unwrap(),
584                 "core instances",
585             )
586             .into());
587         }
588         Ok(())
589     }
590 
591     fn decrement_core_instance_count(&self) {
592         self.live_core_instances.fetch_sub(1, Ordering::AcqRel);
593     }
594 
595     unsafe fn allocate_memory(
596         &self,
597         request: &mut InstanceAllocationRequest,
598         memory_plan: &MemoryPlan,
599         memory_index: DefinedMemoryIndex,
600     ) -> Result<(MemoryAllocationIndex, Memory)> {
601         self.with_flush_and_retry(|| self.memories.allocate(request, memory_plan, memory_index))
602     }
603 
604     unsafe fn deallocate_memory(
605         &self,
606         _memory_index: DefinedMemoryIndex,
607         allocation_index: MemoryAllocationIndex,
608         memory: Memory,
609     ) {
610         // Reset the image slot. If there is any error clearing the
611         // image, just drop it here, and let the drop handler for the
612         // slot unmap in a way that retains the address space
613         // reservation.
614         let mut image = memory.unwrap_static_image();
615         let mut queue = DecommitQueue::default();
616         image
617             .clear_and_remain_ready(self.memories.keep_resident, |ptr, len| {
618                 queue.push_raw(ptr, len);
619             })
620             .expect("failed to reset memory image");
621         queue.push_memory(allocation_index, image);
622         self.merge_or_flush(queue);
623     }
624 
625     unsafe fn allocate_table(
626         &self,
627         request: &mut InstanceAllocationRequest,
628         table_plan: &TablePlan,
629         _table_index: DefinedTableIndex,
630     ) -> Result<(super::TableAllocationIndex, Table)> {
631         self.with_flush_and_retry(|| self.tables.allocate(request, table_plan))
632     }
633 
634     unsafe fn deallocate_table(
635         &self,
636         _table_index: DefinedTableIndex,
637         allocation_index: TableAllocationIndex,
638         mut table: Table,
639     ) {
640         let mut queue = DecommitQueue::default();
641         self.tables
642             .reset_table_pages_to_zero(allocation_index, &mut table, |ptr, len| {
643                 queue.push_raw(ptr, len);
644             });
645         queue.push_table(allocation_index, table);
646         self.merge_or_flush(queue);
647     }
648 
649     #[cfg(feature = "async")]
650     fn allocate_fiber_stack(&self) -> Result<wasmtime_fiber::FiberStack> {
651         self.with_flush_and_retry(|| self.stacks.allocate())
652     }
653 
654     #[cfg(feature = "async")]
655     unsafe fn deallocate_fiber_stack(&self, mut stack: wasmtime_fiber::FiberStack) {
656         let mut queue = DecommitQueue::default();
657         self.stacks
658             .zero_stack(&mut stack, |ptr, len| queue.push_raw(ptr, len));
659         queue.push_stack(stack);
660         self.merge_or_flush(queue);
661     }
662 
663     fn purge_module(&self, module: CompiledModuleId) {
664         self.memories.purge_module(module);
665     }
666 
667     fn next_available_pkey(&self) -> Option<ProtectionKey> {
668         self.memories.next_available_pkey()
669     }
670 
671     fn restrict_to_pkey(&self, pkey: ProtectionKey) {
672         mpk::allow(ProtectionMask::zero().or(pkey));
673     }
674 
675     fn allow_all_pkeys(&self) {
676         mpk::allow(ProtectionMask::all());
677     }
678 
679     #[cfg(feature = "gc")]
680     fn allocate_gc_heap(
681         &self,
682         gc_runtime: &dyn GcRuntime,
683     ) -> Result<(GcHeapAllocationIndex, Box<dyn GcHeap>)> {
684         self.gc_heaps.allocate(gc_runtime)
685     }
686 
687     #[cfg(feature = "gc")]
688     fn deallocate_gc_heap(
689         &self,
690         allocation_index: GcHeapAllocationIndex,
691         gc_heap: Box<dyn GcHeap>,
692     ) {
693         self.gc_heaps.deallocate(allocation_index, gc_heap);
694     }
695 }
696 
697 #[cfg(test)]
698 mod test {
699     use super::*;
700 
701     #[test]
702     fn test_pooling_allocator_with_memory_pages_exceeded() {
703         let config = PoolingInstanceAllocatorConfig {
704             limits: InstanceLimits {
705                 total_memories: 1,
706                 max_memory_size: 0x100010000,
707                 ..Default::default()
708             },
709             ..PoolingInstanceAllocatorConfig::default()
710         };
711         assert_eq!(
712             PoolingInstanceAllocator::new(
713                 &config,
714                 &Tunables {
715                     static_memory_reservation: 0x10000,
716                     ..Tunables::default_host()
717                 },
718             )
719             .map_err(|e| e.to_string())
720             .expect_err("expected a failure constructing instance allocator"),
721             "maximum memory size of 0x100010000 bytes exceeds the configured \
722              static memory reservation of 0x10000 bytes"
723         );
724     }
725 
726     #[cfg(all(unix, target_pointer_width = "64", feature = "async", not(miri)))]
727     #[test]
728     fn test_stack_zeroed() -> Result<()> {
729         let config = PoolingInstanceAllocatorConfig {
730             max_unused_warm_slots: 0,
731             limits: InstanceLimits {
732                 total_stacks: 1,
733                 total_memories: 0,
734                 total_tables: 0,
735                 ..Default::default()
736             },
737             stack_size: 128,
738             async_stack_zeroing: true,
739             ..PoolingInstanceAllocatorConfig::default()
740         };
741         let allocator = PoolingInstanceAllocator::new(&config, &Tunables::default_host())?;
742 
743         unsafe {
744             for _ in 0..255 {
745                 let stack = allocator.allocate_fiber_stack()?;
746 
747                 // The stack pointer is at the top, so decrement it first
748                 let addr = stack.top().unwrap().sub(1);
749 
750                 assert_eq!(*addr, 0);
751                 *addr = 1;
752 
753                 allocator.deallocate_fiber_stack(stack);
754             }
755         }
756 
757         Ok(())
758     }
759 
760     #[cfg(all(unix, target_pointer_width = "64", feature = "async", not(miri)))]
761     #[test]
762     fn test_stack_unzeroed() -> Result<()> {
763         let config = PoolingInstanceAllocatorConfig {
764             max_unused_warm_slots: 0,
765             limits: InstanceLimits {
766                 total_stacks: 1,
767                 total_memories: 0,
768                 total_tables: 0,
769                 ..Default::default()
770             },
771             stack_size: 128,
772             async_stack_zeroing: false,
773             ..PoolingInstanceAllocatorConfig::default()
774         };
775         let allocator = PoolingInstanceAllocator::new(&config, &Tunables::default_host())?;
776 
777         unsafe {
778             for i in 0..255 {
779                 let stack = allocator.allocate_fiber_stack()?;
780 
781                 // The stack pointer is at the top, so decrement it first
782                 let addr = stack.top().unwrap().sub(1);
783 
784                 assert_eq!(*addr, i);
785                 *addr = i + 1;
786 
787                 allocator.deallocate_fiber_stack(stack);
788             }
789         }
790 
791         Ok(())
792     }
793 }
794