Skip to main content

wasmtime/
config.rs

1use crate::Engine;
2use crate::prelude::*;
3use alloc::sync::Arc;
4use bitflags::Flags;
5use core::fmt;
6use core::num::{NonZeroU32, NonZeroUsize};
7use core::str::FromStr;
8#[cfg(any(feature = "cranelift", feature = "winch"))]
9use std::path::Path;
10pub use wasmparser::WasmFeatures;
11#[cfg(any(feature = "cranelift", feature = "winch"))]
12use wasmtime_environ::FlagValue;
13use wasmtime_environ::{ConfigTunables, OperatorCost, OperatorCostStrategy, TripleExt, Tunables};
14
15#[cfg(feature = "runtime")]
16use crate::memory::MemoryCreator;
17#[cfg(feature = "runtime")]
18use crate::profiling_agent::{self, ProfilingAgent};
19#[cfg(feature = "runtime")]
20use crate::runtime::vm::{
21    GcRuntime, InstanceAllocator, OnDemandInstanceAllocator, RuntimeMemoryCreator,
22};
23#[cfg(feature = "runtime")]
24use crate::trampoline::MemoryCreatorProxy;
25
26#[cfg(feature = "async")]
27use crate::stack::{StackCreator, StackCreatorProxy};
28#[cfg(feature = "async")]
29use wasmtime_fiber::RuntimeFiberStackCreator;
30
31#[cfg(feature = "runtime")]
32pub use crate::runtime::code_memory::CustomCodeMemory;
33#[cfg(feature = "cache")]
34pub use wasmtime_cache::{Cache, CacheConfig};
35#[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
36pub use wasmtime_environ::CacheStore;
37pub use wasmtime_environ::Inlining;
38
39pub(crate) const DEFAULT_WASM_BACKTRACE_MAX_FRAMES: NonZeroUsize = NonZeroUsize::new(20).unwrap();
40
41/// Represents the module instance allocation strategy to use.
42#[derive(Clone)]
43#[non_exhaustive]
44pub enum InstanceAllocationStrategy {
45    /// The on-demand instance allocation strategy.
46    ///
47    /// Resources related to a module instance are allocated at instantiation time and
48    /// immediately deallocated when the `Store` referencing the instance is dropped.
49    ///
50    /// This is the default allocation strategy for Wasmtime.
51    OnDemand,
52    /// The pooling instance allocation strategy.
53    ///
54    /// A pool of resources is created in advance and module instantiation reuses resources
55    /// from the pool. Resources are returned to the pool when the `Store` referencing the instance
56    /// is dropped.
57    ///
58    /// When GC is enabled, the pooling allocator requires that the GC heap
59    /// configuration matches the linear memory configuration (i.e.,
60    /// `gc_heap_reservation` must equal `memory_reservation`, etc.). By
61    /// default, if no `gc_heap_*` tunables are explicitly configured, they
62    /// automatically inherit the `memory_*` values.
63    #[cfg(feature = "pooling-allocator")]
64    Pooling(PoolingAllocationConfig),
65}
66
67impl InstanceAllocationStrategy {
68    /// The default pooling instance allocation strategy.
69    #[cfg(feature = "pooling-allocator")]
70    pub fn pooling() -> Self {
71        Self::Pooling(Default::default())
72    }
73}
74
75impl Default for InstanceAllocationStrategy {
76    fn default() -> Self {
77        Self::OnDemand
78    }
79}
80
81#[cfg(feature = "pooling-allocator")]
82impl From<PoolingAllocationConfig> for InstanceAllocationStrategy {
83    fn from(cfg: PoolingAllocationConfig) -> InstanceAllocationStrategy {
84        InstanceAllocationStrategy::Pooling(cfg)
85    }
86}
87
88#[derive(Clone)]
89/// Configure the strategy used for versioning in serializing and deserializing [`crate::Module`].
90pub enum ModuleVersionStrategy {
91    /// Use the wasmtime crate's Cargo package version.
92    WasmtimeVersion,
93    /// Use a custom version string. Must be at most 255 bytes.
94    Custom(String),
95    /// Emit no version string in serialization, and accept all version strings in deserialization.
96    None,
97}
98
99impl Default for ModuleVersionStrategy {
100    fn default() -> Self {
101        ModuleVersionStrategy::WasmtimeVersion
102    }
103}
104
105impl core::hash::Hash for ModuleVersionStrategy {
106    fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
107        match self {
108            Self::WasmtimeVersion => env!("CARGO_PKG_VERSION").hash(hasher),
109            Self::Custom(s) => s.hash(hasher),
110            Self::None => {}
111        };
112    }
113}
114
115impl ModuleVersionStrategy {
116    /// Get the string-encoding version of the module.
117    pub fn as_str(&self) -> &str {
118        match &self {
119            Self::WasmtimeVersion => env!("CARGO_PKG_VERSION_MAJOR"),
120            Self::Custom(c) => c,
121            Self::None => "",
122        }
123    }
124}
125
126/// Configuration for record/replay
127#[derive(Clone)]
128#[non_exhaustive]
129pub enum RRConfig {
130    #[cfg(feature = "rr")]
131    /// Recording on store is enabled
132    Recording,
133    #[cfg(feature = "rr")]
134    /// Replaying on store is enabled
135    Replaying,
136    /// No record/replay is enabled
137    None,
138}
139
140/// Global configuration options used to create an [`Engine`]
141/// and customize its behavior.
142///
143/// This structure exposed a builder-like interface and is primarily consumed by
144/// [`Engine::new()`].
145///
146/// The validation of `Config` is deferred until the engine is being built, thus
147/// a problematic config may cause [`Engine::new`] to fail.
148///
149/// # Defaults
150///
151/// The `Default` trait implementation and the return value from
152/// [`Config::new()`] are the same and represent the default set of
153/// configuration for an engine. The exact set of defaults will differ based on
154/// properties such as enabled Cargo features at compile time and the configured
155/// target (see [`Config::target`]). Configuration options document their
156/// default values and what the conditional value of the default is where
157/// applicable.
158#[derive(Clone)]
159pub struct Config {
160    #[cfg(any(feature = "cranelift", feature = "winch"))]
161    compiler_config: Option<CompilerConfig>,
162    target: Option<target_lexicon::Triple>,
163    #[cfg(feature = "gc")]
164    collector: Collector,
165    profiling_strategy: ProfilingStrategy,
166    tunables: ConfigTunables,
167
168    #[cfg(feature = "cache")]
169    pub(crate) cache: Option<Cache>,
170    #[cfg(feature = "runtime")]
171    pub(crate) mem_creator: Option<Arc<dyn RuntimeMemoryCreator>>,
172    #[cfg(feature = "runtime")]
173    pub(crate) custom_code_memory: Option<Arc<dyn CustomCodeMemory>>,
174    pub(crate) allocation_strategy: InstanceAllocationStrategy,
175    pub(crate) max_wasm_stack: usize,
176    /// Explicitly enabled features via `Config::wasm_*` methods. This is a
177    /// signal that the embedder specifically wants something turned on
178    /// regardless of the defaults that Wasmtime might otherwise have enabled.
179    ///
180    /// Note that this, and `disabled_features` below, start as the empty set of
181    /// features to only track explicit user requests.
182    pub(crate) enabled_features: WasmFeatures,
183    /// Same as `enabled_features`, but for those that are explicitly disabled.
184    pub(crate) disabled_features: WasmFeatures,
185    pub(crate) wasm_backtrace_details_env_used: bool,
186    pub(crate) wasm_backtrace_max_frames: Option<NonZeroUsize>,
187    pub(crate) native_unwind_info: Option<bool>,
188    pub(crate) async_stack_size: usize,
189    pub(crate) async_stack_zeroing: bool,
190    #[cfg(feature = "async")]
191    pub(crate) stack_creator: Option<Arc<dyn RuntimeFiberStackCreator>>,
192    pub(crate) module_version: ModuleVersionStrategy,
193    pub(crate) parallel_compilation: bool,
194    pub(crate) memory_guaranteed_dense_image_size: u64,
195    pub(crate) force_memory_init_memfd: bool,
196    pub(crate) wmemcheck: bool,
197    #[cfg(feature = "coredump")]
198    pub(crate) coredump_on_trap: bool,
199    pub(crate) macos_use_mach_ports: bool,
200    pub(crate) detect_host_feature: Option<fn(&str) -> Option<bool>>,
201    pub(crate) x86_float_abi_ok: Option<bool>,
202    pub(crate) shared_memory: bool,
203    pub(crate) rr_config: RRConfig,
204}
205
206/// User-provided configuration for the compiler.
207#[cfg(any(feature = "cranelift", feature = "winch"))]
208#[derive(Debug, Clone)]
209struct CompilerConfig {
210    strategy: Option<Strategy>,
211    settings: crate::hash_map::HashMap<String, (String, UserSpecified)>,
212    flags: crate::hash_map::HashMap<String, UserSpecified>,
213    #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
214    cache_store: Option<Arc<dyn CacheStore>>,
215    clif_dir: Option<std::path::PathBuf>,
216    wmemcheck: bool,
217}
218
219#[cfg(any(feature = "cranelift", feature = "winch"))]
220#[derive(Debug, Clone)]
221enum UserSpecified {
222    Yes,
223    No,
224}
225
226#[cfg(any(feature = "cranelift", feature = "winch"))]
227impl CompilerConfig {
228    fn new() -> Self {
229        Self {
230            strategy: Strategy::Auto.not_auto(),
231            settings: Default::default(),
232            flags: Default::default(),
233            #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
234            cache_store: None,
235            clif_dir: None,
236            wmemcheck: false,
237        }
238    }
239
240    /// Ensures that the key is not set or equals to the given value.
241    /// If the key is not set, it will be set to the given value.
242    ///
243    /// # Returns
244    ///
245    /// Returns true if successfully set or already had the given setting
246    /// value, or false if the setting was explicitly set to something
247    /// else previously.
248    fn ensure_setting_unset_or_given(&mut self, k: &str, v: &str) -> bool {
249        if let Some((value, _)) = self.settings.get(k) {
250            if value != v {
251                return false;
252            }
253        } else {
254            self.settings
255                .insert(k.to_string(), (v.to_string(), UserSpecified::No));
256        }
257        true
258    }
259}
260
261#[cfg(any(feature = "cranelift", feature = "winch"))]
262impl Default for CompilerConfig {
263    fn default() -> Self {
264        Self::new()
265    }
266}
267
268impl Config {
269    /// Creates a new configuration object with the default configuration
270    /// specified.
271    pub fn new() -> Self {
272        let mut ret = Self {
273            tunables: ConfigTunables::default(),
274            #[cfg(any(feature = "cranelift", feature = "winch"))]
275            compiler_config: Some(CompilerConfig::default()),
276            target: None,
277            #[cfg(feature = "gc")]
278            collector: Collector::default(),
279            #[cfg(feature = "cache")]
280            cache: None,
281            profiling_strategy: ProfilingStrategy::None,
282            #[cfg(feature = "runtime")]
283            mem_creator: None,
284            #[cfg(feature = "runtime")]
285            custom_code_memory: None,
286            allocation_strategy: InstanceAllocationStrategy::OnDemand,
287            // 512k of stack -- note that this is chosen currently to not be too
288            // big, not be too small, and be a good default for most platforms.
289            // One platform of particular note is Windows where the stack size
290            // of the main thread seems to, by default, be smaller than that of
291            // Linux and macOS. This 512k value at least lets our current test
292            // suite pass on the main thread of Windows (using `--test-threads
293            // 1` forces this), or at least it passed when this change was
294            // committed.
295            max_wasm_stack: 512 * 1024,
296            wasm_backtrace_details_env_used: false,
297            wasm_backtrace_max_frames: Some(DEFAULT_WASM_BACKTRACE_MAX_FRAMES),
298            native_unwind_info: None,
299            enabled_features: WasmFeatures::empty(),
300            disabled_features: WasmFeatures::empty(),
301            async_stack_size: 2 << 20,
302            async_stack_zeroing: false,
303            #[cfg(feature = "async")]
304            stack_creator: None,
305            module_version: ModuleVersionStrategy::default(),
306            parallel_compilation: !cfg!(miri),
307            memory_guaranteed_dense_image_size: 16 << 20,
308            force_memory_init_memfd: false,
309            wmemcheck: false,
310            #[cfg(feature = "coredump")]
311            coredump_on_trap: false,
312            macos_use_mach_ports: !cfg!(miri),
313            #[cfg(feature = "std")]
314            detect_host_feature: Some(detect_host_feature),
315            #[cfg(not(feature = "std"))]
316            detect_host_feature: None,
317            x86_float_abi_ok: None,
318            shared_memory: false,
319            rr_config: RRConfig::None,
320        };
321        ret.wasm_backtrace_details(WasmBacktraceDetails::Environment);
322        ret
323    }
324
325    #[cfg(any(feature = "cranelift", feature = "winch"))]
326    pub(crate) fn has_compiler(&self) -> bool {
327        self.compiler_config.is_some()
328    }
329
330    #[track_caller]
331    #[cfg(any(feature = "cranelift", feature = "winch"))]
332    fn compiler_config_mut(&mut self) -> &mut CompilerConfig {
333        self.compiler_config.as_mut().expect(
334            "cannot configure compiler settings for `Config`s \
335             created by `Config::without_compiler`",
336        )
337    }
338
339    /// Configure whether Wasm compilation is enabled.
340    ///
341    /// Disabling Wasm compilation will allow you to load and run
342    /// [pre-compiled][Engine::precompile_module] Wasm programs, but not
343    /// to compile and run new Wasm programs that have not already been
344    /// pre-compiled.
345    ///
346    /// Many compilation-related configuration methods will panic if compilation
347    /// has been disabled.
348    ///
349    /// Note that there are two ways to disable Wasm compilation:
350    ///
351    /// 1. Statically, by disabling the `"cranelift"` and `"winch"` cargo
352    ///    features when building Wasmtime. These builds of Wasmtime will have
353    ///    smaller code size, since they do not include any of the code to
354    ///    compile Wasm.
355    ///
356    /// 2. Dynamically, by passing `false` to this method at run-time when
357    ///    configuring Wasmtime. The Wasmtime binary will still include the code
358    ///    for compiling Wasm, it just won't be executed, so code size is larger
359    ///    than with the first approach.
360    ///
361    /// The static approach is better in most cases, however dynamically calling
362    /// `enable_compiler(false)` is useful whenever you create multiple
363    /// [`Engine`]s in the same process, some of which must be able to compile
364    /// Wasm and some of which should never do so. Tests are a common example of
365    /// such a situation, especially when there are multiple Rust binaries in
366    /// the same cargo workspace, and cargo's feature resolution enables the
367    /// `"cranelift"` or `"winch"` features across the whole workspace.
368    #[cfg(any(feature = "cranelift", feature = "winch"))]
369    pub fn enable_compiler(&mut self, enable: bool) -> &mut Self {
370        match (enable, &self.compiler_config) {
371            (true, Some(_)) | (false, None) => {}
372            (true, None) => {
373                self.compiler_config = Some(CompilerConfig::default());
374            }
375            (false, Some(_)) => {
376                self.compiler_config = None;
377            }
378        }
379        self
380    }
381
382    /// Configures the target platform of this [`Config`].
383    ///
384    /// This method is used to configure the output of compilation in an
385    /// [`Engine`]. This can be used, for example, to
386    /// cross-compile from one platform to another. By default, the host target
387    /// triple is used meaning compiled code is suitable to run on the host.
388    ///
389    /// Note that the [`Module`](crate::Module) type can only be created if the
390    /// target configured here matches the host. Otherwise if a cross-compile is
391    /// being performed where the host doesn't match the target then
392    /// [`Engine::precompile_module`] must be used instead.
393    ///
394    /// Target-specific flags (such as CPU features) will not be inferred by
395    /// default for the target when one is provided here. This means that this
396    /// can also be used, for example, with the host architecture to disable all
397    /// host-inferred feature flags. Configuring target-specific flags can be
398    /// done with [`Config::cranelift_flag_set`] and
399    /// [`Config::cranelift_flag_enable`].
400    ///
401    /// # Errors
402    ///
403    /// This method will error if the given target triple is not supported.
404    pub fn target(&mut self, target: &str) -> Result<&mut Self> {
405        self.target =
406            Some(target_lexicon::Triple::from_str(target).map_err(|e| crate::format_err!(e))?);
407
408        Ok(self)
409    }
410
411    /// Enables the incremental compilation cache in Cranelift, using the provided `CacheStore`
412    /// backend for storage.
413    ///
414    /// # Panics
415    ///
416    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
417    #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
418    pub fn enable_incremental_compilation(
419        &mut self,
420        cache_store: Arc<dyn CacheStore>,
421    ) -> Result<&mut Self> {
422        self.compiler_config_mut().cache_store = Some(cache_store);
423        Ok(self)
424    }
425
426    #[doc(hidden)]
427    #[deprecated(note = "no longer has any effect")]
428    #[cfg(feature = "async")]
429    pub fn async_support(&mut self, _enable: bool) -> &mut Self {
430        self
431    }
432
433    /// Configures whether DWARF debug information will be emitted
434    /// during compilation for a native debugger on the Wasmtime
435    /// process to consume.
436    ///
437    /// Note that the `debug-builtins` compile-time Cargo feature must also be
438    /// enabled for native debuggers such as GDB or LLDB to be able to debug
439    /// guest WebAssembly programs.
440    ///
441    /// By default this option is `false`.
442    /// **Note** Enabling this option is not compatible with the Winch compiler.
443    pub fn debug_info(&mut self, enable: bool) -> &mut Self {
444        self.tunables.debug_native = Some(enable);
445        self
446    }
447
448    /// Whether or not symbols are located in generated compiled module
449    /// artifacts.
450    ///
451    /// Wasmtime's currently representation of compiled artifacts is an ELF
452    /// file. ELF files have symbol tables and such and this option enables
453    /// whether symbols are emitted for wasm functions. This utility can be
454    /// useful when profiling wasm modules (many profilers work with
455    /// ELF-in-memory by default without futher configuration), introspection of
456    /// a `*.cwasm` (e.g. the symbol table is what `wasmtime objdump` reads), or
457    /// just general binary analysis of the result ELF file. Large wasm modules
458    /// can have large symbol tables, however, and the symbols serve no purpose
459    /// at runtime meaning that they are pure overhead for minimal module as
460    /// well. This option can be used to disable these symbols which will reduce
461    /// the debuggability of modules but will also reduce their size.
462    ///
463    /// Note that the ELF file representation is considered an implementation
464    /// detail of Wasmtime and embedders should not rely on this format.
465    /// Wasmtime may change the format of artifacts in the future.
466    ///
467    /// This option is `true` by default.
468    ///
469    /// This option is required if [`Config::debug_info`] is enabled.
470    pub fn debug_symbols(&mut self, enable: bool) -> &mut Self {
471        self.tunables.debug_symbols = Some(enable);
472        self
473    }
474
475    /// Configures whether compiled guest code will be instrumented to
476    /// provide debugging at the Wasm VM level.
477    ///
478    /// This is required in order to enable a guest-level debugging
479    /// API that can precisely examine Wasm VM state and (eventually,
480    /// once it is complete) set breakpoints and watchpoints and step
481    /// through code.
482    ///
483    /// Without this enabled, debugging can only be done via a native
484    /// debugger operating on the compiled guest code (see
485    /// [`Config::debug_info`] and is "best-effort": we may be able to
486    /// recover some Wasm locals or operand stack values, but it is
487    /// not guaranteed, even when optimizations are disabled.
488    ///
489    /// When this is enabled, additional instrumentation is inserted
490    /// that directly tracks the Wasm VM state at every step. This has
491    /// some performance impact, but allows perfect debugging
492    /// fidelity.
493    ///
494    /// Breakpoints, watchpoints, and stepping are not yet supported,
495    /// but will be added in a future version of Wasmtime.
496    ///
497    /// This enables use of the [`crate::FrameHandle`] API which is
498    /// provided by [`crate::Caller::debug_exit_frames`] or
499    /// [`crate::Store::debug_exit_frames`].
500    ///
501    /// ***Note*** Enabling this option is not compatible with the
502    /// Winch compiler.
503    #[cfg(feature = "debug")]
504    pub fn guest_debug(&mut self, enable: bool) -> &mut Self {
505        self.tunables.debug_guest = Some(enable);
506        self
507    }
508
509    /// Configures whether [`WasmBacktrace`] will be present in the context of
510    /// errors returned from Wasmtime.
511    ///
512    /// This method is deprecated in favor of
513    /// [`Config::wasm_backtrace_max_frames`]. Calling `wasm_backtrace(false)`
514    /// is equivalent to `wasm_backtrace_max_frames(None)`, and
515    /// `wasm_backtrace(true)` will leave `wasm_backtrace_max_frames` unchanged
516    /// if the value is `Some` and will otherwise restore the default `Some`
517    /// value.
518    ///
519    /// [`WasmBacktrace`]: crate::WasmBacktrace
520    #[deprecated = "use `wasm_backtrace_max_frames` instead"]
521    pub fn wasm_backtrace(&mut self, enable: bool) -> &mut Self {
522        match (enable, self.wasm_backtrace_max_frames) {
523            (false, _) => self.wasm_backtrace_max_frames = None,
524            // Wasm backtraces were disabled; enable them with the
525            // default maximum number of frames to capture.
526            (true, None) => {
527                self.wasm_backtrace_max_frames = Some(DEFAULT_WASM_BACKTRACE_MAX_FRAMES)
528            }
529            // Wasm backtraces are already enabled; keep the existing
530            // max-frames configuration.
531            (true, Some(_)) => {}
532        }
533        self
534    }
535
536    /// Configures whether backtraces in `Trap` will parse debug info in the wasm file to
537    /// have filename/line number information.
538    ///
539    /// When enabled this will causes modules to retain debugging information
540    /// found in wasm binaries. This debug information will be used when a trap
541    /// happens to symbolicate each stack frame and attempt to print a
542    /// filename/line number for each wasm frame in the stack trace.
543    ///
544    /// By default this option is `WasmBacktraceDetails::Environment`, meaning
545    /// that wasm will read `WASMTIME_BACKTRACE_DETAILS` to indicate whether
546    /// details should be parsed. Note that the `std` feature of this crate must
547    /// be active to read environment variables, otherwise this is disabled by
548    /// default.
549    pub fn wasm_backtrace_details(&mut self, enable: WasmBacktraceDetails) -> &mut Self {
550        self.wasm_backtrace_details_env_used = false;
551        self.tunables.parse_wasm_debuginfo = match enable {
552            WasmBacktraceDetails::Enable => Some(true),
553            WasmBacktraceDetails::Disable => Some(false),
554            WasmBacktraceDetails::Environment => {
555                #[cfg(feature = "std")]
556                {
557                    self.wasm_backtrace_details_env_used = true;
558                    std::env::var("WASMTIME_BACKTRACE_DETAILS")
559                        .map(|s| Some(s == "1"))
560                        .unwrap_or(Some(false))
561                }
562                #[cfg(not(feature = "std"))]
563                {
564                    Some(false)
565                }
566            }
567        };
568        self
569    }
570
571    /// Configures the maximum number of WebAssembly frames to collect in
572    /// backtraces.
573    ///
574    /// A backtrace may be collected whenever an error is returned from a host
575    /// function call through to WebAssembly or when WebAssembly itself hits a
576    /// trap condition, such as an out-of-bounds memory access. This flag
577    /// indicates, in these conditions, whether the backtrace is collected or
578    /// not and how many frames should be collected.
579    ///
580    /// Currently wasm backtraces are implemented through frame pointer walking.
581    /// This means that collecting a backtrace is expected to be a fast and
582    /// relatively cheap operation. Additionally backtrace collection is
583    /// suitable in concurrent environments since one thread capturing a
584    /// backtrace won't block other threads.
585    ///
586    /// Collected backtraces are attached via
587    /// [`Error::context`](crate::Error::context) to errors returned from host
588    /// functions. The [`WasmBacktrace`] type can be acquired via
589    /// [`Error::downcast_ref`](crate::Error::downcast_ref) to inspect the
590    /// backtrace. When this option is set to `None` then this context is never
591    /// applied to errors coming out of wasm.
592    ///
593    /// The default value is 20.
594    ///
595    /// [`WasmBacktrace`]: crate::WasmBacktrace
596    pub fn wasm_backtrace_max_frames(&mut self, limit: Option<NonZeroUsize>) -> &mut Self {
597        self.wasm_backtrace_max_frames = limit;
598        self
599    }
600
601    /// Configures whether to generate native unwind information
602    /// (e.g. `.eh_frame` on Linux).
603    ///
604    /// This configuration option only exists to help third-party stack
605    /// capturing mechanisms, such as the system's unwinder or the `backtrace`
606    /// crate, determine how to unwind through Wasm frames. It does not affect
607    /// whether Wasmtime can capture Wasm backtraces or not. The presence of
608    /// [`WasmBacktrace`] is controlled by the
609    /// [`Config::wasm_backtrace_max_frames`] option.
610    ///
611    /// Native unwind information is included:
612    /// - When targeting Windows, since the Windows ABI requires it.
613    /// - By default.
614    ///
615    /// Note that systems loading many modules may wish to disable this
616    /// configuration option instead of leaving it on-by-default. Some platforms
617    /// exhibit quadratic behavior when registering/unregistering unwinding
618    /// information which can greatly slow down the module loading/unloading
619    /// process.
620    ///
621    /// [`WasmBacktrace`]: crate::WasmBacktrace
622    pub fn native_unwind_info(&mut self, enable: bool) -> &mut Self {
623        self.native_unwind_info = Some(enable);
624        self
625    }
626
627    /// Configures whether execution of WebAssembly will "consume fuel" to
628    /// either halt or yield execution as desired.
629    ///
630    /// This can be used to deterministically prevent infinitely-executing
631    /// WebAssembly code by instrumenting generated code to consume fuel as it
632    /// executes. When fuel runs out a trap is raised, however [`Store`] can be
633    /// configured to yield execution periodically via
634    /// [`crate::Store::fuel_async_yield_interval`].
635    ///
636    /// Note that a [`Store`] starts with no fuel, so if you enable this option
637    /// you'll have to be sure to pour some fuel into [`Store`] before
638    /// executing some code.
639    ///
640    /// By default this option is `false`.
641    ///
642    /// [`Store`]: crate::Store
643    pub fn consume_fuel(&mut self, enable: bool) -> &mut Self {
644        self.tunables.consume_fuel = Some(enable);
645        self
646    }
647
648    /// Configures the fuel cost of each WebAssembly operator.
649    ///
650    /// In addition to each operator's flat cost, [`OperatorCost::variable`]
651    /// configures per-byte, per-element, and per-page costs for operators whose
652    /// work depends on a runtime operand.
653    ///
654    /// These costs apply both to operators in function bodies and to operators
655    /// in constant expressions evaluated at instantiation time, such as global
656    /// initializers and element or data segment offsets.
657    ///
658    /// This is only relevant when [`Config::consume_fuel`] is enabled.
659    pub fn operator_cost(&mut self, cost: OperatorCost) -> &mut Self {
660        self.tunables.operator_cost = Some(OperatorCostStrategy::table(cost));
661        self
662    }
663
664    /// Enables epoch-based interruption.
665    ///
666    /// When executing code in async mode, we sometimes want to
667    /// implement a form of cooperative timeslicing: long-running Wasm
668    /// guest code should periodically yield to the executor
669    /// loop. This yielding could be implemented by using "fuel" (see
670    /// [`consume_fuel`](Config::consume_fuel)). However, fuel
671    /// instrumentation is somewhat expensive: it modifies the
672    /// compiled form of the Wasm code so that it maintains a precise
673    /// instruction count, frequently checking this count against the
674    /// remaining fuel. If one does not need this precise count or
675    /// deterministic interruptions, and only needs a periodic
676    /// interrupt of some form, then It would be better to have a more
677    /// lightweight mechanism.
678    ///
679    /// Epoch-based interruption is that mechanism. There is a global
680    /// "epoch", which is a counter that divides time into arbitrary
681    /// periods (or epochs). This counter lives on the
682    /// [`Engine`] and can be incremented by calling
683    /// [`Engine::increment_epoch`].
684    /// Epoch-based instrumentation works by setting a "deadline
685    /// epoch". The compiled code knows the deadline, and at certain
686    /// points, checks the current epoch against that deadline. It
687    /// will yield if the deadline has been reached.
688    ///
689    /// The idea is that checking an infrequently-changing counter is
690    /// cheaper than counting and frequently storing a precise metric
691    /// (instructions executed) locally. The interruptions are not
692    /// deterministic, but if the embedder increments the epoch in a
693    /// periodic way (say, every regular timer tick by a thread or
694    /// signal handler), then we can ensure that all async code will
695    /// yield to the executor within a bounded time.
696    ///
697    /// The [`Store`](crate::Store) tracks the deadline, and controls
698    /// what happens when the deadline is reached during
699    /// execution. Several behaviors are possible:
700    ///
701    /// - Trap if code is executing when the epoch deadline is
702    ///   met. See
703    ///   [`Store::epoch_deadline_trap`](crate::Store::epoch_deadline_trap).
704    ///
705    /// - Call an arbitrary function. This function may chose to trap or
706    ///   increment the epoch. See
707    ///   [`Store::epoch_deadline_callback`](crate::Store::epoch_deadline_callback).
708    ///
709    /// - Yield to the executor loop, then resume when the future is
710    ///   next polled. See
711    ///   [`Store::epoch_deadline_async_yield_and_update`](crate::Store::epoch_deadline_async_yield_and_update).
712    ///
713    /// Trapping is the default. The yielding behaviour may be used for
714    /// the timeslicing behavior described above.
715    ///
716    /// This feature is available with or without async support.
717    /// However, without async support, the timeslicing behaviour is
718    /// not available. This means epoch-based interruption can only
719    /// serve as a simple external-interruption mechanism.
720    ///
721    /// An initial deadline must be set before executing code by calling
722    /// [`Store::set_epoch_deadline`](crate::Store::set_epoch_deadline). If this
723    /// deadline is not configured then wasm will immediately trap.
724    ///
725    /// ## Interaction with blocking host calls
726    ///
727    /// Epochs (and fuel) do not assist in handling WebAssembly code blocked in
728    /// a call to the host. For example if the WebAssembly function calls
729    /// `wasi:io/poll.poll` to sleep epochs will not assist in waking this up or
730    /// timing it out. Epochs intentionally only affect running WebAssembly code
731    /// itself and it's left to the embedder to determine how best to wake up
732    /// indefinitely blocking code in the host.
733    ///
734    /// The typical solution for this, however, is to use the `async` variant of
735    /// WASI host functions. This models computation as a Rust `Future` which
736    /// means that when blocking happens the future is only suspended and
737    /// control yields back to the main event loop. This gives the embedder the
738    /// opportunity to use `tokio::time::timeout` for example on a wasm
739    /// computation and have the desired effect of cancelling a blocking
740    /// operation when a timeout expires.
741    ///
742    /// ## Limitations with malicious guests
743    ///
744    /// Epochs are designed to handle malicious WebAssembly guests -- the
745    /// deadline check cannot be avoided by WebAssembly code. It is safe to use
746    /// epoch deadlines to limit the execution time of untrusted code.
747    ///
748    /// Note, though, that a current limitation to this is that
749    /// bulk-data-transfer instructions, such as `memory.copy`, only check the
750    /// epoch once at the start of the operation. These operations can take a
751    /// variable amount of time to complete based on how many bytes are being
752    /// copied. This means that the maximal time slice a guest might take is
753    /// the maximum of the epoch interval and the largest
754    /// memory-copy-style-instruction executed. The size of a copy is bounded
755    /// on the size of linear memory or GC heap size. In the limit, however, a
756    /// guest using a 64-bit linear memory with a 128GiB size could issue a
757    /// 128GiB `memory.copy` which would have no preemption within the
758    /// instruction itself. Hosts which need strict time limits for guests right
759    /// now are recommended to ensure that the store's allocated heap size
760    /// (linear memory + GC heap) are bounded with a
761    /// [`ResourceLimiter`](crate::ResourceLimiter).
762    ///
763    /// ## When to use fuel vs. epochs
764    ///
765    /// In general, epoch-based interruption results in faster
766    /// execution. This difference is sometimes significant: in some
767    /// measurements, up to 2-3x. This is because epoch-based
768    /// interruption does less work: it only watches for a global
769    /// rarely-changing counter to increment, rather than keeping a
770    /// local frequently-changing counter and comparing it to a
771    /// deadline.
772    ///
773    /// Fuel, in contrast, should be used when *deterministic*
774    /// yielding or trapping is needed. For example, if it is required
775    /// that the same function call with the same starting state will
776    /// always either complete or trap with an out-of-fuel error,
777    /// deterministically, then fuel with a fixed bound should be
778    /// used.
779    ///
780    /// **Note** Enabling this option is not compatible with the Winch compiler.
781    ///
782    /// # See Also
783    ///
784    /// - [`Store::set_epoch_deadline`](crate::Store::set_epoch_deadline)
785    /// - [`Store::epoch_deadline_trap`](crate::Store::epoch_deadline_trap)
786    /// - [`Store::epoch_deadline_callback`](crate::Store::epoch_deadline_callback)
787    /// - [`Store::epoch_deadline_async_yield_and_update`](crate::Store::epoch_deadline_async_yield_and_update)
788    pub fn epoch_interruption(&mut self, enable: bool) -> &mut Self {
789        self.tunables.epoch_interruption = Some(enable);
790        self
791    }
792
793    /// XXX: For internal fuzzing and debugging use only!
794    #[doc(hidden)]
795    pub fn gc_zeal_alloc_counter(&mut self, counter: Option<NonZeroU32>) -> Result<&mut Self> {
796        #[cfg(not(gc_zeal))]
797        {
798            let _ = counter;
799            bail!(
800                "cannot set `gc_zeal_alloc_counter` because Wasmtime was not built with `cfg(gc_zeal)`"
801            );
802        }
803
804        #[cfg(gc_zeal)]
805        {
806            self.tunables.gc_zeal_alloc_counter = Some(counter);
807            Ok(self)
808        }
809    }
810
811    /// Configures the maximum amount of stack space available for
812    /// executing WebAssembly code.
813    ///
814    /// WebAssembly has well-defined semantics on stack overflow. This is
815    /// intended to be a knob which can help configure how much stack space
816    /// wasm execution is allowed to consume. Note that the number here is not
817    /// super-precise, but rather wasm will take at most "pretty close to this
818    /// much" stack space.
819    ///
820    /// If a wasm call (or series of nested wasm calls) take more stack space
821    /// than the `size` specified then a stack overflow trap will be raised.
822    ///
823    /// Caveat: this knob only limits the stack space consumed by wasm code.
824    /// More importantly, it does not ensure that this much stack space is
825    /// available on the calling thread stack. Exhausting the thread stack
826    /// typically leads to an **abort** of the process.
827    ///
828    /// Here are some examples of how that could happen:
829    ///
830    /// - Let's assume this option is set to 2 MiB and then a thread that has
831    ///   a stack with 512 KiB left.
832    ///
833    ///   If wasm code consumes more than 512 KiB then the process will be aborted.
834    ///
835    /// - Assuming the same conditions, but this time wasm code does not consume
836    ///   any stack but calls into a host function. The host function consumes
837    ///   more than 512 KiB of stack space. The process will be aborted.
838    ///
839    /// There's another gotcha related to recursive calling into wasm: the stack
840    /// space consumed by a host function is counted towards this limit. The
841    /// host functions are not prevented from consuming more than this limit.
842    /// However, if the host function that used more than this limit and called
843    /// back into wasm, then the execution will trap immediately because of
844    /// stack overflow.
845    ///
846    /// When the `async` feature is enabled, this value cannot exceed the
847    /// `async_stack_size` option. Be careful not to set this value too close
848    /// to `async_stack_size` as doing so may limit how much stack space
849    /// is available for host functions.
850    ///
851    /// By default this option is 512 KiB.
852    ///
853    /// # Errors
854    ///
855    /// The [`Engine::new`] method will fail if the `size` specified here is
856    /// either 0 or larger than the [`Config::async_stack_size`] configuration.
857    pub fn max_wasm_stack(&mut self, size: usize) -> &mut Self {
858        self.max_wasm_stack = size;
859        self
860    }
861
862    /// Configures the size of the stacks used for asynchronous execution.
863    ///
864    /// This setting configures the size of the stacks that are allocated for
865    /// asynchronous execution. The value cannot be less than `max_wasm_stack`.
866    ///
867    /// The amount of stack space guaranteed for host functions is
868    /// `async_stack_size - max_wasm_stack`, so take care not to set these two values
869    /// close to one another; doing so may cause host functions to overflow the
870    /// stack and abort the process.
871    ///
872    /// By default this option is 2 MiB.
873    ///
874    /// # Errors
875    ///
876    /// The [`Engine::new`] method will fail if the value for this option is
877    /// smaller than the [`Config::max_wasm_stack`] option.
878    pub fn async_stack_size(&mut self, size: usize) -> &mut Self {
879        self.async_stack_size = size;
880        self
881    }
882
883    /// Configures whether or not stacks used for async futures are zeroed
884    /// before (re)use.
885    ///
886    /// When the [`call_async`] variant of calling WebAssembly is used
887    /// then Wasmtime will create a separate runtime execution stack for each
888    /// future produced by [`call_async`]. By default upon allocation, depending
889    /// on the platform, these stacks might be filled with uninitialized
890    /// memory. This is safe and correct because, modulo bugs in Wasmtime,
891    /// compiled Wasm code will never read from a stack slot before it
892    /// initializes the stack slot.
893    ///
894    /// However, as a defense-in-depth mechanism, you may configure Wasmtime to
895    /// ensure that these stacks are zeroed before they are used. Notably, if
896    /// you are using the pooling allocator, stacks can be pooled and reused
897    /// across different Wasm guests; ensuring that stacks are zeroed can
898    /// prevent data leakage between Wasm guests even in the face of potential
899    /// read-of-stack-slot-before-initialization bugs in Wasmtime's compiler.
900    ///
901    /// Stack zeroing can be a costly operation in highly concurrent
902    /// environments due to modifications of the virtual address space requiring
903    /// process-wide synchronization. It can also be costly in `no-std`
904    /// environments that must manually zero memory, and cannot rely on an OS
905    /// and virtual memory to provide zeroed pages.
906    ///
907    /// This option defaults to `false`.
908    ///
909    /// [`call_async`]: crate::TypedFunc::call_async
910    pub fn async_stack_zeroing(&mut self, enable: bool) -> &mut Self {
911        self.async_stack_zeroing = enable;
912        self
913    }
914
915    /// Explicitly enables (and un-disables) a given set of [`WasmFeatures`].
916    ///
917    /// Note: this is a low-level method that does not necessarily imply that
918    /// wasmtime _supports_ a feature. It should only be used to _disable_
919    /// features that callers want to be rejected by the parser or _enable_
920    /// features callers are certain that the current configuration of wasmtime
921    /// supports.
922    ///
923    /// Feature validation is deferred until an engine is being built, thus by
924    /// enabling features here a caller may cause
925    /// [`Engine::new`] to fail later, if the feature
926    /// configuration isn't supported.
927    pub fn wasm_features(&mut self, flag: WasmFeatures, enable: bool) -> &mut Self {
928        self.enabled_features.set(flag, enable);
929        self.disabled_features.set(flag, !enable);
930        self
931    }
932
933    /// Configures whether the WebAssembly tail calls proposal will be enabled
934    /// for compilation or not.
935    ///
936    /// The [WebAssembly tail calls proposal] introduces the `return_call` and
937    /// `return_call_indirect` instructions. These instructions allow for Wasm
938    /// programs to implement some recursive algorithms with *O(1)* stack space
939    /// usage.
940    ///
941    /// This is `true` by default except when the Winch compiler is enabled.
942    ///
943    /// [WebAssembly tail calls proposal]: https://github.com/WebAssembly/tail-call
944    pub fn wasm_tail_call(&mut self, enable: bool) -> &mut Self {
945        self.wasm_features(WasmFeatures::TAIL_CALL, enable);
946        self
947    }
948
949    /// Configures whether the WebAssembly [branch-hinting] proposal is enabled.
950    ///
951    /// When enabled, the `metadata.code.branch_hint` custom section is parsed
952    /// and used to lay out cold code paths during compilation. The hints are
953    /// advisory and never affect execution semantics.
954    ///
955    /// This is `false` by default until the proposal has been fuzzed.
956    ///
957    /// [branch-hinting]: https://github.com/WebAssembly/branch-hinting
958    pub fn wasm_branch_hinting(&mut self, enable: bool) -> &mut Self {
959        self.tunables.branch_hinting = Some(enable);
960        self
961    }
962
963    /// Configures whether the WebAssembly custom-page-sizes proposal will be
964    /// enabled for compilation or not.
965    ///
966    /// The [WebAssembly custom-page-sizes proposal] allows a memory to
967    /// customize its page sizes. By default, Wasm page sizes are 64KiB
968    /// large. This proposal allows the memory to opt into smaller page sizes
969    /// instead, allowing Wasm to run in environments with less than 64KiB RAM
970    /// available, for example.
971    ///
972    /// Note that the page size is part of the memory's type, and because
973    /// different memories may have different types, they may also have
974    /// different page sizes.
975    ///
976    /// Currently the only valid page sizes are 64KiB (the default) and 1
977    /// byte. Future extensions may relax this constraint and allow all powers
978    /// of two.
979    ///
980    /// Support for this proposal is disabled by default.
981    ///
982    /// [WebAssembly custom-page-sizes proposal]: https://github.com/WebAssembly/custom-page-sizes
983    pub fn wasm_custom_page_sizes(&mut self, enable: bool) -> &mut Self {
984        self.wasm_features(WasmFeatures::CUSTOM_PAGE_SIZES, enable);
985        self
986    }
987
988    /// Configures whether the WebAssembly [threads] proposal will be enabled
989    /// for compilation.
990    ///
991    /// This feature gates items such as shared memories and atomic
992    /// instructions. Note that the threads feature depends on the bulk memory
993    /// feature, which is enabled by default. Additionally note that while the
994    /// wasm feature is called "threads" it does not actually include the
995    /// ability to spawn threads. Spawning threads is part of the [wasi-threads]
996    /// proposal which is a separately gated feature in Wasmtime.
997    ///
998    /// Embeddings of Wasmtime are able to build their own custom threading
999    /// scheme on top of the core wasm threads proposal, however.
1000    ///
1001    /// The default value for this option is whether the `threads`
1002    /// crate feature of Wasmtime is enabled or not. By default this crate
1003    /// feature is enabled.
1004    ///
1005    /// [threads]: https://github.com/webassembly/threads
1006    /// [wasi-threads]: https://github.com/webassembly/wasi-threads
1007    #[cfg(feature = "threads")]
1008    pub fn wasm_threads(&mut self, enable: bool) -> &mut Self {
1009        self.wasm_features(WasmFeatures::THREADS, enable);
1010        self
1011    }
1012
1013    /// Configures whether the WebAssembly [shared-everything-threads] proposal
1014    /// will be enabled for compilation.
1015    ///
1016    /// This feature gates extended use of the `shared` attribute on items other
1017    /// than memories, extra atomic instructions, and new component model
1018    /// intrinsics for spawning threads. It depends on the
1019    /// [`wasm_threads`][Self::wasm_threads] being enabled.
1020    ///
1021    /// [shared-everything-threads]:
1022    ///     https://github.com/webassembly/shared-everything-threads
1023    pub fn wasm_shared_everything_threads(&mut self, enable: bool) -> &mut Self {
1024        self.wasm_features(WasmFeatures::SHARED_EVERYTHING_THREADS, enable);
1025        self
1026    }
1027
1028    /// Configures whether the [WebAssembly reference types proposal][proposal]
1029    /// will be enabled for compilation.
1030    ///
1031    /// This feature gates items such as the `externref` and `funcref` types as
1032    /// well as allowing a module to define multiple tables.
1033    ///
1034    /// Note that the reference types proposal depends on the bulk memory proposal.
1035    ///
1036    /// This feature is `true` by default.
1037    ///
1038    /// # Errors
1039    ///
1040    /// The validation of this feature are deferred until the engine is being built,
1041    /// and thus may cause [`Engine::new`] fail if the `bulk_memory` feature is disabled.
1042    ///
1043    /// [proposal]: https://github.com/webassembly/reference-types
1044    #[cfg(feature = "gc")]
1045    pub fn wasm_reference_types(&mut self, enable: bool) -> &mut Self {
1046        self.wasm_features(WasmFeatures::REFERENCE_TYPES, enable);
1047        self
1048    }
1049
1050    /// Configures whether the [WebAssembly function references
1051    /// proposal][proposal] will be enabled for compilation.
1052    ///
1053    /// This feature gates non-nullable reference types, function reference
1054    /// types, `call_ref`, `ref.func`, and non-nullable reference related
1055    /// instructions.
1056    ///
1057    /// Note that the function references proposal depends on the reference
1058    /// types proposal.
1059    ///
1060    /// This feature is `true` by default.
1061    ///
1062    /// [proposal]: https://github.com/WebAssembly/function-references
1063    #[cfg(feature = "gc")]
1064    pub fn wasm_function_references(&mut self, enable: bool) -> &mut Self {
1065        self.wasm_features(WasmFeatures::FUNCTION_REFERENCES, enable);
1066        self
1067    }
1068
1069    /// Configures whether the [WebAssembly wide-arithmetic][proposal] will be
1070    /// enabled for compilation.
1071    ///
1072    /// This feature is `true` by default.
1073    ///
1074    /// [proposal]: https://github.com/WebAssembly/wide-arithmetic
1075    pub fn wasm_wide_arithmetic(&mut self, enable: bool) -> &mut Self {
1076        self.wasm_features(WasmFeatures::WIDE_ARITHMETIC, enable);
1077        self
1078    }
1079
1080    /// Configures whether the [WebAssembly Garbage Collection
1081    /// proposal][proposal] will be enabled for compilation.
1082    ///
1083    /// This feature gates `struct` and `array` type definitions and references,
1084    /// the `i31ref` type, and all related instructions.
1085    ///
1086    /// Note that the function references proposal depends on the typed function
1087    /// references proposal.
1088    ///
1089    /// This feature is `true` by default.
1090    ///
1091    /// [proposal]: https://github.com/WebAssembly/gc
1092    pub fn wasm_gc(&mut self, enable: bool) -> &mut Self {
1093        self.wasm_features(WasmFeatures::GC, enable);
1094        self
1095    }
1096
1097    /// Configures whether the WebAssembly SIMD proposal will be
1098    /// enabled for compilation.
1099    ///
1100    /// The [WebAssembly SIMD proposal][proposal]. This feature gates items such
1101    /// as the `v128` type and all of its operators being in a module. Note that
1102    /// this does not enable the [relaxed simd proposal].
1103    ///
1104    /// **Note**
1105    ///
1106    /// On x86_64 platforms the base CPU feature requirement for SIMD
1107    /// is SSE2 for the Cranelift compiler and AVX for the Winch compiler.
1108    ///
1109    /// This is `true` by default.
1110    ///
1111    /// [proposal]: https://github.com/webassembly/simd
1112    /// [relaxed simd proposal]: https://github.com/WebAssembly/relaxed-simd
1113    pub fn wasm_simd(&mut self, enable: bool) -> &mut Self {
1114        self.wasm_features(WasmFeatures::SIMD, enable);
1115        self
1116    }
1117
1118    /// Configures whether the WebAssembly Relaxed SIMD proposal will be
1119    /// enabled for compilation.
1120    ///
1121    /// The relaxed SIMD proposal adds new instructions to WebAssembly which,
1122    /// for some specific inputs, are allowed to produce different results on
1123    /// different hosts. More-or-less this proposal enables exposing
1124    /// platform-specific semantics of SIMD instructions in a controlled
1125    /// fashion to a WebAssembly program. From an embedder's perspective this
1126    /// means that WebAssembly programs may execute differently depending on
1127    /// whether the host is x86_64 or AArch64, for example.
1128    ///
1129    /// By default Wasmtime lowers relaxed SIMD instructions to the fastest
1130    /// lowering for the platform it's running on. This means that, by default,
1131    /// some relaxed SIMD instructions may have different results for the same
1132    /// inputs across x86_64 and AArch64. This behavior can be disabled through
1133    /// the [`Config::relaxed_simd_deterministic`] option which will force
1134    /// deterministic behavior across all platforms, as classified by the
1135    /// specification, at the cost of performance.
1136    ///
1137    /// This is `true` by default.
1138    ///
1139    /// [proposal]: https://github.com/webassembly/relaxed-simd
1140    pub fn wasm_relaxed_simd(&mut self, enable: bool) -> &mut Self {
1141        self.wasm_features(WasmFeatures::RELAXED_SIMD, enable);
1142        self
1143    }
1144
1145    /// This option can be used to control the behavior of the [relaxed SIMD
1146    /// proposal's][proposal] instructions.
1147    ///
1148    /// The relaxed SIMD proposal introduces instructions that are allowed to
1149    /// have different behavior on different architectures, primarily to afford
1150    /// an efficient implementation on all architectures. This means, however,
1151    /// that the same module may execute differently on one host than another,
1152    /// which typically is not otherwise the case. This option is provided to
1153    /// force Wasmtime to generate deterministic code for all relaxed simd
1154    /// instructions, at the cost of performance, for all architectures. When
1155    /// this option is enabled then the deterministic behavior of all
1156    /// instructions in the relaxed SIMD proposal is selected.
1157    ///
1158    /// This is `false` by default.
1159    ///
1160    /// [proposal]: https://github.com/webassembly/relaxed-simd
1161    pub fn relaxed_simd_deterministic(&mut self, enable: bool) -> &mut Self {
1162        self.tunables.relaxed_simd_deterministic = Some(enable);
1163        self
1164    }
1165
1166    /// Configures whether the [WebAssembly bulk memory operations
1167    /// proposal][proposal] will be enabled for compilation.
1168    ///
1169    /// This feature gates items such as the `memory.copy` instruction, passive
1170    /// data/table segments, etc, being in a module.
1171    ///
1172    /// This is `true` by default.
1173    ///
1174    /// Feature `reference_types`, which is also `true` by default, requires
1175    /// this feature to be enabled. Thus disabling this feature must also disable
1176    /// `reference_types` as well using [`wasm_reference_types`](crate::Config::wasm_reference_types).
1177    ///
1178    /// # Errors
1179    ///
1180    /// Disabling this feature without disabling `reference_types` will cause
1181    /// [`Engine::new`] to fail.
1182    ///
1183    /// [proposal]: https://github.com/webassembly/bulk-memory-operations
1184    pub fn wasm_bulk_memory(&mut self, enable: bool) -> &mut Self {
1185        self.wasm_features(WasmFeatures::BULK_MEMORY, enable);
1186        self
1187    }
1188
1189    /// Configures whether the WebAssembly multi-value [proposal] will
1190    /// be enabled for compilation.
1191    ///
1192    /// This feature gates functions and blocks returning multiple values in a
1193    /// module, for example.
1194    ///
1195    /// This is `true` by default.
1196    ///
1197    /// [proposal]: https://github.com/webassembly/multi-value
1198    pub fn wasm_multi_value(&mut self, enable: bool) -> &mut Self {
1199        self.wasm_features(WasmFeatures::MULTI_VALUE, enable);
1200        self
1201    }
1202
1203    /// Configures whether the WebAssembly multi-memory [proposal] will
1204    /// be enabled for compilation.
1205    ///
1206    /// This feature gates modules having more than one linear memory
1207    /// declaration or import.
1208    ///
1209    /// This is `true` by default.
1210    ///
1211    /// [proposal]: https://github.com/webassembly/multi-memory
1212    pub fn wasm_multi_memory(&mut self, enable: bool) -> &mut Self {
1213        self.wasm_features(WasmFeatures::MULTI_MEMORY, enable);
1214        self
1215    }
1216
1217    /// Configures whether the WebAssembly memory64 [proposal] will
1218    /// be enabled for compilation.
1219    ///
1220    /// Note that this the upstream specification is not finalized and Wasmtime
1221    /// may also have bugs for this feature since it hasn't been exercised
1222    /// much.
1223    ///
1224    /// This is `false` by default.
1225    ///
1226    /// [proposal]: https://github.com/webassembly/memory64
1227    pub fn wasm_memory64(&mut self, enable: bool) -> &mut Self {
1228        self.wasm_features(WasmFeatures::MEMORY64, enable);
1229        self
1230    }
1231
1232    /// Configures whether the WebAssembly extended-const [proposal] will
1233    /// be enabled for compilation.
1234    ///
1235    /// This is `true` by default.
1236    ///
1237    /// [proposal]: https://github.com/webassembly/extended-const
1238    pub fn wasm_extended_const(&mut self, enable: bool) -> &mut Self {
1239        self.wasm_features(WasmFeatures::EXTENDED_CONST, enable);
1240        self
1241    }
1242
1243    /// Configures whether the [WebAssembly stack switching
1244    /// proposal][proposal] will be enabled for compilation.
1245    ///
1246    /// This feature gates the use of control tags.
1247    ///
1248    /// This feature depends on the `function_reference_types` and
1249    /// `exceptions` features.
1250    ///
1251    /// This feature is `false` by default.
1252    ///
1253    /// # Errors
1254    ///
1255    /// [proposal]: https://github.com/webassembly/stack-switching
1256    pub fn wasm_stack_switching(&mut self, enable: bool) -> &mut Self {
1257        self.wasm_features(WasmFeatures::STACK_SWITCHING, enable);
1258        self
1259    }
1260
1261    /// Configures whether the WebAssembly component-model [proposal] will
1262    /// be enabled for compilation.
1263    ///
1264    /// This flag can be used to blanket disable all components within Wasmtime.
1265    /// Otherwise usage of components requires statically using
1266    /// [`Component`](crate::component::Component) instead of
1267    /// [`Module`](crate::Module) for example anyway.
1268    ///
1269    /// The default value for this option is whether the `component-model`
1270    /// crate feature of Wasmtime is enabled or not. By default this crate
1271    /// feature is enabled.
1272    ///
1273    /// [proposal]: https://github.com/webassembly/component-model
1274    #[cfg(feature = "component-model")]
1275    pub fn wasm_component_model(&mut self, enable: bool) -> &mut Self {
1276        self.wasm_features(WasmFeatures::COMPONENT_MODEL, enable);
1277        self
1278    }
1279
1280    /// Configures whether components support the async ABI [proposal] for
1281    /// lifting and lowering functions, as well as `stream`, `future`, and
1282    /// `error-context` types.
1283    ///
1284    /// Please note that Wasmtime's support for this feature is _very_
1285    /// incomplete.
1286    ///
1287    /// [proposal]:
1288    ///     https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1289    #[cfg(feature = "component-model-async")]
1290    pub fn wasm_component_model_async(&mut self, enable: bool) -> &mut Self {
1291        self.wasm_features(WasmFeatures::CM_ASYNC, enable);
1292        self
1293    }
1294
1295    /// This corresponds to the 🚝 emoji in the component model specification.
1296    ///
1297    /// Please note that Wasmtime's support for this feature is _very_
1298    /// incomplete.
1299    ///
1300    /// [proposal]:
1301    ///     https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1302    #[cfg(feature = "component-model-async")]
1303    pub fn wasm_component_model_more_async_builtins(&mut self, enable: bool) -> &mut Self {
1304        self.wasm_features(WasmFeatures::CM_MORE_ASYNC_BUILTINS, enable);
1305        self
1306    }
1307
1308    /// This corresponds to the 🚟 emoji in the component model specification.
1309    ///
1310    /// Please note that Wasmtime's support for this feature is _very_
1311    /// incomplete.
1312    ///
1313    /// [proposal]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1314    #[cfg(feature = "component-model-async")]
1315    pub fn wasm_component_model_async_stackful(&mut self, enable: bool) -> &mut Self {
1316        self.wasm_features(WasmFeatures::CM_ASYNC_STACKFUL, enable);
1317        self
1318    }
1319
1320    /// This corresponds to the 🧵 emoji in the component model specification.
1321    ///
1322    /// Please note that Wasmtime's support for this feature is _very_
1323    /// incomplete.
1324    ///
1325    /// [proposal]:
1326    ///     https://github.com/WebAssembly/component-model/pull/557
1327    #[cfg(feature = "component-model-async")]
1328    pub fn wasm_component_model_threading(&mut self, enable: bool) -> &mut Self {
1329        self.wasm_features(WasmFeatures::CM_THREADING, enable);
1330        self
1331    }
1332
1333    /// This corresponds to the 📝 emoji in the component model specification.
1334    ///
1335    /// Please note that Wasmtime's support for this feature is _very_
1336    /// incomplete.
1337    ///
1338    /// [proposal]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1339    #[cfg(feature = "component-model")]
1340    pub fn wasm_component_model_error_context(&mut self, enable: bool) -> &mut Self {
1341        self.wasm_features(WasmFeatures::CM_ERROR_CONTEXT, enable);
1342        self
1343    }
1344
1345    /// Configures whether the [GC extension to the component-model
1346    /// proposal][proposal] is enabled or not.
1347    ///
1348    /// This corresponds to the 🛸 emoji in the component model specification.
1349    ///
1350    /// Please note that Wasmtime's support for this feature is _very_
1351    /// incomplete.
1352    ///
1353    /// [proposal]: https://github.com/WebAssembly/component-model/issues/525
1354    #[cfg(feature = "component-model")]
1355    pub fn wasm_component_model_gc(&mut self, enable: bool) -> &mut Self {
1356        self.wasm_features(WasmFeatures::CM_GC, enable);
1357        self
1358    }
1359
1360    /// Configures whether the component model map type is enabled or not.
1361    ///
1362    /// This is part of the component model specification and enables the
1363    /// `map<k, v>` type in WIT and the component binary format.
1364    #[cfg(feature = "component-model")]
1365    pub fn wasm_component_model_map(&mut self, enable: bool) -> &mut Self {
1366        self.wasm_features(WasmFeatures::CM_MAP, enable);
1367        self
1368    }
1369
1370    /// Configures whether the component model memory64 support is enabled
1371    ///
1372    /// This corresponds to the 🐘 emoji in the component model specification.
1373    ///
1374    /// Please note that Wasmtime's support for this feature is _very_
1375    /// incomplete.
1376    #[cfg(feature = "component-model")]
1377    pub fn wasm_component_model_memory64(&mut self, enable: bool) -> &mut Self {
1378        self.wasm_features(WasmFeatures::CM64, enable);
1379        self
1380    }
1381
1382    /// This corresponds to the 🔧 emoji in the component model specification.
1383    ///
1384    /// Please note that Wasmtime's support for this feature is _very_
1385    /// incomplete.
1386    #[cfg(feature = "component-model")]
1387    pub fn wasm_component_model_fixed_length_lists(&mut self, enable: bool) -> &mut Self {
1388        self.wasm_features(WasmFeatures::CM_FIXED_LENGTH_LISTS, enable);
1389        self
1390    }
1391
1392    /// This corresponds to the 🏷️ emoji in the component model specification.
1393    ///
1394    /// Please note that Wasmtime's support for this feature is a work in
1395    /// progress.
1396    #[cfg(feature = "component-model")]
1397    pub fn wasm_component_model_implements(&mut self, enable: bool) -> &mut Self {
1398        self.wasm_features(WasmFeatures::CM_IMPLEMENTS, enable);
1399        self
1400    }
1401
1402    /// This corresponds to the 🔗 emoji in the component model specification.
1403    ///
1404    /// Please note that Wasmtime's support for this feature is a work in
1405    /// progress.
1406    #[cfg(feature = "component-model")]
1407    pub fn wasm_component_model_canonical_names(&mut self, enable: bool) -> &mut Self {
1408        self.wasm_features(WasmFeatures::CM_CANON_NAMES, enable);
1409        self
1410    }
1411
1412    /// Configures whether the [Exception-handling proposal][proposal] is enabled or not.
1413    ///
1414    /// This is `true` by default.
1415    ///
1416    /// [proposal]: https://github.com/WebAssembly/exception-handling
1417    #[cfg(feature = "gc")]
1418    pub fn wasm_exceptions(&mut self, enable: bool) -> &mut Self {
1419        self.wasm_features(WasmFeatures::EXCEPTIONS, enable);
1420        self
1421    }
1422
1423    #[doc(hidden)] // FIXME(#3427) - if/when implemented then un-hide this
1424    #[deprecated = "This configuration option only exists for internal \
1425                    usage with the spec testsuite. It may be removed at \
1426                    any time and without warning. Do not rely on it!"]
1427    pub fn wasm_legacy_exceptions(&mut self, enable: bool) -> &mut Self {
1428        self.wasm_features(WasmFeatures::LEGACY_EXCEPTIONS, enable);
1429        self
1430    }
1431
1432    /// Configures which compilation strategy will be used for wasm modules.
1433    ///
1434    /// This method can be used to configure which compiler is used for wasm
1435    /// modules, and for more documentation consult the [`Strategy`] enumeration
1436    /// and its documentation.
1437    ///
1438    /// The default value for this is `Strategy::Auto`.
1439    ///
1440    /// # Panics
1441    ///
1442    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1443    #[cfg(any(feature = "cranelift", feature = "winch"))]
1444    pub fn strategy(&mut self, strategy: Strategy) -> &mut Self {
1445        self.compiler_config_mut().strategy = strategy.not_auto();
1446        self
1447    }
1448
1449    /// Configures which garbage collector will be used for Wasm modules.
1450    ///
1451    /// This method can be used to configure which garbage collector
1452    /// implementation is used for Wasm modules. For more documentation, consult
1453    /// the [`Collector`] enumeration and its documentation.
1454    ///
1455    /// The default value for this is `Collector::Auto`.
1456    #[cfg(feature = "gc")]
1457    pub fn collector(&mut self, collector: Collector) -> &mut Self {
1458        self.collector = collector;
1459        self
1460    }
1461
1462    /// Configures the initial size, in bytes, of each store's GC heap.
1463    ///
1464    /// By default all GC heaps start out at 0 bytes in size and must grow
1465    /// upwards from there. Growth happens incrementally as GC pressure happens
1466    /// and memory runs out. The amount being grown by is additionally a
1467    /// heuristic of the size of the failed allocation. By providing an initial
1468    /// size of a store's GC heap embedders can more tightly control initial
1469    /// parameters to optimize workloads that might have a predictable pattern.
1470    /// For example if workloads frequently have less than a certain threshold
1471    /// of size then that could be configured as the initial size here to avoid
1472    /// growths happening over time.
1473    ///
1474    /// Note that like WebAssembly linear memories the GC heap does not start
1475    /// with committed memory equal to this size. Instead memory is reserved,
1476    /// but then lazily allocated by the OS on access. In other words it should
1477    /// be relatively cheap to increase this value to help amortize initial
1478    /// startup cost of wasm modules.
1479    ///
1480    /// The `bytes` size is rounded up to the GC heap's page size.
1481    ///
1482    /// This only configures the initially-allocated size of the GC heap; the
1483    /// heap can still grow beyond it on demand. It is separate from
1484    /// [`Config::gc_heap_reservation`], which configures the size of the
1485    /// virtual-memory reservation (and therefore how far the heap can grow
1486    /// in place).
1487    ///
1488    /// The default value for this is 0.
1489    pub fn gc_heap_initial_size(&mut self, bytes: u64) -> &mut Self {
1490        self.tunables.gc_heap_initial_size = Some(bytes);
1491        self
1492    }
1493
1494    /// Creates a default profiler based on the profiling strategy chosen.
1495    ///
1496    /// Profiler creation calls the type's default initializer where the purpose is
1497    /// really just to put in place the type used for profiling.
1498    ///
1499    /// Some [`ProfilingStrategy`] require specific platforms or particular feature
1500    /// to be enabled, such as `ProfilingStrategy::JitDump` requires the `jitdump`
1501    /// feature.
1502    ///
1503    /// # Errors
1504    ///
1505    /// The validation of this field is deferred until the engine is being built, and thus may
1506    /// cause [`Engine::new`] fail if the required feature is disabled, or the platform is not
1507    /// supported.
1508    pub fn profiler(&mut self, profile: ProfilingStrategy) -> &mut Self {
1509        self.profiling_strategy = profile;
1510        self
1511    }
1512
1513    /// Configures whether the debug verifier of Cranelift is enabled or not.
1514    ///
1515    /// When Cranelift is used as a code generation backend this will configure
1516    /// it to have the `enable_verifier` flag which will enable a number of debug
1517    /// checks inside of Cranelift. This is largely only useful for the
1518    /// developers of wasmtime itself.
1519    ///
1520    /// The default value for this is `false`
1521    ///
1522    /// # Panics
1523    ///
1524    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1525    #[cfg(any(feature = "cranelift", feature = "winch"))]
1526    pub fn cranelift_debug_verifier(&mut self, enable: bool) -> &mut Self {
1527        let val = if enable { "true" } else { "false" };
1528        self.compiler_config_mut().settings.insert(
1529            "enable_verifier".to_string(),
1530            (val.to_string(), UserSpecified::No),
1531        );
1532        self
1533    }
1534
1535    /// Configures whether extra debug checks are inserted into
1536    /// Wasmtime-generated code by Cranelift.
1537    ///
1538    /// The default value for this is `false`
1539    ///
1540    /// # Panics
1541    ///
1542    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1543    #[cfg(any(feature = "cranelift", feature = "winch"))]
1544    pub fn cranelift_wasmtime_debug_checks(&mut self, enable: bool) -> &mut Self {
1545        unsafe { self.cranelift_flag_set("wasmtime_debug_checks", &enable.to_string()) }
1546    }
1547
1548    /// Configures the Cranelift code generator optimization level.
1549    ///
1550    /// When the Cranelift code generator is used you can configure the
1551    /// optimization level used for generated code in a few various ways. For
1552    /// more information see the documentation of [`OptLevel`].
1553    ///
1554    /// The default value for this is `OptLevel::Speed`.
1555    ///
1556    /// # Panics
1557    ///
1558    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1559    #[cfg(any(feature = "cranelift", feature = "winch"))]
1560    pub fn cranelift_opt_level(&mut self, level: OptLevel) -> &mut Self {
1561        let val = match level {
1562            OptLevel::None => "none",
1563            OptLevel::Speed => "speed",
1564            OptLevel::SpeedAndSize => "speed_and_size",
1565        };
1566        self.compiler_config_mut().settings.insert(
1567            "opt_level".to_string(),
1568            (val.to_string(), UserSpecified::No),
1569        );
1570        self
1571    }
1572
1573    /// Configures the regalloc algorithm used by the Cranelift code generator.
1574    ///
1575    /// Cranelift can select any of several register allocator algorithms. Each
1576    /// of these algorithms generates correct code, but they represent different
1577    /// tradeoffs between compile speed (how expensive the compilation process
1578    /// is) and run-time speed (how fast the generated code runs).
1579    /// For more information see the documentation of [`RegallocAlgorithm`].
1580    ///
1581    /// The default value for this is `RegallocAlgorithm::Backtracking`.
1582    ///
1583    /// # Panics
1584    ///
1585    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1586    #[cfg(any(feature = "cranelift", feature = "winch"))]
1587    pub fn cranelift_regalloc_algorithm(&mut self, algo: RegallocAlgorithm) -> &mut Self {
1588        let val = match algo {
1589            RegallocAlgorithm::Backtracking => "backtracking",
1590            RegallocAlgorithm::SinglePass => "single_pass",
1591        };
1592        self.compiler_config_mut().settings.insert(
1593            "regalloc_algorithm".to_string(),
1594            (val.to_string(), UserSpecified::No),
1595        );
1596        self
1597    }
1598
1599    /// Configures whether Cranelift should perform a NaN-canonicalization pass.
1600    ///
1601    /// When Cranelift is used as a code generation backend this will configure
1602    /// it to replace NaNs with a single canonical value. This is useful for
1603    /// users requiring entirely deterministic WebAssembly computation.  This is
1604    /// not required by the WebAssembly spec, so it is not enabled by default.
1605    ///
1606    /// Note that this option affects not only WebAssembly's `f32` and `f64`
1607    /// types but additionally the `v128` type. This option will cause
1608    /// operations using any of these types to have extra checks placed after
1609    /// them to normalize NaN values as needed.
1610    ///
1611    /// The default value for this is `false`
1612    ///
1613    /// # Panics
1614    ///
1615    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1616    #[cfg(any(feature = "cranelift", feature = "winch"))]
1617    pub fn cranelift_nan_canonicalization(&mut self, enable: bool) -> &mut Self {
1618        let val = if enable { "true" } else { "false" };
1619        self.compiler_config_mut().settings.insert(
1620            "enable_nan_canonicalization".to_string(),
1621            (val.to_string(), UserSpecified::No),
1622        );
1623        self
1624    }
1625
1626    /// Allows setting a Cranelift boolean flag or preset. This allows
1627    /// fine-tuning of Cranelift settings.
1628    ///
1629    /// Since Cranelift flags may be unstable, this method should not be considered to be stable
1630    /// either; other `Config` functions should be preferred for stability.
1631    ///
1632    /// # Safety
1633    ///
1634    /// This is marked as unsafe, because setting the wrong flag might break invariants,
1635    /// resulting in execution hazards.
1636    ///
1637    /// # Errors
1638    ///
1639    /// The validation of the flags are deferred until the engine is being built, and thus may
1640    /// cause [`Engine::new`] fail if the flag's name does not exist, or the value is not appropriate
1641    /// for the flag type.
1642    ///
1643    /// # Panics
1644    ///
1645    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1646    #[cfg(any(feature = "cranelift", feature = "winch"))]
1647    pub unsafe fn cranelift_flag_enable(&mut self, flag: &str) -> &mut Self {
1648        self.compiler_config_mut()
1649            .flags
1650            .insert(flag.to_string(), UserSpecified::Yes);
1651        self
1652    }
1653
1654    /// Allows settings another Cranelift flag defined by a flag name and value. This allows
1655    /// fine-tuning of Cranelift settings.
1656    ///
1657    /// Since Cranelift flags may be unstable, this method should not be considered to be stable
1658    /// either; other `Config` functions should be preferred for stability.
1659    ///
1660    /// # Safety
1661    ///
1662    /// This is marked as unsafe, because setting the wrong flag might break invariants,
1663    /// resulting in execution hazards.
1664    ///
1665    /// # Errors
1666    ///
1667    /// The validation of the flags are deferred until the engine is being built, and thus may
1668    /// cause [`Engine::new`] fail if the flag's name does not exist, or incompatible with other
1669    /// settings.
1670    ///
1671    /// For example, feature `wasm_backtrace` will set `unwind_info` to `true`, but if it's
1672    /// manually set to false then it will fail.
1673    ///
1674    /// # Panics
1675    ///
1676    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1677    #[cfg(any(feature = "cranelift", feature = "winch"))]
1678    pub unsafe fn cranelift_flag_set(&mut self, name: &str, value: &str) -> &mut Self {
1679        self.compiler_config_mut()
1680            .settings
1681            .insert(name.to_string(), (value.to_string(), UserSpecified::Yes));
1682        self
1683    }
1684
1685    /// Set a custom [`Cache`].
1686    ///
1687    /// To load a cache configuration from a file, use [`Cache::from_file`]. Otherwise, you can
1688    /// create a new cache config using [`CacheConfig::new`] and passing that to [`Cache::new`].
1689    ///
1690    /// If you want to disable the cache, you can call this method with `None`.
1691    ///
1692    /// By default, new configs do not have caching enabled.
1693    /// Every call to [`Module::new(my_wasm)`][crate::Module::new] will recompile `my_wasm`,
1694    /// even when it is unchanged, unless an enabled `CacheConfig` is provided.
1695    ///
1696    /// This method is only available when the `cache` feature of this crate is
1697    /// enabled.
1698    ///
1699    /// [docs]: https://bytecodealliance.github.io/wasmtime/cli-cache.html
1700    #[cfg(feature = "cache")]
1701    pub fn cache(&mut self, cache: Option<Cache>) -> &mut Self {
1702        self.cache = cache;
1703        self
1704    }
1705
1706    /// Sets a custom memory creator.
1707    ///
1708    /// Custom memory creators are used when creating host `Memory` objects or when
1709    /// creating instance linear memories for the on-demand instance allocation strategy.
1710    #[cfg(feature = "runtime")]
1711    pub fn with_host_memory(&mut self, mem_creator: Arc<dyn MemoryCreator>) -> &mut Self {
1712        self.mem_creator = Some(Arc::new(MemoryCreatorProxy(mem_creator)));
1713        self
1714    }
1715
1716    /// Sets a custom stack creator.
1717    ///
1718    /// Custom memory creators are used when creating creating async instance stacks for
1719    /// the on-demand instance allocation strategy.
1720    #[cfg(feature = "async")]
1721    pub fn with_host_stack(&mut self, stack_creator: Arc<dyn StackCreator>) -> &mut Self {
1722        self.stack_creator = Some(Arc::new(StackCreatorProxy(stack_creator)));
1723        self
1724    }
1725
1726    /// Sets a custom executable-memory publisher.
1727    ///
1728    /// Custom executable-memory publishers are hooks that allow
1729    /// Wasmtime to make certain regions of memory executable when
1730    /// loading precompiled modules or compiling new modules
1731    /// in-process. In most modern operating systems, memory allocated
1732    /// for heap usage is readable and writable by default but not
1733    /// executable. To jump to machine code stored in that memory, we
1734    /// need to make it executable. For security reasons, we usually
1735    /// also make it read-only at the same time, so the executing code
1736    /// can't be modified later.
1737    ///
1738    /// By default, Wasmtime will use the appropriate system calls on
1739    /// the host platform for this work. However, it also allows
1740    /// plugging in a custom implementation via this configuration
1741    /// option. This may be useful on custom or `no_std` platforms,
1742    /// for example, especially where virtual memory is not otherwise
1743    /// used by Wasmtime (no `signals-and-traps` feature).
1744    #[cfg(feature = "runtime")]
1745    pub fn with_custom_code_memory(
1746        &mut self,
1747        custom_code_memory: Option<Arc<dyn CustomCodeMemory>>,
1748    ) -> &mut Self {
1749        self.custom_code_memory = custom_code_memory;
1750        self
1751    }
1752
1753    /// Sets the instance allocation strategy to use.
1754    ///
1755    /// This is notably used in conjunction with
1756    /// [`InstanceAllocationStrategy::Pooling`] and [`PoolingAllocationConfig`].
1757    pub fn allocation_strategy(
1758        &mut self,
1759        strategy: impl Into<InstanceAllocationStrategy>,
1760    ) -> &mut Self {
1761        self.allocation_strategy = strategy.into();
1762        self
1763    }
1764
1765    /// Specifies the capacity of linear memories, in bytes, in their initial
1766    /// allocation.
1767    ///
1768    /// > Note: this value has important performance ramifications, be sure to
1769    /// > benchmark when setting this to a non-default value and read over this
1770    /// > documentation.
1771    ///
1772    /// This function will change the size of the initial memory allocation made
1773    /// for linear memories. This setting is only applicable when the initial
1774    /// size of a linear memory is below this threshold. Linear memories are
1775    /// allocated in the virtual address space of the host process with OS APIs
1776    /// such as `mmap` and this setting affects how large the allocation will
1777    /// be.
1778    ///
1779    /// ## Background: WebAssembly Linear Memories
1780    ///
1781    /// WebAssembly linear memories always start with a minimum size and can
1782    /// possibly grow up to a maximum size. The minimum size is always specified
1783    /// in a WebAssembly module itself and the maximum size can either be
1784    /// optionally specified in the module or inherently limited by the index
1785    /// type. For example for this module:
1786    ///
1787    /// ```wasm
1788    /// (module
1789    ///     (memory $a 4)
1790    ///     (memory $b 4096 4096 (pagesize 1))
1791    ///     (memory $c i64 10)
1792    /// )
1793    /// ```
1794    ///
1795    /// * Memory `$a` initially allocates 4 WebAssembly pages (256KiB) and can
1796    ///   grow up to 4GiB, the limit of the 32-bit index space.
1797    /// * Memory `$b` initially allocates 4096 WebAssembly pages, but in this
1798    ///   case its page size is 1, so it's 4096 bytes. Memory can also grow no
1799    ///   further meaning that it will always be 4096 bytes.
1800    /// * Memory `$c` is a 64-bit linear memory which starts with 640KiB of
1801    ///   memory and can theoretically grow up to 2^64 bytes, although most
1802    ///   hosts will run out of memory long before that.
1803    ///
1804    /// All operations on linear memories done by wasm are required to be
1805    /// in-bounds. Any access beyond the end of a linear memory is considered a
1806    /// trap.
1807    ///
1808    /// ## What this setting affects: Virtual Memory
1809    ///
1810    /// This setting is used to configure the behavior of the size of the linear
1811    /// memory allocation performed for each of these memories. For example the
1812    /// initial linear memory allocation looks like this:
1813    ///
1814    /// ```text
1815    ///              memory_reservation
1816    ///                    |
1817    ///          ◄─────────┴────────────────►
1818    /// ┌───────┬─────────┬──────────────────┬───────┐
1819    /// │ guard │ initial │ ... capacity ... │ guard │
1820    /// └───────┴─────────┴──────────────────┴───────┘
1821    ///  ◄──┬──►                              ◄──┬──►
1822    ///     │                                    │
1823    ///     │                             memory_guard_size
1824    ///     │
1825    ///     │
1826    ///  memory_guard_size (if guard_before_linear_memory)
1827    /// ```
1828    ///
1829    /// Memory in the `initial` range is accessible to the instance and can be
1830    /// read/written by wasm code. Memory in the `guard` regions is never
1831    /// accessible to wasm code and memory in `capacity` is initially
1832    /// inaccessible but may become accessible through `memory.grow` instructions
1833    /// for example.
1834    ///
1835    /// This means that this setting is the size of the initial chunk of virtual
1836    /// memory that a linear memory may grow into.
1837    ///
1838    /// ## What this setting affects: Runtime Speed
1839    ///
1840    /// This is a performance-sensitive setting which is taken into account
1841    /// during the compilation process of a WebAssembly module. For example if a
1842    /// 32-bit WebAssembly linear memory has a `memory_reservation` size of 4GiB
1843    /// then bounds checks can be elided because `capacity` will be guaranteed
1844    /// to be unmapped for all addressable bytes that wasm can access (modulo a
1845    /// few details).
1846    ///
1847    /// If `memory_reservation` was something smaller like 256KiB then that
1848    /// would have a much smaller impact on virtual memory but the compile code
1849    /// would then need to have explicit bounds checks to ensure that
1850    /// loads/stores are in-bounds.
1851    ///
1852    /// The goal of this setting is to enable skipping bounds checks in most
1853    /// modules by default. Some situations which require explicit bounds checks
1854    /// though are:
1855    ///
1856    /// * When `memory_reservation` is smaller than the addressable size of the
1857    ///   linear memory. For example if 64-bit linear memories always need
1858    ///   bounds checks as they can address the entire virtual address spacce.
1859    ///   For 32-bit linear memories a `memory_reservation` minimum size of 4GiB
1860    ///   is required to elide bounds checks.
1861    ///
1862    /// * When linear memories have a page size of 1 then bounds checks are
1863    ///   required. In this situation virtual memory can't be relied upon
1864    ///   because that operates at the host page size granularity where wasm
1865    ///   requires a per-byte level granularity.
1866    ///
1867    /// * Configuration settings such as [`Config::signals_based_traps`] can be
1868    ///   used to disable the use of signal handlers and virtual memory so
1869    ///   explicit bounds checks are required.
1870    ///
1871    /// * When [`Config::memory_guard_size`] is too small a bounds check may be
1872    ///   required. For 32-bit wasm addresses are actually 33-bit effective
1873    ///   addresses because loads/stores have a 32-bit static offset to add to
1874    ///   the dynamic 32-bit address. If the static offset is larger than the
1875    ///   size of the guard region then an explicit bounds check is required.
1876    ///
1877    /// ## What this setting affects: Memory Growth Behavior
1878    ///
1879    /// In addition to affecting bounds checks emitted in compiled code this
1880    /// setting also affects how WebAssembly linear memories are grown. The
1881    /// `memory.grow` instruction can be used to make a linear memory larger and
1882    /// this is also affected by APIs such as
1883    /// [`Memory::grow`](crate::Memory::grow).
1884    ///
1885    /// In these situations when the amount being grown is small enough to fit
1886    /// within the remaining capacity then the linear memory doesn't have to be
1887    /// moved at runtime. If the capacity runs out though then a new linear
1888    /// memory allocation must be made and the contents of linear memory is
1889    /// copied over.
1890    ///
1891    /// For example here's a situation where a copy happens:
1892    ///
1893    /// * The `memory_reservation` setting is configured to 128KiB.
1894    /// * A WebAssembly linear memory starts with a single 64KiB page.
1895    /// * This memory can be grown by one page to contain the full 128KiB of
1896    ///   memory.
1897    /// * If grown by one more page, though, then a 192KiB allocation must be
1898    ///   made and the previous 128KiB of contents are copied into the new
1899    ///   allocation.
1900    ///
1901    /// This growth behavior can have a significant performance impact if lots
1902    /// of data needs to be copied on growth. Conversely if memory growth never
1903    /// needs to happen because the capacity will always be large enough then
1904    /// optimizations can be applied to cache the base pointer of linear memory.
1905    ///
1906    /// When memory is grown then the
1907    /// [`Config::memory_reservation_for_growth`] is used for the new
1908    /// memory allocation to have memory to grow into.
1909    ///
1910    /// When using the pooling allocator via [`PoolingAllocationConfig`] then
1911    /// memories are never allowed to move so requests for growth are instead
1912    /// rejected with an error.
1913    ///
1914    /// ## When this setting is not used
1915    ///
1916    /// This setting is ignored and unused when the initial size of linear
1917    /// memory is larger than this threshold. For example if this setting is set
1918    /// to 1MiB but a wasm module requires a 2MiB minimum allocation then this
1919    /// setting is ignored. In this situation the minimum size of memory will be
1920    /// allocated along with [`Config::memory_reservation_for_growth`]
1921    /// after it to grow into.
1922    ///
1923    /// That means that this value can be set to zero. That can be useful in
1924    /// benchmarking to see the overhead of bounds checks for example.
1925    /// Additionally it can be used to minimize the virtual memory allocated by
1926    /// Wasmtime.
1927    ///
1928    /// ## Default Value
1929    ///
1930    /// The default value for this property depends on the host platform. For
1931    /// 64-bit platforms there's lots of address space available, so the default
1932    /// configured here is 4GiB. When coupled with the default size of
1933    /// [`Config::memory_guard_size`] this means that 32-bit WebAssembly linear
1934    /// memories with 64KiB page sizes will skip almost all bounds checks by
1935    /// default.
1936    ///
1937    /// For 32-bit platforms this value defaults to 10MiB. This means that
1938    /// bounds checks will be required on 32-bit platforms.
1939    pub fn memory_reservation(&mut self, bytes: u64) -> &mut Self {
1940        self.tunables.memory_reservation = Some(bytes);
1941        self
1942    }
1943
1944    /// Indicates whether linear memories may relocate their base pointer at
1945    /// runtime.
1946    ///
1947    /// WebAssembly linear memories either have a maximum size that's explicitly
1948    /// listed in the type of a memory or inherently limited by the index type
1949    /// of the memory (e.g. 4GiB for 32-bit linear memories). Depending on how
1950    /// the linear memory is allocated (see [`Config::memory_reservation`]) it
1951    /// may be necessary to move the memory in the host's virtual address space
1952    /// during growth. This option controls whether this movement is allowed or
1953    /// not.
1954    ///
1955    /// An example of a linear memory needing to move is when
1956    /// [`Config::memory_reservation`] is 0 then a linear memory will be
1957    /// allocated as the minimum size of the memory plus
1958    /// [`Config::memory_reservation_for_growth`]. When memory grows beyond the
1959    /// reservation for growth then the memory needs to be relocated.
1960    ///
1961    /// When this option is set to `false` then it can have a number of impacts
1962    /// on how memories work at runtime:
1963    ///
1964    /// * Modules can be compiled with static knowledge the base pointer of
1965    ///   linear memory never changes to enable optimizations such as
1966    ///   loop invariant code motion (hoisting the base pointer out of a loop).
1967    ///
1968    /// * Memories cannot grow in excess of their original allocation. This
1969    ///   means that [`Config::memory_reservation`] and
1970    ///   [`Config::memory_reservation_for_growth`] may need tuning to ensure
1971    ///   the memory configuration works at runtime.
1972    ///
1973    /// The default value for this option is `true`.
1974    pub fn memory_may_move(&mut self, enable: bool) -> &mut Self {
1975        self.tunables.memory_may_move = Some(enable);
1976        self
1977    }
1978
1979    /// Configures the size, in bytes, of the guard region used at the end of a
1980    /// linear memory's address space reservation.
1981    ///
1982    /// > Note: this value has important performance ramifications, be sure to
1983    /// > understand what this value does before tweaking it and benchmarking.
1984    ///
1985    /// This setting controls how many bytes are guaranteed to be unmapped after
1986    /// the virtual memory allocation of a linear memory. When
1987    /// combined with sufficiently large values of
1988    /// [`Config::memory_reservation`] (e.g. 4GiB for 32-bit linear memories)
1989    /// then a guard region can be used to eliminate bounds checks in generated
1990    /// code.
1991    ///
1992    /// This setting additionally can be used to help deduplicate bounds checks
1993    /// in code that otherwise requires bounds checks. For example with a 4KiB
1994    /// guard region then a 64-bit linear memory which accesses addresses `x+8`
1995    /// and `x+16` only needs to perform a single bounds check on `x`. If that
1996    /// bounds check passes then the offset is guaranteed to either reside in
1997    /// linear memory or the guard region, resulting in deterministic behavior
1998    /// either way.
1999    ///
2000    /// ## How big should the guard be?
2001    ///
2002    /// In general, like with configuring [`Config::memory_reservation`], you
2003    /// probably don't want to change this value from the defaults. Removing
2004    /// bounds checks is dependent on a number of factors where the size of the
2005    /// guard region is only one piece of the equation. Other factors include:
2006    ///
2007    /// * [`Config::memory_reservation`]
2008    /// * The index type of the linear memory (e.g. 32-bit or 64-bit)
2009    /// * The page size of the linear memory
2010    /// * Other settings such as [`Config::signals_based_traps`]
2011    ///
2012    /// Embeddings using virtual memory almost always want at least some guard
2013    /// region, but otherwise changes from the default should be profiled
2014    /// locally to see the performance impact.
2015    ///
2016    /// ## Default
2017    ///
2018    /// The default value for this property is 32MiB on 64-bit platforms. This
2019    /// allows eliminating almost all bounds checks on loads/stores with an
2020    /// immediate offset of less than 32MiB. On 32-bit platforms this defaults
2021    /// to 64KiB.
2022    pub fn memory_guard_size(&mut self, bytes: u64) -> &mut Self {
2023        self.tunables.memory_guard_size = Some(bytes);
2024        self
2025    }
2026
2027    /// Configures the size, in bytes, of the extra virtual memory space
2028    /// reserved after a linear memory is relocated.
2029    ///
2030    /// This setting is used in conjunction with [`Config::memory_reservation`]
2031    /// to configure what happens after a linear memory is relocated in the host
2032    /// address space. If the initial size of a linear memory exceeds
2033    /// [`Config::memory_reservation`] or if it grows beyond that size
2034    /// throughout its lifetime then this setting will be used.
2035    ///
2036    /// When a linear memory is relocated it will initially look like this:
2037    ///
2038    /// ```text
2039    ///            memory.size
2040    ///                 │
2041    ///          ◄──────┴─────►
2042    /// ┌───────┬──────────────┬───────┐
2043    /// │ guard │  accessible  │ guard │
2044    /// └───────┴──────────────┴───────┘
2045    ///                         ◄──┬──►
2046    ///                            │
2047    ///                     memory_guard_size
2048    /// ```
2049    ///
2050    /// where `accessible` needs to be grown but there's no more memory to grow
2051    /// into. A new region of the virtual address space will be allocated that
2052    /// looks like this:
2053    ///
2054    /// ```text
2055    ///                           memory_reservation_for_growth
2056    ///                                       │
2057    ///            memory.size                │
2058    ///                 │                     │
2059    ///          ◄──────┴─────► ◄─────────────┴───────────►
2060    /// ┌───────┬──────────────┬───────────────────────────┬───────┐
2061    /// │ guard │  accessible  │ .. reserved for growth .. │ guard │
2062    /// └───────┴──────────────┴───────────────────────────┴───────┘
2063    ///                                                     ◄──┬──►
2064    ///                                                        │
2065    ///                                               memory_guard_size
2066    /// ```
2067    ///
2068    /// This means that up to `memory_reservation_for_growth` bytes can be
2069    /// allocated again before the entire linear memory needs to be moved again
2070    /// when another `memory_reservation_for_growth` bytes will be appended to
2071    /// the size of the allocation.
2072    ///
2073    /// Note that this is a currently simple heuristic for optimizing the growth
2074    /// of dynamic memories, primarily implemented for the memory64 proposal
2075    /// where the maximum size of memory is larger than 4GiB. This setting is
2076    /// unlikely to be a one-size-fits-all style approach and if you're an
2077    /// embedder running into issues with growth and are interested in having
2078    /// other growth strategies available here please feel free to [open an
2079    /// issue on the Wasmtime repository][issue]!
2080    ///
2081    /// [issue]: https://github.com/bytecodealliance/wasmtime/issues/new
2082    ///
2083    /// ## Default
2084    ///
2085    /// For 64-bit platforms this defaults to 2GiB, and for 32-bit platforms
2086    /// this defaults to 1MiB.
2087    pub fn memory_reservation_for_growth(&mut self, bytes: u64) -> &mut Self {
2088        self.tunables.memory_reservation_for_growth = Some(bytes);
2089        self
2090    }
2091
2092    /// Configures the initial size, in bytes, to be allocated for GC heaps.
2093    ///
2094    /// This is similar to [`Config::memory_reservation`] but applies to the GC
2095    /// heap rather than to linear memories. See that method for more details
2096    /// on what "reservation" means and the implications of this setting.
2097    ///
2098    /// ## Default
2099    ///
2100    /// If none of the `gc_heap_*` tunables are explicitly configured, they
2101    /// default to the same values as their `memory_*` counterparts. Otherwise,
2102    /// the default value for this property depends on the host platform: for
2103    /// 64-bit platforms this defaults to 4GiB, and for 32-bit platforms this
2104    /// defaults to 10MiB.
2105    pub fn gc_heap_reservation(&mut self, bytes: u64) -> &mut Self {
2106        self.tunables.gc_heap_reservation = Some(bytes);
2107        self
2108    }
2109
2110    /// Configures the size, in bytes, of the guard page region for GC heaps.
2111    ///
2112    /// This is similar to [`Config::memory_guard_size`] but applies to the GC
2113    /// heap rather than to linear memories. See that method for more details on
2114    /// what guard pages are and the implications of this setting.
2115    ///
2116    /// ## Default
2117    ///
2118    /// If none of the `gc_heap_*` tunables are explicitly configured, they
2119    /// default to the same values as their `memory_*` counterparts. Otherwise,
2120    /// the default value for this property is 32MiB on 64-bit platforms and
2121    /// 64KiB on 32-bit platforms.
2122    pub fn gc_heap_guard_size(&mut self, bytes: u64) -> &mut Self {
2123        self.tunables.gc_heap_guard_size = Some(bytes);
2124        self
2125    }
2126
2127    /// Configures the size, in bytes, of the extra virtual memory space
2128    /// reserved after a GC heap is relocated.
2129    ///
2130    /// This is similar to [`Config::memory_reservation_for_growth`] but applies
2131    /// to the GC heap rather than to linear memories. See that method for more
2132    /// details.
2133    ///
2134    /// ## Default
2135    ///
2136    /// If none of the `gc_heap_*` tunables are explicitly configured, they
2137    /// default to the same values as their `memory_*` counterparts. Otherwise,
2138    /// for 64-bit platforms this defaults to 2GiB, and for 32-bit platforms
2139    /// this defaults to 1MiB.
2140    pub fn gc_heap_reservation_for_growth(&mut self, bytes: u64) -> &mut Self {
2141        self.tunables.gc_heap_reservation_for_growth = Some(bytes);
2142        self
2143    }
2144
2145    /// Indicates whether GC heaps are allowed to be reallocated after initial
2146    /// allocation at runtime.
2147    ///
2148    /// This is similar to [`Config::memory_may_move`] but applies to the GC
2149    /// heap rather than to linear memories. See that method for more details.
2150    ///
2151    /// ## Default
2152    ///
2153    /// If none of the `gc_heap_*` tunables are explicitly configured, they
2154    /// default to the same values as their `memory_*` counterparts. Otherwise,
2155    /// the default value for this option is `true`.
2156    pub fn gc_heap_may_move(&mut self, enable: bool) -> &mut Self {
2157        self.tunables.gc_heap_may_move = Some(enable);
2158        self
2159    }
2160
2161    /// Indicates whether a guard region is present before allocations of
2162    /// linear memory.
2163    ///
2164    /// Guard regions before linear memories are never used during normal
2165    /// operation of WebAssembly modules, even if they have out-of-bounds
2166    /// loads. The only purpose for a preceding guard region in linear memory
2167    /// is extra protection against possible bugs in code generators like
2168    /// Cranelift. This setting does not affect performance in any way, but will
2169    /// result in larger virtual memory reservations for linear memories (it
2170    /// won't actually ever use more memory, just use more of the address
2171    /// space).
2172    ///
2173    /// The size of the guard region before linear memory is the same as the
2174    /// guard size that comes after linear memory, which is configured by
2175    /// [`Config::memory_guard_size`].
2176    ///
2177    /// ## Default
2178    ///
2179    /// This value defaults to `true`.
2180    pub fn guard_before_linear_memory(&mut self, enable: bool) -> &mut Self {
2181        self.tunables.guard_before_linear_memory = Some(enable);
2182        self
2183    }
2184
2185    /// Indicates whether to initialize tables lazily, so that instantiation
2186    /// is fast but indirect calls are a little slower. If false, tables
2187    /// are initialized eagerly during instantiation from any active element
2188    /// segments that apply to them.
2189    ///
2190    /// **Note** Disabling this option is not compatible with the Winch compiler.
2191    ///
2192    /// ## Default
2193    ///
2194    /// This value defaults to `true`.
2195    pub fn table_lazy_init(&mut self, table_lazy_init: bool) -> &mut Self {
2196        self.tunables.table_lazy_init = Some(table_lazy_init);
2197        self
2198    }
2199
2200    /// Configure the version information used in serialized and deserialized [`crate::Module`]s.
2201    /// This effects the behavior of [`crate::Module::serialize()`], as well as
2202    /// [`crate::Module::deserialize()`] and related functions.
2203    ///
2204    /// The default strategy is to use the wasmtime crate's Cargo package version.
2205    pub fn module_version(&mut self, strategy: ModuleVersionStrategy) -> Result<&mut Self> {
2206        match strategy {
2207            // This case requires special precondition for assertion in SerializedModule::to_bytes
2208            ModuleVersionStrategy::Custom(ref v) => {
2209                if v.as_bytes().len() > 255 {
2210                    bail!("custom module version cannot be more than 255 bytes: {v}");
2211                }
2212            }
2213            _ => {}
2214        }
2215        self.module_version = strategy;
2216        Ok(self)
2217    }
2218
2219    /// Configure whether wasmtime should compile a module using multiple
2220    /// threads.
2221    ///
2222    /// Disabling this will result in a single thread being used to compile
2223    /// the wasm bytecode.
2224    ///
2225    /// By default parallel compilation is enabled.
2226    #[cfg(feature = "parallel-compilation")]
2227    pub fn parallel_compilation(&mut self, parallel: bool) -> &mut Self {
2228        self.parallel_compilation = parallel;
2229        self
2230    }
2231
2232    /// Configures whether compiled artifacts will contain information to map
2233    /// native program addresses back to the original wasm module.
2234    ///
2235    /// This configuration option is `true` by default and, if enabled,
2236    /// generates the appropriate tables in compiled modules to map from native
2237    /// address back to wasm source addresses. This is used for displaying wasm
2238    /// program counters in backtraces as well as generating filenames/line
2239    /// numbers if so configured as well (and the original wasm module has DWARF
2240    /// debugging information present).
2241    pub fn generate_address_map(&mut self, generate: bool) -> &mut Self {
2242        self.tunables.generate_address_map = Some(generate);
2243        self
2244    }
2245
2246    /// Configures whether copy-on-write memory-mapped data is used to
2247    /// initialize a linear memory.
2248    ///
2249    /// Initializing linear memory via a copy-on-write mapping can drastically
2250    /// improve instantiation costs of a WebAssembly module because copying
2251    /// memory is deferred. Additionally if a page of memory is only ever read
2252    /// from WebAssembly and never written too then the same underlying page of
2253    /// data will be reused between all instantiations of a module meaning that
2254    /// if a module is instantiated many times this can lower the overall memory
2255    /// required needed to run that module.
2256    ///
2257    /// The main disadvantage of copy-on-write initialization, however, is that
2258    /// it may be possible for highly-parallel scenarios to be less scalable. If
2259    /// a page is read initially by a WebAssembly module then that page will be
2260    /// mapped to a read-only copy shared between all WebAssembly instances. If
2261    /// the same page is then written, however, then a private copy is created
2262    /// and swapped out from the read-only version. This also requires an [IPI],
2263    /// however, which can be a significant bottleneck in high-parallelism
2264    /// situations.
2265    ///
2266    /// This feature is only applicable when a WebAssembly module meets specific
2267    /// criteria to be initialized in this fashion, such as:
2268    ///
2269    /// * Only memories defined in the module can be initialized this way.
2270    /// * Data segments for memory must use statically known offsets.
2271    /// * Data segments for memory must all be in-bounds.
2272    ///
2273    /// Modules which do not meet these criteria will fall back to
2274    /// initialization of linear memory based on copying memory.
2275    ///
2276    /// This feature of Wasmtime is also platform-specific:
2277    ///
2278    /// * Linux - this feature is supported for all instances of [`Module`].
2279    ///   Modules backed by an existing mmap (such as those created by
2280    ///   [`Module::deserialize_file`]) will reuse that mmap to cow-initialize
2281    ///   memory. Other instance of [`Module`] may use the `memfd_create`
2282    ///   syscall to create an initialization image to `mmap`.
2283    /// * Unix (not Linux) - this feature is only supported when loading modules
2284    ///   from a precompiled file via [`Module::deserialize_file`] where there
2285    ///   is a file descriptor to use to map data into the process. Note that
2286    ///   the module must have been compiled with this setting enabled as well.
2287    /// * Windows - there is no support for this feature at this time. Memory
2288    ///   initialization will always copy bytes.
2289    ///
2290    /// By default this option is enabled.
2291    ///
2292    /// [`Module::deserialize_file`]: crate::Module::deserialize_file
2293    /// [`Module`]: crate::Module
2294    /// [IPI]: https://en.wikipedia.org/wiki/Inter-processor_interrupt
2295    pub fn memory_init_cow(&mut self, enable: bool) -> &mut Self {
2296        self.tunables.memory_init_cow = Some(enable);
2297        self
2298    }
2299
2300    /// A configuration option to force the usage of `memfd_create` on Linux to
2301    /// be used as the backing source for a module's initial memory image.
2302    ///
2303    /// When [`Config::memory_init_cow`] is enabled, which is enabled by
2304    /// default, module memory initialization images are taken from a module's
2305    /// original mmap if possible. If a precompiled module was loaded from disk
2306    /// this means that the disk's file is used as an mmap source for the
2307    /// initial linear memory contents. This option can be used to force, on
2308    /// Linux, that instead of using the original file on disk a new in-memory
2309    /// file is created with `memfd_create` to hold the contents of the initial
2310    /// image.
2311    ///
2312    /// This option can be used to avoid possibly loading the contents of memory
2313    /// from disk through a page fault. Instead with `memfd_create` the contents
2314    /// of memory are always in RAM, meaning that even page faults which
2315    /// initially populate a wasm linear memory will only work with RAM instead
2316    /// of ever hitting the disk that the original precompiled module is stored
2317    /// on.
2318    ///
2319    /// This option is disabled by default.
2320    pub fn force_memory_init_memfd(&mut self, enable: bool) -> &mut Self {
2321        self.force_memory_init_memfd = enable;
2322        self
2323    }
2324
2325    /// Configures whether or not a coredump should be generated and attached to
2326    /// the [`Error`](crate::Error) when a trap is raised.
2327    ///
2328    /// This option is disabled by default.
2329    #[cfg(feature = "coredump")]
2330    pub fn coredump_on_trap(&mut self, enable: bool) -> &mut Self {
2331        self.coredump_on_trap = enable;
2332        self
2333    }
2334
2335    /// Enables memory error checking for wasm programs.
2336    ///
2337    /// This option is disabled by default.
2338    ///
2339    /// # Panics
2340    ///
2341    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
2342    #[cfg(any(feature = "cranelift", feature = "winch"))]
2343    pub fn wmemcheck(&mut self, enable: bool) -> &mut Self {
2344        self.wmemcheck = enable;
2345        self.compiler_config_mut().wmemcheck = enable;
2346        self
2347    }
2348
2349    /// Configures the "guaranteed dense image size" for copy-on-write
2350    /// initialized memories.
2351    ///
2352    /// When using the [`Config::memory_init_cow`] feature to initialize memory
2353    /// efficiently (which is enabled by default), compiled modules contain an
2354    /// image of the module's initial heap. If the module has a fairly sparse
2355    /// initial heap, with just a few data segments at very different offsets,
2356    /// this could result in a large region of zero bytes in the image. In
2357    /// other words, it's not very memory-efficient.
2358    ///
2359    /// We normally use a heuristic to avoid this: if less than half
2360    /// of the initialized range (first non-zero to last non-zero
2361    /// byte) of any memory in the module has pages with nonzero
2362    /// bytes, then we avoid creating a memory image for the entire module.
2363    ///
2364    /// However, if the embedder always needs the instantiation-time efficiency
2365    /// of copy-on-write initialization, and is otherwise carefully controlling
2366    /// parameters of the modules (for example, by limiting the maximum heap
2367    /// size of the modules), then it may be desirable to ensure a memory image
2368    /// is created even if this could go against the heuristic above. Thus, we
2369    /// add another condition: there is a size of initialized data region up to
2370    /// which we *always* allow a memory image. The embedder can set this to a
2371    /// known maximum heap size if they desire to always get the benefits of
2372    /// copy-on-write images.
2373    ///
2374    /// In the future we may implement a "best of both worlds"
2375    /// solution where we have a dense image up to some limit, and
2376    /// then support a sparse list of initializers beyond that; this
2377    /// would get most of the benefit of copy-on-write and pay the incremental
2378    /// cost of eager initialization only for those bits of memory
2379    /// that are out-of-bounds. However, for now, an embedder desiring
2380    /// fast instantiation should ensure that this setting is as large
2381    /// as the maximum module initial memory content size.
2382    ///
2383    /// By default this value is 16 MiB.
2384    pub fn memory_guaranteed_dense_image_size(&mut self, size_in_bytes: u64) -> &mut Self {
2385        self.memory_guaranteed_dense_image_size = size_in_bytes;
2386        self
2387    }
2388
2389    /// Whether to enable function inlining during compilation or not.
2390    ///
2391    /// This may result in faster execution at runtime, but adds additional
2392    /// compilation time. Inlining may also enlarge the size of compiled
2393    /// artifacts (for example, the size of the result of
2394    /// [`Engine::precompile_component`]).
2395    ///
2396    /// Inlining is not supported by all of Wasmtime's compilation strategies;
2397    /// currently, it only Cranelift supports it. This setting will be ignored
2398    /// when using a compilation strategy that does not support inlining, like
2399    /// Winch.
2400    ///
2401    /// The default value for this is `Inlining::No`.
2402    pub fn compiler_inlining(&mut self, inlining: Inlining) -> &mut Self {
2403        self.tunables.inlining = Some(inlining);
2404        self
2405    }
2406
2407    /// Returns the set of features that the currently selected compiler backend
2408    /// does not support at all and may panic on.
2409    ///
2410    /// Wasmtime strives to reject unknown modules or unsupported modules with
2411    /// first-class errors instead of panics. Not all compiler backends have the
2412    /// same level of feature support on all platforms as well. This method
2413    /// returns a set of features that the currently selected compiler
2414    /// configuration is known to not support and may panic on. This acts as a
2415    /// first-level filter on incoming wasm modules/configuration to fail-fast
2416    /// instead of panicking later on.
2417    ///
2418    /// Note that if a feature is not returned here it does not mean that the
2419    /// backend fully supports the proposal. Instead that means that the backend
2420    /// doesn't ever panic on the proposal, but errors during compilation may
2421    /// still be returned. This means that features listed here are definitely
2422    /// not supported at all, but features not listed here may still be
2423    /// partially supported. For example at the time of this writing the Winch
2424    /// backend partially supports simd so it's not listed here. Winch doesn't
2425    /// fully support simd but unimplemented instructions just return errors.
2426    fn compiler_panicking_wasm_features(&self) -> WasmFeatures {
2427        // First we compute the set of features that Wasmtime itself knows;
2428        // this is a sort of "maximal set" that we invert to create a set
2429        // of features we _definitely can't support_ because wasmtime
2430        // has never heard of them.
2431        let features_known_to_wasmtime = WasmFeatures::WASM3
2432            | WasmFeatures::SHARED_EVERYTHING_THREADS
2433            | WasmFeatures::COMPONENT_MODEL
2434            | WasmFeatures::CUSTOM_PAGE_SIZES
2435            | WasmFeatures::STACK_SWITCHING
2436            | WasmFeatures::WIDE_ARITHMETIC
2437            | WasmFeatures::CM_ASYNC
2438            | WasmFeatures::CM_ASYNC_STACKFUL
2439            | WasmFeatures::CM_MORE_ASYNC_BUILTINS
2440            | WasmFeatures::CM_THREADING
2441            | WasmFeatures::CM_ERROR_CONTEXT
2442            | WasmFeatures::CM_GC
2443            | WasmFeatures::CM_MAP
2444            | WasmFeatures::CM64
2445            | WasmFeatures::CM_FIXED_LENGTH_LISTS
2446            | WasmFeatures::CM_IMPLEMENTS
2447            | WasmFeatures::CM_CANON_NAMES;
2448
2449        #[allow(unused_mut, reason = "easier to avoid #[cfg]")]
2450        let mut unsupported = !features_known_to_wasmtime;
2451
2452        #[cfg(any(feature = "cranelift", feature = "winch"))]
2453        match self.compiler_config.as_ref().and_then(|c| c.strategy) {
2454            None | Some(Strategy::Cranelift) => {
2455                // Pulley at this time fundamentally doesn't support the
2456                // `threads` proposal, notably shared memory, because Rust can't
2457                // safely implement loads/stores in the face of shared memory.
2458                // Stack switching is not implemented, either.
2459                if self.compiler_target().is_pulley() {
2460                    unsupported |= WasmFeatures::THREADS;
2461                    unsupported |= WasmFeatures::STACK_SWITCHING;
2462                }
2463
2464                use target_lexicon::*;
2465                match self.compiler_target() {
2466                    Triple {
2467                        architecture: Architecture::X86_64 | Architecture::X86_64h,
2468                        operating_system:
2469                            OperatingSystem::Linux
2470                            | OperatingSystem::MacOSX(_)
2471                            | OperatingSystem::Darwin(_),
2472                        ..
2473                    } => {
2474                        // Stack switching supported on (non-Pulley) Cranelift.
2475                    }
2476
2477                    _ => {
2478                        // On platforms other than x64 Unix-like, we don't
2479                        // support stack switching.
2480                        unsupported |= WasmFeatures::STACK_SWITCHING;
2481                    }
2482                }
2483            }
2484            Some(Strategy::Winch) => {
2485                unsupported |= WasmFeatures::GC
2486                    | WasmFeatures::FUNCTION_REFERENCES
2487                    | WasmFeatures::RELAXED_SIMD
2488                    | WasmFeatures::TAIL_CALL
2489                    | WasmFeatures::LEGACY_EXCEPTIONS
2490                    | WasmFeatures::STACK_SWITCHING;
2491
2492                match self.compiler_target().architecture {
2493                    target_lexicon::Architecture::Aarch64(_) => {
2494                        unsupported |= WasmFeatures::THREADS;
2495                    }
2496
2497                    // Winch doesn't support other non-x64 architectures at this
2498                    // time either but will return an first-class error for
2499                    // them.
2500                    _ => {}
2501                }
2502            }
2503            Some(Strategy::Auto) => unreachable!(),
2504        }
2505        unsupported
2506    }
2507
2508    /// Calculates the set of features that are enabled for this `Config`.
2509    ///
2510    /// This is a bit of a subtle function which takes into account inputs such
2511    /// as the default set of features Wasmtime has enabled, the currently
2512    /// enabled compiler, the currently enabled target, compile-time crate
2513    /// features, and explicitly configured wasm proposals. This function does
2514    /// not return a fixed set of all proposals in all cases as it's a bit more
2515    /// nuanced than that.
2516    ///
2517    /// This method internally will start with an empty set of features to
2518    /// avoid being tied to wasmparser's defaults. Next Wasmtime's set of
2519    /// default features are added to this set, some of which are conditional
2520    /// depending on crate features. Finally explicitly requested features via
2521    /// `wasm_*` methods on `Config` are applied. Everything is then validated
2522    /// later in `Config::validate`.
2523    ///
2524    /// Note that the validation later on in `Config::validate` is a crucial
2525    /// step here. The returned features here might include features unsupported
2526    /// at compile time or unsupported by the selected compiler. In that case
2527    /// `Config::validate` will present a first-class error message indicating
2528    /// what's going on, and users should in theory be able to understand "ok
2529    /// yeah that's why I can't enable that feature here".
2530    fn features(&self) -> WasmFeatures {
2531        // Start with an empty set of wasm features. This notably decouples
2532        // features in Wasmtime from features in wasmparser as the two are
2533        // generally on different timelines.
2534        let mut features = WasmFeatures::empty();
2535
2536        // Next add in all on-by-default features that Wasmtime has which are
2537        // subject to the criteria at
2538        // https://docs.wasmtime.dev/contributing-implementing-wasm-proposals.html
2539        // and https://docs.wasmtime.dev/stability-wasm-proposals.html.
2540        //
2541        // Note that the first entry here, `WASM3`, is a fixed feature set that
2542        // won't change over time in wasmparser which represents the union of
2543        // all on-by-default features in Wasmtime. Also note that this is
2544        // further refined in the conditional section below based on crate
2545        // features.
2546        features |= WasmFeatures::WASM3;
2547
2548        features |= WasmFeatures::WIDE_ARITHMETIC;
2549        // features |= WasmFeatures::YOUR_WASM_FEATURE;
2550        // ...
2551
2552        // NB: if you add a feature above this line please double-check
2553        // https://docs.wasmtime.dev/stability-wasm-proposals.html
2554        // to ensure all requirements are met and/or update the documentation
2555        // there too.
2556
2557        // Next configure some features further based on compile-time features
2558        // of the wasmtime crate itself. For example if "gc" is disabled then
2559        // `GC_TYPES` are disabled (a wasmparser pseudo-feature) as well as
2560        // exceptions, but reference-types is still available (e.g. new
2561        // encodings/types/etc).
2562        //
2563        // These features are all "on by default" in effect but dependent on
2564        // compile-time support being available.
2565        features.set(WasmFeatures::GC_TYPES, cfg!(feature = "gc"));
2566        features.set(WasmFeatures::EXCEPTIONS, cfg!(feature = "gc"));
2567        features.set(WasmFeatures::THREADS, cfg!(feature = "threads"));
2568        features.set(
2569            WasmFeatures::COMPONENT_MODEL,
2570            cfg!(feature = "component-model"),
2571        );
2572        features.set(
2573            WasmFeatures::CM_ASYNC,
2574            self.tunables
2575                .concurrency_support
2576                .unwrap_or(cfg!(feature = "component-model-async")),
2577        );
2578
2579        // Next disable any features which the current compiler/target do not
2580        // support. This handles cases where Winch, for example, doesn't
2581        // implement a feature yet but Cranelift does. Or maybe Cranelift only
2582        // supports one particular platform and not others. Things like that.
2583        features = features & !self.compiler_panicking_wasm_features();
2584
2585        // And, finally, process all explicitly enabled/disabled features on
2586        // behalf of the embedder's frobbing `Config::wasm_*`. These have the
2587        // highest priority since they were explicitly requested.
2588        debug_assert!((self.enabled_features & self.disabled_features).is_empty());
2589        features &= !self.disabled_features;
2590        features |= self.enabled_features;
2591
2592        features
2593    }
2594
2595    /// Returns the configured compiler target for this `Config`.
2596    pub(crate) fn compiler_target(&self) -> target_lexicon::Triple {
2597        // If a target is explicitly configured, always use that.
2598        if let Some(target) = self.target.clone() {
2599            return target;
2600        }
2601
2602        // If the `build.rs` script determined that this platform uses pulley by
2603        // default, then use Pulley.
2604        if cfg!(default_target_pulley) {
2605            return target_lexicon::Triple::pulley_host();
2606        }
2607
2608        // And at this point the target is for sure the host.
2609        target_lexicon::Triple::host()
2610    }
2611
2612    /// Returns `true` if any of the `gc_heap_*` tunables have been explicitly
2613    /// configured.
2614    fn any_gc_heap_tunables_configured(&self) -> bool {
2615        self.tunables.gc_heap_reservation.is_some()
2616            || self.tunables.gc_heap_guard_size.is_some()
2617            || self.tunables.gc_heap_reservation_for_growth.is_some()
2618            || self.tunables.gc_heap_may_move.is_some()
2619    }
2620
2621    pub(crate) fn validate(&self) -> Result<(Tunables, WasmFeatures)> {
2622        let features = self.features();
2623
2624        // First validate that the selected compiler backend and configuration
2625        // supports the set of `features` that are enabled. This will help
2626        // provide more first class errors instead of panics about unsupported
2627        // features and configurations.
2628        let unsupported = features & self.compiler_panicking_wasm_features();
2629        if !unsupported.is_empty() {
2630            for flag in WasmFeatures::FLAGS.iter() {
2631                if !unsupported.contains(*flag.value()) {
2632                    continue;
2633                }
2634                bail!(
2635                    "the wasm_{} feature is not supported on this compiler configuration",
2636                    flag.name().to_lowercase()
2637                );
2638            }
2639
2640            panic!("should have returned an error by now")
2641        }
2642
2643        if self.max_wasm_stack > self.async_stack_size {
2644            bail!("max_wasm_stack size cannot exceed the async_stack_size");
2645        }
2646        if self.max_wasm_stack == 0 {
2647            bail!("max_wasm_stack size cannot be zero");
2648        }
2649        if !cfg!(feature = "wmemcheck") && self.wmemcheck {
2650            bail!("wmemcheck (memory checker) was requested but is not enabled in this build");
2651        }
2652
2653        if !cfg!(feature = "gc") && features.gc_types() {
2654            bail!("support for GC was disabled at compile time")
2655        }
2656
2657        if !cfg!(feature = "gc") && features.contains(WasmFeatures::EXCEPTIONS) {
2658            bail!("exceptions support requires garbage collection (GC) to be enabled in the build");
2659        }
2660
2661        match &self.rr_config {
2662            #[cfg(feature = "rr")]
2663            RRConfig::Recording | RRConfig::Replaying => {
2664                self.validate_rr_determinism_conflicts()?;
2665            }
2666            RRConfig::None => {}
2667        };
2668
2669        let mut tunables = Tunables::default_for_target(&self.compiler_target())?;
2670
2671        // By default this is enabled with the Cargo feature, and if the feature
2672        // is missing this is disabled.
2673        tunables.concurrency_support = cfg!(feature = "component-model-async");
2674
2675        #[cfg(feature = "rr")]
2676        {
2677            tunables.recording = matches!(self.rr_config, RRConfig::Recording);
2678        }
2679
2680        // If no target is explicitly specified then further refine `tunables`
2681        // for the configuration of this host depending on what platform
2682        // features were found available at compile time. This means that anyone
2683        // cross-compiling for a customized host will need to further refine
2684        // compilation options.
2685        if self.target.is_none() {
2686            // If this platform doesn't have native signals then change some
2687            // defaults to account for that. Note that VM guards are turned off
2688            // here because that's primarily a feature of eliding
2689            // bounds-checks.
2690            if !cfg!(has_native_signals) {
2691                tunables.signals_based_traps = cfg!(has_native_signals);
2692                tunables.memory_guard_size = 0;
2693                tunables.gc_heap_guard_size = 0;
2694            }
2695
2696            // When virtual memory is not available use slightly different
2697            // defaults for tunables to be more amenable to `MallocMemory`.
2698            // Note that these can still be overridden by config options.
2699            if !cfg!(has_virtual_memory) {
2700                tunables.memory_reservation = 0;
2701                tunables.memory_reservation_for_growth = 1 << 20; // 1MB
2702                tunables.memory_init_cow = false;
2703                tunables.gc_heap_reservation = 0;
2704                tunables.gc_heap_reservation_for_growth = 1 << 20; // 1MB
2705            }
2706        }
2707
2708        // If guest-debugging is enabled, we must disable
2709        // signals-based traps. Do this before we process the user's
2710        // provided tunables settings so we can detect a conflict with
2711        // an explicit request to use signals-based traps.
2712        #[cfg(feature = "debug")]
2713        if self.tunables.debug_guest == Some(true) {
2714            tunables.signals_based_traps = false;
2715        }
2716
2717        // Inlining currently falls over with the `stack_switch` instruction.
2718        #[cfg(any(feature = "cranelift", feature = "winch"))]
2719        if features.contains(WasmFeatures::STACK_SWITCHING) {
2720            if let Some(inlining) = self.tunables.inlining
2721                && inlining != Inlining::No
2722            {
2723                bail!("cannot enable compiler inlining when stack switching is enabled");
2724            }
2725            tunables.inlining = Inlining::No;
2726        }
2727
2728        self.tunables.configure(&mut tunables);
2729
2730        // If no GC heap tunables are explicitly configured, copy the memory
2731        // tunables' configured values so that GC heaps default to the same
2732        // configuration as linear memories.
2733        if !self.any_gc_heap_tunables_configured() {
2734            tunables.gc_heap_reservation = tunables.memory_reservation;
2735            tunables.gc_heap_guard_size = tunables.memory_guard_size;
2736            tunables.gc_heap_reservation_for_growth = tunables.memory_reservation_for_growth;
2737            tunables.gc_heap_may_move = tunables.memory_may_move;
2738        }
2739
2740        // If we're going to compile with winch, we must use the winch calling convention.
2741        #[cfg(any(feature = "cranelift", feature = "winch"))]
2742        {
2743            tunables.winch_callable = self
2744                .compiler_config
2745                .as_ref()
2746                .is_some_and(|c| c.strategy == Some(Strategy::Winch));
2747        }
2748
2749        tunables.collector = if features.gc_types() {
2750            #[cfg(feature = "gc")]
2751            {
2752                use wasmtime_environ::Collector as EnvCollector;
2753                Some(match self.collector.try_not_auto()? {
2754                    Collector::DeferredReferenceCounting => EnvCollector::DeferredReferenceCounting,
2755                    Collector::Null => EnvCollector::Null,
2756                    Collector::Copying => EnvCollector::Copying,
2757                    Collector::Auto => unreachable!(),
2758                })
2759            }
2760            #[cfg(not(feature = "gc"))]
2761            bail!("cannot use GC types: the `gc` feature was disabled at compile time")
2762        } else {
2763            None
2764        };
2765
2766        if tunables.debug_guest {
2767            ensure!(
2768                cfg!(feature = "debug"),
2769                "debug instrumentation support was disabled at compile time"
2770            );
2771            ensure!(
2772                !tunables.signals_based_traps,
2773                "cannot use signals-based traps with guest debugging enabled"
2774            );
2775        }
2776
2777        // Concurrency support is required for some component model features.
2778        let requires_concurrency = WasmFeatures::CM_ASYNC
2779            | WasmFeatures::CM_MORE_ASYNC_BUILTINS
2780            | WasmFeatures::CM_ASYNC_STACKFUL
2781            | WasmFeatures::CM_THREADING
2782            | WasmFeatures::CM_ERROR_CONTEXT;
2783        if tunables.concurrency_support && !cfg!(feature = "component-model-async") {
2784            bail!(
2785                "concurrency support was requested but was not \
2786                 compiled into this build of Wasmtime"
2787            )
2788        }
2789        if !tunables.concurrency_support && features.intersects(requires_concurrency) {
2790            bail!(
2791                "concurrency support must be enabled to use the component \
2792                 model async or threading features"
2793            )
2794        }
2795
2796        // Generated adapters between components will use `ref.func` in some
2797        // async-related situations so `component-model-async` requires
2798        // `reference-types`.
2799        if features.contains(WasmFeatures::CM_ASYNC)
2800            && !features.contains(WasmFeatures::REFERENCE_TYPES)
2801        {
2802            bail!("the component-model-async feature requires the wasm reference-types proposal");
2803        }
2804
2805        // If the pooling allocator is used and GC is enabled, check that
2806        // memories and the GC heap are configured identically, since the
2807        // pooling allocator can't support differently-configured heaps.
2808        #[cfg(feature = "pooling-allocator")]
2809        if matches!(
2810            &self.allocation_strategy,
2811            InstanceAllocationStrategy::Pooling(_)
2812        ) && tunables.collector.is_some()
2813        {
2814            if tunables.memory_reservation != tunables.gc_heap_reservation {
2815                bail!(
2816                    "when using the pooling allocator with GC, `memory_reservation` ({}) \
2817                     and `gc_heap_reservation` ({}) must be the same",
2818                    tunables.memory_reservation,
2819                    tunables.gc_heap_reservation,
2820                );
2821            }
2822            if tunables.memory_guard_size != tunables.gc_heap_guard_size {
2823                bail!(
2824                    "when using the pooling allocator with GC, `memory_guard_size` ({}) \
2825                     and `gc_heap_guard_size` ({}) must be the same",
2826                    tunables.memory_guard_size,
2827                    tunables.gc_heap_guard_size,
2828                );
2829            }
2830            if tunables.memory_reservation_for_growth != tunables.gc_heap_reservation_for_growth {
2831                bail!(
2832                    "when using the pooling allocator with GC, \
2833                     `memory_reservation_for_growth` ({}) and \
2834                     `gc_heap_reservation_for_growth` ({}) must be the same",
2835                    tunables.memory_reservation_for_growth,
2836                    tunables.gc_heap_reservation_for_growth,
2837                );
2838            }
2839            if tunables.memory_may_move != tunables.gc_heap_may_move {
2840                bail!(
2841                    "when using the pooling allocator with GC, `memory_may_move` ({}) \
2842                     and `gc_heap_may_move` ({}) must be the same",
2843                    tunables.memory_may_move,
2844                    tunables.gc_heap_may_move,
2845                );
2846            }
2847        }
2848
2849        if tunables.debug_native && !tunables.debug_symbols {
2850            bail!("cannot enable native debug info while debug symbols are disabled");
2851        }
2852
2853        Ok((tunables, features))
2854    }
2855
2856    #[cfg(feature = "runtime")]
2857    pub(crate) fn build_allocator(
2858        &self,
2859        tunables: &Tunables,
2860    ) -> Result<Box<dyn InstanceAllocator + Send + Sync>> {
2861        let _ = tunables;
2862
2863        match &self.allocation_strategy {
2864            InstanceAllocationStrategy::OnDemand => {
2865                let mut _allocator = try_new::<Box<_>>(OnDemandInstanceAllocator::new(
2866                    self.mem_creator.clone(),
2867                    self.async_stack_size,
2868                    self.async_stack_zeroing,
2869                ))?;
2870                #[cfg(feature = "async")]
2871                if let Some(stack_creator) = &self.stack_creator {
2872                    _allocator.set_stack_creator(stack_creator.clone());
2873                }
2874                Ok(_allocator as _)
2875            }
2876            #[cfg(feature = "pooling-allocator")]
2877            InstanceAllocationStrategy::Pooling(config) => {
2878                let mut config = config.clone();
2879                let _ = &mut config;
2880                #[cfg(feature = "async")]
2881                {
2882                    config.stack_size = self.async_stack_size;
2883                    config.async_stack_zeroing = self.async_stack_zeroing;
2884                }
2885                let allocator = try_new::<Box<_>>(
2886                    crate::runtime::vm::PoolingInstanceAllocator::new(&config, tunables)?,
2887                )?;
2888                Ok(allocator as _)
2889            }
2890        }
2891    }
2892
2893    #[cfg(feature = "runtime")]
2894    pub(crate) fn build_gc_runtime(&self) -> Result<Option<Arc<dyn GcRuntime>>> {
2895        if !self.features().gc_types() {
2896            return Ok(None);
2897        }
2898
2899        #[cfg(not(feature = "gc"))]
2900        bail!("cannot create a GC runtime: the `gc` feature was disabled at compile time");
2901
2902        #[cfg(feature = "gc")]
2903        #[cfg_attr(
2904            not(any(feature = "gc-null", feature = "gc-drc", feature = "gc-copying")),
2905            expect(unreachable_code, reason = "definitions known to be dummy")
2906        )]
2907        {
2908            Ok(Some(match self.collector.try_not_auto()? {
2909                #[cfg(feature = "gc-drc")]
2910                Collector::DeferredReferenceCounting => {
2911                    try_new::<Arc<_>>(crate::runtime::vm::DrcCollector::default())? as _
2912                }
2913                #[cfg(not(feature = "gc-drc"))]
2914                Collector::DeferredReferenceCounting => unreachable!(),
2915
2916                #[cfg(feature = "gc-null")]
2917                Collector::Null => {
2918                    try_new::<Arc<_>>(crate::runtime::vm::NullCollector::default())? as _
2919                }
2920                #[cfg(not(feature = "gc-null"))]
2921                Collector::Null => unreachable!(),
2922
2923                #[cfg(feature = "gc-copying")]
2924                Collector::Copying => {
2925                    try_new::<Arc<_>>(crate::runtime::vm::CopyingCollector::default())? as _
2926                }
2927                #[cfg(not(feature = "gc-copying"))]
2928                Collector::Copying => unreachable!(),
2929
2930                Collector::Auto => unreachable!(),
2931            }))
2932        }
2933    }
2934
2935    #[cfg(feature = "runtime")]
2936    pub(crate) fn build_profiler(&self) -> Result<Box<dyn ProfilingAgent>> {
2937        Ok(match self.profiling_strategy {
2938            ProfilingStrategy::PerfMap => profiling_agent::new_perfmap()?,
2939            ProfilingStrategy::JitDump => profiling_agent::new_jitdump()?,
2940            ProfilingStrategy::VTune => profiling_agent::new_vtune()?,
2941            ProfilingStrategy::None => profiling_agent::new_null(),
2942            ProfilingStrategy::Pulley => profiling_agent::new_pulley()?,
2943        })
2944    }
2945
2946    #[cfg(any(feature = "cranelift", feature = "winch"))]
2947    pub(crate) fn build_compiler(
2948        mut self,
2949        tunables: &mut Tunables,
2950        features: WasmFeatures,
2951    ) -> Result<(Self, Box<dyn wasmtime_environ::Compiler>)> {
2952        let target = self.compiler_target();
2953
2954        // The target passed to the builders below is an `Option<Triple>` where
2955        // `None` represents the current host with CPU features inferred from
2956        // the host's CPU itself. The `target` above is not an `Option`, so
2957        // switch it to `None` in the case that a target wasn't explicitly
2958        // specified (which indicates no feature inference) and the target
2959        // matches the host.
2960        let target_for_builder =
2961            if self.target.is_none() && target == target_lexicon::Triple::host() {
2962                None
2963            } else {
2964                Some(target.clone())
2965            };
2966
2967        let mut compiler = match self.compiler_config_mut().strategy {
2968            #[cfg(feature = "cranelift")]
2969            Some(Strategy::Cranelift) => wasmtime_cranelift::builder(target_for_builder)?,
2970            #[cfg(not(feature = "cranelift"))]
2971            Some(Strategy::Cranelift) => bail!("cranelift support not compiled in"),
2972            #[cfg(feature = "winch")]
2973            Some(Strategy::Winch) => wasmtime_winch::builder(target_for_builder)?,
2974            #[cfg(not(feature = "winch"))]
2975            Some(Strategy::Winch) => bail!("winch support not compiled in"),
2976
2977            None | Some(Strategy::Auto) => unreachable!(),
2978        };
2979
2980        if let Some(path) = &self.compiler_config_mut().clif_dir {
2981            compiler.clif_dir(path)?;
2982        }
2983
2984        // If probestack is enabled for a target, Wasmtime will always use the
2985        // inline strategy which doesn't require us to define a `__probestack`
2986        // function or similar.
2987        self.compiler_config_mut().settings.insert(
2988            "probestack_strategy".into(),
2989            ("inline".into(), UserSpecified::No),
2990        );
2991
2992        // We enable stack probing by default on all targets.
2993        // This is required on Windows because of the way Windows
2994        // commits its stacks, but it's also a good idea on other
2995        // platforms to ensure guard pages are hit for large frame
2996        // sizes.
2997        self.compiler_config_mut()
2998            .flags
2999            .insert("enable_probestack".into(), UserSpecified::No);
3000
3001        // The current wasm multivalue implementation depends on this.
3002        // FIXME(#9510) handle this in wasmtime-cranelift instead.
3003        self.compiler_config_mut()
3004            .flags
3005            .insert("enable_multi_ret_implicit_sret".into(), UserSpecified::No);
3006
3007        if let Some(unwind_requested) = self.native_unwind_info {
3008            if !self
3009                .compiler_config_mut()
3010                .ensure_setting_unset_or_given("unwind_info", &unwind_requested.to_string())
3011            {
3012                bail!(
3013                    "incompatible settings requested for Cranelift and Wasmtime `unwind-info` settings"
3014                );
3015            }
3016        }
3017
3018        if target.operating_system == target_lexicon::OperatingSystem::Windows {
3019            if !self
3020                .compiler_config_mut()
3021                .ensure_setting_unset_or_given("unwind_info", "true")
3022            {
3023                bail!("`native_unwind_info` cannot be disabled on Windows");
3024            }
3025        }
3026
3027        // We require frame pointers for correct stack walking, which is safety
3028        // critical in the presence of reference types, and otherwise it is just
3029        // really bad developer experience to get wrong.
3030        self.compiler_config_mut().settings.insert(
3031            "preserve_frame_pointers".into(),
3032            ("true".into(), UserSpecified::No),
3033        );
3034
3035        if !tunables.signals_based_traps {
3036            let mut ok = self
3037                .compiler_config_mut()
3038                .ensure_setting_unset_or_given("enable_table_access_spectre_mitigation", "false");
3039            ok = ok
3040                && self.compiler_config_mut().ensure_setting_unset_or_given(
3041                    "enable_heap_access_spectre_mitigation",
3042                    "false",
3043                );
3044
3045            // Right now spectre-mitigated bounds checks will load from zero so
3046            // if host-based signal handlers are disabled then that's a mismatch
3047            // and doesn't work right now. Fixing this will require more thought
3048            // of how to implement the bounds check in spectre-only mode.
3049            if !ok {
3050                bail!(
3051                    "when signals-based traps are disabled then spectre \
3052                     mitigations must also be disabled"
3053                );
3054            }
3055        }
3056
3057        if features.contains(WasmFeatures::RELAXED_SIMD) && !features.contains(WasmFeatures::SIMD) {
3058            bail!("cannot disable the simd proposal but enable the relaxed simd proposal");
3059        }
3060
3061        if features.contains(WasmFeatures::STACK_SWITCHING) {
3062            use target_lexicon::OperatingSystem;
3063            let model = match target.operating_system {
3064                OperatingSystem::Windows => "update_windows_tib",
3065                OperatingSystem::Linux
3066                | OperatingSystem::MacOSX(_)
3067                | OperatingSystem::Darwin(_) => "basic",
3068                _ => bail!("stack-switching feature not supported on this platform "),
3069            };
3070
3071            if !self
3072                .compiler_config_mut()
3073                .ensure_setting_unset_or_given("stack_switch_model", model)
3074            {
3075                bail!(
3076                    "compiler option 'stack_switch_model' must be set to '{model}' on this platform"
3077                );
3078            }
3079        }
3080
3081        // Apply compiler settings and flags
3082        compiler.set_tunables(tunables.clone())?;
3083        for (k, (v, _)) in self.compiler_config_mut().settings.iter() {
3084            compiler.set(k, v)?;
3085        }
3086        for (flag, _) in self.compiler_config_mut().flags.iter() {
3087            compiler.enable(flag)?;
3088        }
3089        *tunables = compiler.tunables().cloned().unwrap();
3090
3091        #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
3092        if let Some(cache_store) = &self.compiler_config_mut().cache_store {
3093            compiler.enable_incremental_compilation(cache_store.clone())?;
3094        }
3095
3096        compiler.wmemcheck(self.compiler_config_mut().wmemcheck);
3097
3098        Ok((self, compiler.build()?))
3099    }
3100
3101    /// Internal setting for whether adapter modules for components will have
3102    /// extra WebAssembly instructions inserted performing more debug checks
3103    /// then are necessary.
3104    #[cfg(feature = "component-model")]
3105    pub fn debug_adapter_modules(&mut self, debug: bool) -> &mut Self {
3106        self.tunables.debug_adapter_modules = Some(debug);
3107        self
3108    }
3109
3110    /// Enables clif output when compiling a WebAssembly module.
3111    #[cfg(any(feature = "cranelift", feature = "winch"))]
3112    pub fn emit_clif(&mut self, path: &Path) -> &mut Self {
3113        self.compiler_config_mut().clif_dir = Some(path.to_path_buf());
3114        self
3115    }
3116
3117    /// Configures whether, when on macOS, Mach ports are used for exception
3118    /// handling instead of traditional Unix-based signal handling.
3119    ///
3120    /// WebAssembly traps in Wasmtime are implemented with native faults, for
3121    /// example a `SIGSEGV` will occur when a WebAssembly guest accesses
3122    /// out-of-bounds memory. Handling this can be configured to either use Unix
3123    /// signals or Mach ports on macOS. By default Mach ports are used.
3124    ///
3125    /// Mach ports enable Wasmtime to work by default with foreign
3126    /// error-handling systems such as breakpad which also use Mach ports to
3127    /// handle signals. In this situation Wasmtime will continue to handle guest
3128    /// faults gracefully while any non-guest faults will get forwarded to
3129    /// process-level handlers such as breakpad. Some more background on this
3130    /// can be found in #2456.
3131    ///
3132    /// A downside of using mach ports, however, is that they don't interact
3133    /// well with `fork()`. Forking a Wasmtime process on macOS will produce a
3134    /// child process that cannot successfully run WebAssembly. In this
3135    /// situation traditional Unix signal handling should be used as that's
3136    /// inherited and works across forks.
3137    ///
3138    /// If your embedding wants to use a custom error handler which leverages
3139    /// Mach ports and you additionally wish to `fork()` the process and use
3140    /// Wasmtime in the child process that's not currently possible. Please
3141    /// reach out to us if you're in this bucket!
3142    ///
3143    /// This option defaults to `true`, using Mach ports by default.
3144    pub fn macos_use_mach_ports(&mut self, mach_ports: bool) -> &mut Self {
3145        self.macos_use_mach_ports = mach_ports;
3146        self
3147    }
3148
3149    /// Configures an embedder-provided function, `detect`, which is used to
3150    /// determine if an ISA-specific feature is available on the current host.
3151    ///
3152    /// This function is used to verify that any features enabled for a compiler
3153    /// backend, such as AVX support on x86\_64, are also available on the host.
3154    /// It is undefined behavior to execute an AVX instruction on a host that
3155    /// doesn't support AVX instructions, for example.
3156    ///
3157    /// When the `std` feature is active on this crate then this function is
3158    /// configured to a default implementation that uses the standard library's
3159    /// feature detection. When the `std` feature is disabled then there is no
3160    /// default available and this method must be called to configure a feature
3161    /// probing function.
3162    ///
3163    /// The `detect` function provided is given a string name of an ISA feature.
3164    /// The function should then return:
3165    ///
3166    /// * `Some(true)` - indicates that the feature was found on the host and it
3167    ///   is supported.
3168    /// * `Some(false)` - the feature name was recognized but it was not
3169    ///   detected on the host, for example the CPU is too old.
3170    /// * `None` - the feature name was not recognized and it's not known
3171    ///   whether it's on the host or not.
3172    ///
3173    /// Feature names passed to `detect` match the same feature name used in the
3174    /// Rust standard library. For example `"sse4.2"` is used on x86\_64.
3175    ///
3176    /// # Unsafety
3177    ///
3178    /// This function is `unsafe` because it is undefined behavior to execute
3179    /// instructions that a host does not support. This means that the result of
3180    /// `detect` must be correct for memory safe execution at runtime.
3181    pub unsafe fn detect_host_feature(&mut self, detect: fn(&str) -> Option<bool>) -> &mut Self {
3182        self.detect_host_feature = Some(detect);
3183        self
3184    }
3185
3186    /// Configures Wasmtime to not use signals-based trap handlers, for example
3187    /// disables `SIGILL` and `SIGSEGV` handler registration on Unix platforms.
3188    ///
3189    /// > **Note:** this option has important performance ramifications, be sure
3190    /// > to understand the implications. Wasm programs have been measured to
3191    /// > run up to 2x slower when signals-based traps are disabled.
3192    ///
3193    /// Wasmtime will by default leverage signals-based trap handlers (or the
3194    /// platform equivalent, for example "vectored exception handlers" on
3195    /// Windows) to make generated code more efficient. For example, when
3196    /// Wasmtime can use signals-based traps, it can elide explicit bounds
3197    /// checks for Wasm linear memory accesses, instead relying on virtual
3198    /// memory guard pages to raise a `SIGSEGV` (on Unix) for out-of-bounds
3199    /// accesses, which Wasmtime's runtime then catches and handles. Another
3200    /// example is divide-by-zero: with signals-based traps, Wasmtime can let
3201    /// the hardware raise a trap when the divisor is zero. Without
3202    /// signals-based traps, Wasmtime must explicitly emit additional
3203    /// instructions to check for zero and conditionally branch to a trapping
3204    /// code path.
3205    ///
3206    /// Some environments however may not have access to signal handlers. For
3207    /// example embedded scenarios may not support virtual memory. Other
3208    /// environments where Wasmtime is embedded within the surrounding
3209    /// environment may require that new signal handlers aren't registered due
3210    /// to the global nature of signal handlers. This option exists to disable
3211    /// the signal handler registration when required for these scenarios.
3212    ///
3213    /// When signals-based trap handlers are disabled, then Wasmtime and its
3214    /// generated code will *never* rely on segfaults or other
3215    /// signals. Generated code will be slower because bounds must be explicitly
3216    /// checked along with other conditions like division by zero.
3217    ///
3218    /// The following additional factors can also affect Wasmtime's ability to
3219    /// elide explicit bounds checks and leverage signals-based traps:
3220    ///
3221    /// * The [`Config::memory_reservation`] and [`Config::memory_guard_size`]
3222    ///   settings
3223    /// * The index type of the linear memory (e.g. 32-bit or 64-bit)
3224    /// * The page size of the linear memory
3225    ///
3226    /// When this option is disabled, the
3227    /// `enable_heap_access_spectre_mitigation` and
3228    /// `enable_table_access_spectre_mitigation` Cranelift settings must also be
3229    /// disabled. This means that generated code must have spectre mitigations
3230    /// disabled. This is because spectre mitigations rely on faults from
3231    /// loading from the null address to implement bounds checks.
3232    ///
3233    /// This option defaults to `true`: signals-based trap handlers are enabled
3234    /// by default.
3235    ///
3236    /// > **Note:** Disabling this option is not compatible with the Winch
3237    /// > compiler.
3238    pub fn signals_based_traps(&mut self, enable: bool) -> &mut Self {
3239        self.tunables.signals_based_traps = Some(enable);
3240        self
3241    }
3242
3243    /// Enable/disable GC support in Wasmtime entirely.
3244    ///
3245    /// This flag can be used to gate whether GC infrastructure is enabled or
3246    /// initialized in Wasmtime at all. Wasmtime's GC implementation is required
3247    /// for the [`Self::wasm_gc`] proposal, [`Self::wasm_function_references`],
3248    /// and [`Self::wasm_exceptions`] at this time. None of those proposal can
3249    /// be enabled without also having this option enabled.
3250    ///
3251    /// This option defaults to whether the crate `gc` feature is enabled or
3252    /// not.
3253    pub fn gc_support(&mut self, enable: bool) -> &mut Self {
3254        self.wasm_features(WasmFeatures::GC_TYPES, enable)
3255    }
3256
3257    /// Explicitly indicate or not whether the host is using a hardware float
3258    /// ABI on x86 targets.
3259    ///
3260    /// This configuration option is only applicable on the
3261    /// `x86_64-unknown-none` Rust target and has no effect on other host
3262    /// targets. The `x86_64-unknown-none` Rust target does not support hardware
3263    /// floats by default and uses a "soft float" implementation and ABI. This
3264    /// means that `f32`, for example, is passed in a general-purpose register
3265    /// between functions instead of a floating-point register. This does not
3266    /// match Cranelift's ABI for `f32` where it's passed in floating-point
3267    /// registers.  Cranelift does not have support for a "soft float"
3268    /// implementation where all floating-point operations are lowered to
3269    /// libcalls.
3270    ///
3271    /// This means that for the `x86_64-unknown-none` target the ABI between
3272    /// Wasmtime's libcalls and the host is incompatible when floats are used.
3273    /// This further means that, by default, Wasmtime is unable to load native
3274    /// code when compiled to the `x86_64-unknown-none` target. The purpose of
3275    /// this option is to explicitly allow loading code and bypass this check.
3276    ///
3277    /// Setting this configuration option to `true` indicates that either:
3278    /// (a) the Rust target is compiled with the hard-float ABI manually via
3279    /// `-Zbuild-std` and a custom target JSON configuration, or (b) sufficient
3280    /// x86 features have been enabled in the compiler such that float libcalls
3281    /// will not be used in Wasmtime. For (a) there is no way in Rust at this
3282    /// time to detect whether a hard-float or soft-float ABI is in use on
3283    /// stable Rust, so this manual opt-in is required. For (b) the only
3284    /// instance where Wasmtime passes a floating-point value in a register
3285    /// between the host and compiled wasm code is with libcalls.
3286    ///
3287    /// Float-based libcalls are only used when the compilation target for a
3288    /// wasm module has insufficient target features enabled for native
3289    /// support. For example SSE4.1 is required for the `f32.ceil` WebAssembly
3290    /// instruction to be compiled to a native instruction. If SSE4.1 is not
3291    /// enabled then `f32.ceil` is translated to a "libcall" which is
3292    /// implemented on the host. Float-based libcalls can be avoided with
3293    /// sufficient target features enabled, for example:
3294    ///
3295    /// * `self.cranelift_flag_enable("has_sse3")`
3296    /// * `self.cranelift_flag_enable("has_ssse3")`
3297    /// * `self.cranelift_flag_enable("has_sse41")`
3298    /// * `self.cranelift_flag_enable("has_sse42")`
3299    /// * `self.cranelift_flag_enable("has_fma")`
3300    ///
3301    /// Note that when these features are enabled Wasmtime will perform a
3302    /// runtime check to determine that the host actually has the feature
3303    /// present.
3304    ///
3305    /// For some more discussion see [#11506].
3306    ///
3307    /// [#11506]: https://github.com/bytecodealliance/wasmtime/issues/11506
3308    ///
3309    /// # Safety
3310    ///
3311    /// This method is not safe because it cannot be detected in Rust right now
3312    /// whether the host is compiled with a soft or hard float ABI. Additionally
3313    /// if the host is compiled with a soft float ABI disabling this check does
3314    /// not ensure that the wasm module in question has zero usage of floats
3315    /// in the boundary to the host.
3316    ///
3317    /// Safely using this method requires one of:
3318    ///
3319    /// * The host target is compiled to use hardware floats.
3320    /// * Wasm modules loaded are compiled with enough x86 Cranelift features
3321    ///   enabled to avoid float-related hostcalls.
3322    pub unsafe fn x86_float_abi_ok(&mut self, enable: bool) -> &mut Self {
3323        self.x86_float_abi_ok = Some(enable);
3324        self
3325    }
3326
3327    /// Enable or disable the ability to create a
3328    /// [`SharedMemory`](crate::SharedMemory).
3329    ///
3330    /// The WebAssembly threads proposal, configured by [`Config::wasm_threads`]
3331    /// is on-by-default but there are enough deficiencies in Wasmtime's
3332    /// implementation and API integration that creation of a shared memory is
3333    /// disabled by default. This configuration knob can be used to enable this.
3334    ///
3335    /// When enabling this method be aware that wasm threads are, at this time,
3336    /// a [tier 2
3337    /// feature](https://docs.wasmtime.dev/stability-tiers.html#tier-2) in
3338    /// Wasmtime meaning that it will not receive security updates or fixes to
3339    /// historical releases. Additionally security CVEs will not be issued for
3340    /// bugs in the implementation.
3341    ///
3342    /// This option is `false` by default.
3343    pub fn shared_memory(&mut self, enable: bool) -> &mut Self {
3344        self.shared_memory = enable;
3345        self
3346    }
3347
3348    /// Specifies whether support for concurrent execution of WebAssembly is
3349    /// supported within this store.
3350    ///
3351    /// This configuration option affects whether runtime data structures are
3352    /// initialized within a `Store` on creation to support concurrent execution
3353    /// of WebAssembly guests. This is primarily applicable to the
3354    /// [`Config::wasm_component_model_async`] configuration which is the first
3355    /// time Wasmtime has supported concurrent execution of guests. This
3356    /// configuration option, for example, enables usage of
3357    /// [`Store::run_concurrent`], [`Func::call_concurrent`], [`StreamReader`],
3358    /// etc.
3359    ///
3360    /// This configuration option can be manually disabled to avoid initializing
3361    /// data structures in the [`Store`] related to concurrent execution. When
3362    /// this option is disabled then APIs related to concurrency will all fail
3363    /// with a panic. For example [`Store::run_concurrent`] will panic, creating
3364    /// a [`StreamReader`] will panic, etc.
3365    ///
3366    /// The value of this option additionally affects whether a [`Config`] is
3367    /// valid and the default set of enabled WebAssembly features. If this
3368    /// option is disabled then component-model features related to concurrency
3369    /// will all be disabled. If this option is enabled, then the options will
3370    /// retain their normal defaults. It is not valid to create a [`Config`]
3371    /// with component-model-async explicitly enabled and this option explicitly
3372    /// disabled, however.
3373    ///
3374    /// This option defaults to `true`.
3375    ///
3376    /// [`Store`]: crate::Store
3377    /// [`Store::run_concurrent`]: crate::Store::run_concurrent
3378    /// [`Func::call_concurrent`]: crate::component::Func::call_concurrent
3379    /// [`StreamReader`]: crate::component::StreamReader
3380    pub fn concurrency_support(&mut self, enable: bool) -> &mut Self {
3381        self.tunables.concurrency_support = Some(enable);
3382        self
3383    }
3384
3385    /// Validate if the current configuration has conflicting overrides that prevent
3386    /// execution determinism. Returns an error if a conflict exists.
3387    ///
3388    /// Note: Keep this in sync with [`Config::enforce_determinism`].
3389    #[inline]
3390    #[cfg(feature = "rr")]
3391    pub(crate) fn validate_rr_determinism_conflicts(&self) -> Result<()> {
3392        if let Some(v) = self.tunables.relaxed_simd_deterministic {
3393            if v == false {
3394                bail!("Relaxed deterministic SIMD cannot be disabled when determinism is enforced");
3395            }
3396        }
3397        #[cfg(any(feature = "cranelift", feature = "winch"))]
3398        if let Some((v, _)) = self
3399            .compiler_config
3400            .as_ref()
3401            .and_then(|c| c.settings.get("enable_nan_canonicalization"))
3402        {
3403            if v != "true" {
3404                bail!("NaN canonicalization cannot be disabled when determinism is enforced");
3405            }
3406        }
3407        Ok(())
3408    }
3409
3410    /// Enable execution trace recording or replaying to the configuration.
3411    ///
3412    /// When either recording/replaying are enabled, validation fails if settings
3413    /// that control determinism are not set appropriately. In particular, RR requires
3414    /// doing the following:
3415    /// * Enabling NaN canonicalization with [`Config::cranelift_nan_canonicalization`].
3416    /// * Enabling deterministic relaxed SIMD with [`Config::relaxed_simd_deterministic`].
3417    #[inline]
3418    pub fn rr(&mut self, cfg: RRConfig) -> &mut Self {
3419        self.rr_config = cfg;
3420        self
3421    }
3422
3423    /// Whether or not trap metadata is generated in compiled wasms for internal
3424    /// asserts in the compiled code itself.
3425    ///
3426    /// Wasmtime inserts metadata within compiled artifacts which contain a
3427    /// table of known trap codes for all instructions. If a trap via a signal
3428    /// happens, and it's not listed in these tables, then that's considered a
3429    /// fatal bug that crashes the process. This option controls whether trap
3430    /// codes are inserted into metadata for internal asserts as part of
3431    /// Wasmtime's translation process. These internal asserts should never be
3432    /// triggered, but if they are then the process dies with a signal.
3433    ///
3434    /// Inserting trap metadata into compiled artifacts can take extra space in
3435    /// the final artifact. The trap tables for the artifact will be larger as
3436    /// they contain more trap codes to contain.
3437    ///
3438    /// This is intended as a debugging option and is set to `false` by
3439    /// default.
3440    pub fn metadata_for_internal_asserts(&mut self, enable: bool) -> &mut Self {
3441        self.tunables.metadata_for_internal_asserts = Some(enable);
3442        self
3443    }
3444
3445    /// Whether or not trap metadata is generated in compiled wasms for
3446    /// detection of corruption in the GC heap.
3447    ///
3448    /// For more information about what metadata is in this scenario, see
3449    /// [`Config::metadata_for_internal_asserts`]. Note, though, that this
3450    /// option is enabled by default unlike internal asserts. This is intended
3451    /// as a defense-in-depth option for generated code in the face of GC heap
3452    /// corruption. If the GC heap is corrupted and is detected then the
3453    /// trapping instruction will be gracefully handled and delivered to the
3454    /// embedder. Otherwise if this option were set to `false` then the process
3455    /// would be aborted due to a signal.
3456    pub fn metadata_for_gc_heap_corruption(&mut self, enable: bool) -> &mut Self {
3457        self.tunables.metadata_for_gc_heap_corruption = Some(enable);
3458        self
3459    }
3460}
3461
3462impl Default for Config {
3463    fn default() -> Config {
3464        Config::new()
3465    }
3466}
3467
3468impl fmt::Debug for Config {
3469    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3470        let mut f = f.debug_struct("Config");
3471
3472        // Not every flag in WasmFeatures can be enabled as part of creating
3473        // a Config. This impl gives a complete picture of all WasmFeatures
3474        // enabled, and doesn't require maintenance by hand (which has become out
3475        // of date in the past), at the cost of possible confusion for why
3476        // a flag in this set doesn't have a Config setter.
3477        let features = self.features();
3478        for flag in WasmFeatures::FLAGS.iter() {
3479            f.field(
3480                &format!("wasm_{}", flag.name().to_lowercase()),
3481                &features.contains(*flag.value()),
3482            );
3483        }
3484
3485        f.field("parallel_compilation", &self.parallel_compilation);
3486        #[cfg(any(feature = "cranelift", feature = "winch"))]
3487        {
3488            f.field("compiler_config", &self.compiler_config);
3489        }
3490
3491        self.tunables.format(&mut f);
3492        f.finish()
3493    }
3494}
3495
3496/// Possible Compilation strategies for a wasm module.
3497///
3498/// This is used as an argument to the [`Config::strategy`] method.
3499#[non_exhaustive]
3500#[derive(PartialEq, Eq, Clone, Debug, Copy)]
3501pub enum Strategy {
3502    /// An indicator that the compilation strategy should be automatically
3503    /// selected.
3504    ///
3505    /// This is generally what you want for most projects and indicates that the
3506    /// `wasmtime` crate itself should make the decision about what the best
3507    /// code generator for a wasm module is.
3508    ///
3509    /// Currently this always defaults to Cranelift, but the default value may
3510    /// change over time.
3511    Auto,
3512
3513    /// Currently the default backend, Cranelift aims to be a reasonably fast
3514    /// code generator which generates high quality machine code.
3515    Cranelift,
3516
3517    /// A low-latency baseline compiler for WebAssembly.
3518    /// For more details regarding ISA support and Wasm proposals support
3519    /// see <https://docs.wasmtime.dev/stability-tiers.html#current-tier-status>
3520    Winch,
3521}
3522
3523#[cfg(any(feature = "winch", feature = "cranelift"))]
3524impl Strategy {
3525    fn not_auto(&self) -> Option<Strategy> {
3526        match self {
3527            Strategy::Auto => {
3528                if cfg!(feature = "cranelift") {
3529                    Some(Strategy::Cranelift)
3530                } else if cfg!(feature = "winch") {
3531                    Some(Strategy::Winch)
3532                } else {
3533                    None
3534                }
3535            }
3536            other => Some(*other),
3537        }
3538    }
3539}
3540
3541/// Possible garbage collector implementations for Wasm.
3542///
3543/// This is used as an argument to the [`Config::collector`] method.
3544///
3545/// The properties of Wasmtime's available collectors are summarized in the
3546/// following table:
3547///
3548/// | Collector                   | Collects Garbage[^1]  | Latency[^2] | Throughput[^3] | Allocation Speed[^4] | Heap Utilization[^5] |
3549/// |-----------------------------|-----------------------|-------------|----------------|----------------------|----------------------|
3550/// | `Copying`                   | Yes, including cycles | 🙁         | 🙂             | 🙂                   | 🙁                  |
3551/// | `DeferredReferenceCounting` | Yes, but not cycles   | 🙂         | 🙁             | 😐                   | 😐                  |
3552/// | `Null`                      | No                    | 🙂         | 🙂             | 🙂                   | 🙂                  |
3553///
3554/// [^1]: Whether or not the collector is capable of collecting garbage and cyclic garbage.
3555///
3556/// [^2]: How long the Wasm program is paused during garbage
3557///       collections. Shorter is better. In general, better latency implies
3558///       worse throughput and vice versa.
3559///
3560/// [^3]: How fast the Wasm program runs when using this collector. Roughly
3561///       equivalent to the number of Wasm instructions executed per
3562///       second. Faster is better. In general, better throughput implies worse
3563///       latency and vice versa.
3564///
3565/// [^4]: How fast can individual objects be allocated?
3566///
3567/// [^5]: How many objects can the collector fit into N bytes of memory? That
3568///       is, how much space for bookkeeping and metadata does this collector
3569///       require? Less space taken up by metadata means more space for
3570///       additional objects. Reference counts are larger than mark bits and
3571///       free lists are larger than bump pointers, for example.
3572#[non_exhaustive]
3573#[derive(PartialEq, Eq, Clone, Debug, Copy)]
3574pub enum Collector {
3575    /// An indicator that the garbage collector should be automatically
3576    /// selected.
3577    ///
3578    /// This is generally what you want for most projects and indicates that the
3579    /// `wasmtime` crate itself should make the decision about what the best
3580    /// collector to use is.
3581    ///
3582    /// Currently this always defaults to the copying collector, but the default
3583    /// value may change over time.
3584    Auto,
3585
3586    /// The deferred reference-counting collector.
3587    ///
3588    /// A reference-counting collector, generally trading improved latency for
3589    /// worsened throughput. However, to avoid the largest overheads of
3590    /// reference counting, it avoids manipulating reference counts for Wasm
3591    /// objects on the stack. Instead, it will hold a reference count for an
3592    /// over-approximation of all objects that are currently on the stack, trace
3593    /// the stack during collection to find the precise set of on-stack roots,
3594    /// and decrement the reference count of any object that was in the
3595    /// over-approximation but not the precise set. This improves throughput,
3596    /// compared to "pure" reference counting, by performing many fewer
3597    /// refcount-increment and -decrement operations. The cost is the increased
3598    /// latency associated with tracing the stack.
3599    ///
3600    /// This collector cannot currently collect cycles; they will leak until the
3601    /// GC heap's store is dropped.
3602    DeferredReferenceCounting,
3603
3604    /// The null collector.
3605    ///
3606    /// This collector does not actually collect any garbage. It simply
3607    /// allocates objects until it runs out of memory, at which point further
3608    /// objects allocation attempts will trap.
3609    ///
3610    /// This collector is useful for incredibly short-running Wasm instances
3611    /// where additionally you would rather halt an over-allocating Wasm program
3612    /// than spend time collecting its garbage to allow it to keep running. It
3613    /// is also useful for measuring the overheads associated with other
3614    /// collectors, as this collector imposes as close to zero throughput and
3615    /// latency overhead as possible.
3616    Null,
3617
3618    /// The copying collector.
3619    ///
3620    /// A tracing collector that splits the GC heap in half, bump-allocates
3621    /// objects in one half until it fills up, and then does a GC and copies
3622    /// live objects into the other half, and repeats the process. It has fast
3623    /// allocation, collects cyclic garbage, and good collection throughput,
3624    /// however it suffers from poor latency due to its stop-the-world
3625    /// collections and poor heap utilization due to only using half the GC
3626    /// heap's full capacity at any given time.
3627    ///
3628    /// Note that this collector is still under construction and is not yet
3629    /// functional.
3630    Copying,
3631}
3632
3633impl Default for Collector {
3634    fn default() -> Collector {
3635        Collector::Auto
3636    }
3637}
3638
3639#[cfg(feature = "gc")]
3640impl Collector {
3641    fn not_auto(&self) -> Option<Collector> {
3642        match self {
3643            Collector::Auto => {
3644                if cfg!(feature = "gc-copying") {
3645                    Some(Collector::Copying)
3646                } else if cfg!(feature = "gc-drc") {
3647                    Some(Collector::DeferredReferenceCounting)
3648                } else if cfg!(feature = "gc-null") {
3649                    Some(Collector::Null)
3650                } else {
3651                    None
3652                }
3653            }
3654            other => Some(*other),
3655        }
3656    }
3657
3658    fn try_not_auto(&self) -> Result<Self> {
3659        match self.not_auto() {
3660            #[cfg(feature = "gc-drc")]
3661            Some(c @ Collector::DeferredReferenceCounting) => Ok(c),
3662            #[cfg(not(feature = "gc-drc"))]
3663            Some(Collector::DeferredReferenceCounting) => bail!(
3664                "cannot create an engine using the deferred reference-counting \
3665                 collector because the `gc-drc` feature was not enabled at \
3666                 compile time",
3667            ),
3668
3669            #[cfg(feature = "gc-null")]
3670            Some(c @ Collector::Null) => Ok(c),
3671            #[cfg(not(feature = "gc-null"))]
3672            Some(Collector::Null) => bail!(
3673                "cannot create an engine using the null collector because \
3674                 the `gc-null` feature was not enabled at compile time",
3675            ),
3676
3677            #[cfg(feature = "gc-copying")]
3678            Some(c @ Collector::Copying) => Ok(c),
3679            #[cfg(not(feature = "gc-copying"))]
3680            Some(Collector::Copying) => bail!(
3681                "cannot create an engine using the copying collector because \
3682                 the `gc-copying` feature was not enabled at compile time",
3683            ),
3684
3685            Some(Collector::Auto) => unreachable!(),
3686
3687            None => bail!(
3688                "cannot create an engine with GC support when none of the \
3689                 collectors are available; enable one of the following \
3690                 features: `gc-drc`, `gc-null`, `gc-copying`",
3691            ),
3692        }
3693    }
3694}
3695
3696/// Possible optimization levels for the Cranelift codegen backend.
3697#[non_exhaustive]
3698#[derive(Copy, Clone, Debug, Eq, PartialEq)]
3699pub enum OptLevel {
3700    /// No optimizations performed, minimizes compilation time by disabling most
3701    /// optimizations.
3702    None,
3703    /// Generates the fastest possible code, but may take longer.
3704    Speed,
3705    /// Similar to `speed`, but also performs transformations aimed at reducing
3706    /// code size.
3707    SpeedAndSize,
3708}
3709
3710/// Possible register allocator algorithms for the Cranelift codegen backend.
3711#[non_exhaustive]
3712#[derive(Copy, Clone, Debug, Eq, PartialEq)]
3713pub enum RegallocAlgorithm {
3714    /// Generates the fastest possible code, but may take longer.
3715    ///
3716    /// This algorithm performs "backtracking", which means that it may
3717    /// undo its earlier work and retry as it discovers conflicts. This
3718    /// results in better register utilization, producing fewer spills
3719    /// and moves, but can cause super-linear compile runtime.
3720    Backtracking,
3721    /// Generates acceptable code very quickly.
3722    ///
3723    /// This algorithm performs a single pass through the code,
3724    /// guaranteed to work in linear time.  (Note that the rest of
3725    /// Cranelift is not necessarily guaranteed to run in linear time,
3726    /// however.) It cannot undo earlier decisions, however, and it
3727    /// cannot foresee constraints or issues that may occur further
3728    /// ahead in the code, so the code may have more spills and moves as
3729    /// a result.
3730    ///
3731    /// > **Note**: This algorithm is not yet production-ready and has
3732    /// > historically had known problems. It is not recommended to enable this
3733    /// > algorithm for security-sensitive applications and the Wasmtime project
3734    /// > does not consider this configuration option for issuing security
3735    /// > advisories at this time.
3736    SinglePass,
3737}
3738
3739/// Select which profiling technique to support.
3740#[derive(Debug, Clone, Copy, PartialEq)]
3741pub enum ProfilingStrategy {
3742    /// No profiler support.
3743    None,
3744
3745    /// Collect function name information as the "perf map" file format, used with `perf` on Linux.
3746    PerfMap,
3747
3748    /// Collect profiling info for "jitdump" file format, used with `perf` on
3749    /// Linux.
3750    JitDump,
3751
3752    /// Collect profiling info using the "ittapi", used with `VTune` on Linux.
3753    VTune,
3754
3755    /// Support for profiling Pulley, Wasmtime's interpreter. Note that enabling
3756    /// this at runtime requires enabling the `profile-pulley` Cargo feature at
3757    /// compile time.
3758    Pulley,
3759}
3760
3761/// Select how wasm backtrace detailed information is handled.
3762#[derive(Debug, Clone, Copy)]
3763pub enum WasmBacktraceDetails {
3764    /// Support is unconditionally enabled and wasmtime will parse and read
3765    /// debug information.
3766    Enable,
3767
3768    /// Support is disabled, and wasmtime will not parse debug information for
3769    /// backtrace details.
3770    Disable,
3771
3772    /// Support for backtrace details is conditional on the
3773    /// `WASMTIME_BACKTRACE_DETAILS` environment variable.
3774    Environment,
3775}
3776
3777/// Describe the tri-state configuration of keys such as MPK or PAGEMAP_SCAN.
3778#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3779pub enum Enabled {
3780    /// Enable this feature if it's detected on the host system, otherwise leave
3781    /// it disabled.
3782    Auto,
3783    /// Enable this feature and fail configuration if the feature is not
3784    /// detected on the host system.
3785    Yes,
3786    /// Do not enable this feature, even if the host system supports it.
3787    No,
3788}
3789
3790/// Configuration options used with [`InstanceAllocationStrategy::Pooling`] to
3791/// change the behavior of the pooling instance allocator.
3792///
3793/// This structure has a builder-style API in the same manner as [`Config`] and
3794/// is configured with [`Config::allocation_strategy`].
3795///
3796/// Note that usage of the pooling allocator does not affect compiled
3797/// WebAssembly code. Compiled `*.cwasm` files, for example, are usable both
3798/// with and without the pooling allocator.
3799///
3800/// ## Advantages of Pooled Allocation
3801///
3802/// The main benefit of the pooling allocator is to make WebAssembly
3803/// instantiation both faster and more scalable in terms of parallelism.
3804/// Allocation is faster because virtual memory is already configured and ready
3805/// to go within the pool, there's no need to [`mmap`] (for example on Unix) a
3806/// new region and configure it with guard pages. By avoiding [`mmap`] this
3807/// avoids whole-process virtual memory locks which can improve scalability and
3808/// performance through avoiding this.
3809///
3810/// Additionally with pooled allocation it's possible to create "affine slots"
3811/// to a particular WebAssembly module or component over time. For example if
3812/// the same module is multiple times over time the pooling allocator will, by
3813/// default, attempt to reuse the same slot. This mean that the slot has been
3814/// pre-configured and can retain virtual memory mappings for a copy-on-write
3815/// image, for example (see [`Config::memory_init_cow`] for more information.
3816/// This means that in a steady state instance deallocation is a single
3817/// [`madvise`] to reset linear memory to its original contents followed by a
3818/// single (optional) [`mprotect`] during the next instantiation to shrink
3819/// memory back to its original size. Compared to non-pooled allocation this
3820/// avoids the need to [`mmap`] a new region of memory, [`munmap`] it, and
3821/// [`mprotect`] regions too.
3822///
3823/// Another benefit of pooled allocation is that it's possible to configure
3824/// things such that no virtual memory management is required at all in a steady
3825/// state. For example a pooling allocator can be configured with:
3826///
3827/// * [`Config::memory_init_cow`] disabled
3828/// * [`Config::memory_guard_size`] disabled
3829/// * [`Config::memory_reservation`] shrunk to minimal size
3830/// * [`PoolingAllocationConfig::table_keep_resident`] sufficiently large
3831/// * [`PoolingAllocationConfig::linear_memory_keep_resident`] sufficiently large
3832///
3833/// With all these options in place no virtual memory tricks are used at all and
3834/// everything is manually managed by Wasmtime (for example resetting memory is
3835/// a `memset(0)`). This is not as fast in a single-threaded scenario but can
3836/// provide benefits in high-parallelism situations as no virtual memory locks
3837/// or IPIs need happen.
3838///
3839/// ## Disadvantages of Pooled Allocation
3840///
3841/// Despite the above advantages to instantiation performance the pooling
3842/// allocator is not enabled by default in Wasmtime. One reason is that the
3843/// performance advantages are not necessarily portable, for example while the
3844/// pooling allocator works on Windows it has not been tuned for performance on
3845/// Windows in the same way it has on Linux.
3846///
3847/// Additionally the main cost of the pooling allocator is that it requires a
3848/// very large reservation of virtual memory (on the order of most of the
3849/// addressable virtual address space). WebAssembly 32-bit linear memories in
3850/// Wasmtime are, by default 4G address space reservations with a small guard
3851/// region both before and after the linear memory. Memories in the pooling
3852/// allocator are contiguous which means that we only need a guard after linear
3853/// memory because the previous linear memory's slot post-guard is our own
3854/// pre-guard. This means that, by default, the pooling allocator uses roughly
3855/// 4G of virtual memory per WebAssembly linear memory slot. 4G of virtual
3856/// memory is 32 bits of a 64-bit address. Many 64-bit systems can only
3857/// actually use 48-bit addresses by default (although this can be extended on
3858/// architectures nowadays too), and of those 48 bits one of them is reserved
3859/// to indicate kernel-vs-userspace. This leaves 47-32=15 bits left,
3860/// meaning you can only have at most 32k slots of linear memories on many
3861/// systems by default. This is a relatively small number and shows how the
3862/// pooling allocator can quickly exhaust all of virtual memory.
3863///
3864/// Another disadvantage of the pooling allocator is that it may keep memory
3865/// alive when nothing is using it. A previously used slot for an instance might
3866/// have paged-in memory that will not get paged out until the
3867/// [`Engine`] owning the pooling allocator is dropped. While
3868/// suitable for some applications this behavior may not be suitable for all
3869/// applications.
3870///
3871/// Finally the last disadvantage of the pooling allocator is that the
3872/// configuration values for the maximum number of instances, memories, tables,
3873/// etc, must all be fixed up-front. There's not always a clear answer as to
3874/// what these values should be so not all applications may be able to work
3875/// with this constraint.
3876///
3877/// [`madvise`]: https://man7.org/linux/man-pages/man2/madvise.2.html
3878/// [`mprotect`]: https://man7.org/linux/man-pages/man2/mprotect.2.html
3879/// [`mmap`]: https://man7.org/linux/man-pages/man2/mmap.2.html
3880/// [`munmap`]: https://man7.org/linux/man-pages/man2/munmap.2.html
3881#[derive(Debug, Clone)]
3882pub struct PoolingAllocationConfig {
3883    /// See `PoolingAllocatorConfig::max_unused_warm_slots` in `wasmtime`
3884    pub(crate) max_unused_warm_slots: u32,
3885    /// The target number of decommits to do per batch. This is not precise, as
3886    /// we can queue up decommits at times when we aren't prepared to
3887    /// immediately flush them, and so we may go over this target size
3888    /// occasionally.
3889    pub(crate) decommit_batch_size: usize,
3890    /// The size, in bytes, of async stacks to allocate (not including the guard
3891    /// page).
3892    #[cfg_attr(
3893        not(all(feature = "async", feature = "pooling-allocator")),
3894        expect(dead_code, reason = "easier to cfg")
3895    )]
3896    pub(crate) stack_size: usize,
3897    /// The limits to apply to instances allocated within this allocator.
3898    pub(crate) limits: InstanceLimits,
3899    /// Whether or not async stacks are zeroed after use.
3900    #[cfg_attr(
3901        not(all(feature = "async", feature = "pooling-allocator")),
3902        expect(dead_code, reason = "easier to cfg")
3903    )]
3904    pub(crate) async_stack_zeroing: bool,
3905    /// If async stack zeroing is enabled and the host platform is Linux this is
3906    /// how much memory to zero out with `memset`.
3907    ///
3908    /// The rest of memory will be zeroed out with `madvise`.
3909    pub(crate) async_stack_keep_resident: usize,
3910    /// How much linear memory, in bytes, to keep resident after resetting for
3911    /// use with the next instance. This much memory will be `memset` to zero
3912    /// when a linear memory is deallocated.
3913    ///
3914    /// Memory exceeding this amount in the wasm linear memory will be released
3915    /// with `madvise` back to the kernel.
3916    ///
3917    /// Only applicable on Linux.
3918    pub(crate) linear_memory_keep_resident: usize,
3919    /// Same as `linear_memory_keep_resident` but for tables.
3920    pub(crate) table_keep_resident: usize,
3921    /// Whether to enable memory protection keys.
3922    pub(crate) memory_protection_keys: Enabled,
3923    /// How many memory protection keys to allocate.
3924    pub(crate) max_memory_protection_keys: usize,
3925    /// Whether to enable PAGEMAP_SCAN on Linux.
3926    pub(crate) pagemap_scan: Enabled,
3927}
3928
3929impl Default for PoolingAllocationConfig {
3930    fn default() -> Self {
3931        Self {
3932            max_unused_warm_slots: 100,
3933            decommit_batch_size: 1,
3934            stack_size: 2 << 20,
3935            limits: InstanceLimits::default(),
3936            async_stack_zeroing: false,
3937            async_stack_keep_resident: 0,
3938            linear_memory_keep_resident: 0,
3939            table_keep_resident: 0,
3940            memory_protection_keys: Enabled::No,
3941            max_memory_protection_keys: 16,
3942            pagemap_scan: Enabled::No,
3943        }
3944    }
3945}
3946
3947/// Instance-related limit configuration for pooling.
3948///
3949/// More docs on this can be found at `wasmtime::PoolingAllocationConfig`.
3950#[derive(Debug, Copy, Clone)]
3951pub(crate) struct InstanceLimits {
3952    /// The maximum number of component instances that may be allocated
3953    /// concurrently.
3954    pub(crate) total_component_instances: u32,
3955
3956    /// The maximum size of a component's `VMComponentContext`, including
3957    /// the aggregate size of all its inner core modules' `VMContext` sizes.
3958    pub(crate) component_instance_size: usize,
3959
3960    /// The maximum number of core module instances that may be allocated
3961    /// concurrently.
3962    pub(crate) total_core_instances: u32,
3963
3964    /// The maximum number of core module instances that a single component may
3965    /// transitively contain.
3966    pub(crate) max_core_instances_per_component: u32,
3967
3968    /// The maximum number of Wasm linear memories that a component may
3969    /// transitively contain.
3970    pub(crate) max_memories_per_component: u32,
3971
3972    /// The maximum number of tables that a component may transitively contain.
3973    pub(crate) max_tables_per_component: u32,
3974
3975    /// The total number of linear memories in the pool, across all instances.
3976    pub(crate) total_memories: u32,
3977
3978    /// The total number of tables in the pool, across all instances.
3979    pub(crate) total_tables: u32,
3980
3981    /// The total number of async stacks in the pool, across all instances.
3982    pub(crate) total_stacks: u32,
3983
3984    /// Maximum size of a core instance's `VMContext`.
3985    pub(crate) core_instance_size: usize,
3986
3987    /// Maximum number of tables per instance.
3988    pub(crate) max_tables_per_module: u32,
3989
3990    /// Maximum number of word-size elements per table.
3991    ///
3992    /// Note that tables for element types such as continuations
3993    /// that use more than one word of storage may store fewer
3994    /// elements.
3995    pub(crate) table_elements: usize,
3996
3997    /// Maximum number of linear memories per instance.
3998    pub(crate) max_memories_per_module: u32,
3999
4000    /// Maximum byte size of a linear memory, must be smaller than
4001    /// `memory_reservation` in `Tunables`.
4002    pub(crate) max_memory_size: usize,
4003
4004    /// The total number of GC heaps in the pool, across all instances.
4005    pub(crate) total_gc_heaps: u32,
4006}
4007
4008impl Default for InstanceLimits {
4009    fn default() -> Self {
4010        let total = if cfg!(target_pointer_width = "32") {
4011            100
4012        } else {
4013            1000
4014        };
4015        // See doc comments for `wasmtime::PoolingAllocationConfig` for these
4016        // default values
4017        Self {
4018            total_component_instances: total,
4019            component_instance_size: 1 << 20, // 1 MiB
4020            total_core_instances: total,
4021            max_core_instances_per_component: u32::MAX,
4022            max_memories_per_component: u32::MAX,
4023            max_tables_per_component: u32::MAX,
4024            total_memories: total,
4025            total_tables: total,
4026            total_stacks: total,
4027            core_instance_size: 1 << 20, // 1 MiB
4028            max_tables_per_module: 1,
4029            // NB: in #8504 it was seen that a C# module in debug module can
4030            // have 10k+ elements.
4031            table_elements: 20_000,
4032            max_memories_per_module: 1,
4033            #[cfg(target_pointer_width = "64")]
4034            max_memory_size: 1 << 32, // 4G,
4035            #[cfg(target_pointer_width = "32")]
4036            max_memory_size: 10 << 20, // 10 MiB
4037            total_gc_heaps: total,
4038        }
4039    }
4040}
4041
4042impl PoolingAllocationConfig {
4043    /// Returns a new configuration builder with all default settings
4044    /// configured.
4045    pub fn new() -> PoolingAllocationConfig {
4046        PoolingAllocationConfig::default()
4047    }
4048
4049    /// Configures the maximum number of "unused warm slots" to retain in the
4050    /// pooling allocator.
4051    ///
4052    /// The pooling allocator operates over slots to allocate from, and each
4053    /// slot is considered "cold" if it's never been used before or "warm" if
4054    /// it's been used by some module in the past. Slots in the pooling
4055    /// allocator additionally track an "affinity" flag to a particular core
4056    /// wasm module. When a module is instantiated into a slot then the slot is
4057    /// considered affine to that module, even after the instance has been
4058    /// deallocated.
4059    ///
4060    /// When a new instance is created then a slot must be chosen, and the
4061    /// current algorithm for selecting a slot is:
4062    ///
4063    /// * If there are slots that are affine to the module being instantiated,
4064    ///   then the most recently used slot is selected to be allocated from.
4065    ///   This is done to improve reuse of resources such as memory mappings and
4066    ///   additionally try to benefit from temporal locality for things like
4067    ///   caches.
4068    ///
4069    /// * Otherwise if there are more than N affine slots to other modules, then
4070    ///   one of those affine slots is chosen to be allocated. The slot chosen
4071    ///   is picked on a least-recently-used basis.
4072    ///
4073    /// * Finally, if there are less than N affine slots to other modules, then
4074    ///   the non-affine slots are allocated from.
4075    ///
4076    /// This setting, `max_unused_warm_slots`, is the value for N in the above
4077    /// algorithm. The purpose of this setting is to have a knob over the RSS
4078    /// impact of "unused slots" for a long-running wasm server.
4079    ///
4080    /// If this setting is set to 0, for example, then affine slots are
4081    /// aggressively reused on a least-recently-used basis. A "cold" slot is
4082    /// only used if there are no affine slots available to allocate from. This
4083    /// means that the set of slots used over the lifetime of a program is the
4084    /// same as the maximum concurrent number of wasm instances.
4085    ///
4086    /// If this setting is set to infinity, however, then cold slots are
4087    /// prioritized to be allocated from. This means that the set of slots used
4088    /// over the lifetime of a program will approach
4089    /// [`PoolingAllocationConfig::total_memories`], or the maximum number of
4090    /// slots in the pooling allocator.
4091    ///
4092    /// Wasmtime does not aggressively decommit all resources associated with a
4093    /// slot when the slot is not in use. For example the
4094    /// [`PoolingAllocationConfig::linear_memory_keep_resident`] option can be
4095    /// used to keep memory associated with a slot, even when it's not in use.
4096    /// This means that the total set of used slots in the pooling instance
4097    /// allocator can impact the overall RSS usage of a program.
4098    ///
4099    /// The default value for this option is `100`.
4100    pub fn max_unused_warm_slots(&mut self, max: u32) -> &mut Self {
4101        self.max_unused_warm_slots = max;
4102        self
4103    }
4104
4105    /// The target number of decommits to do per batch.
4106    ///
4107    /// This is not precise, as we can queue up decommits at times when we
4108    /// aren't prepared to immediately flush them, and so we may go over this
4109    /// target size occasionally.
4110    ///
4111    /// Note additionally that the queue of not-yet-decommitted entities is
4112    /// sharded to reduce lock contention: one shard per available CPU, capped
4113    /// at 16. Each shard batches up to this many decommits independently,
4114    /// meaning that up to `min(available_parallelism, 16) * (batch_size - 1)`
4115    /// decommits may be queued and not yet flushed at any given time.
4116    ///
4117    /// A batch size of one effectively disables batching.
4118    ///
4119    /// Defaults to `1`.
4120    pub fn decommit_batch_size(&mut self, batch_size: usize) -> &mut Self {
4121        self.decommit_batch_size = batch_size;
4122        self
4123    }
4124
4125    /// How much memory, in bytes, to keep resident for async stacks allocated
4126    /// with the pooling allocator.
4127    ///
4128    /// When [`Config::async_stack_zeroing`] is enabled then Wasmtime will reset
4129    /// the contents of async stacks back to zero upon deallocation. This option
4130    /// can be used to perform the zeroing operation with `memset` up to a
4131    /// certain threshold of bytes instead of using system calls to reset the
4132    /// stack to zero.
4133    ///
4134    /// Note that when using this option the memory with async stacks will
4135    /// never be decommitted.
4136    pub fn async_stack_keep_resident(&mut self, size: usize) -> &mut Self {
4137        self.async_stack_keep_resident = size;
4138        self
4139    }
4140
4141    /// How much memory, in bytes, to keep resident for each linear memory
4142    /// after deallocation.
4143    ///
4144    /// This option is only applicable on Linux and has no effect on other
4145    /// platforms.
4146    ///
4147    /// By default Wasmtime will use `madvise` to reset the entire contents of
4148    /// linear memory back to zero when a linear memory is deallocated. This
4149    /// option can be used to use `memset` instead to set memory back to zero
4150    /// which can, in some configurations, reduce the number of page faults
4151    /// taken when a slot is reused.
4152    pub fn linear_memory_keep_resident(&mut self, size: usize) -> &mut Self {
4153        self.linear_memory_keep_resident = size;
4154        self
4155    }
4156
4157    /// How much memory, in bytes, to keep resident for each table after
4158    /// deallocation.
4159    ///
4160    /// This option is only applicable on Linux and has no effect on other
4161    /// platforms.
4162    ///
4163    /// This option is the same as
4164    /// [`PoolingAllocationConfig::linear_memory_keep_resident`] except that it
4165    /// is applicable to tables instead.
4166    pub fn table_keep_resident(&mut self, size: usize) -> &mut Self {
4167        self.table_keep_resident = size;
4168        self
4169    }
4170
4171    /// The maximum number of concurrent component instances supported (default
4172    /// is `1000`).
4173    ///
4174    /// This provides an upper-bound on the total size of component
4175    /// metadata-related allocations, along with
4176    /// [`PoolingAllocationConfig::max_component_instance_size`]. The upper bound is
4177    ///
4178    /// ```text
4179    /// total_component_instances * max_component_instance_size
4180    /// ```
4181    ///
4182    /// where `max_component_instance_size` is rounded up to the size and alignment
4183    /// of the internal representation of the metadata.
4184    pub fn total_component_instances(&mut self, count: u32) -> &mut Self {
4185        self.limits.total_component_instances = count;
4186        self
4187    }
4188
4189    /// The maximum size, in bytes, allocated for a component instance's
4190    /// `VMComponentContext` metadata as well as the aggregate size of this
4191    /// component's core instances `VMContext` metadata.
4192    ///
4193    /// The [`wasmtime::component::Instance`][crate::component::Instance] type
4194    /// has a static size but its internal `VMComponentContext` is dynamically
4195    /// sized depending on the component being instantiated. This size limit
4196    /// loosely correlates to the size of the component, taking into account
4197    /// factors such as:
4198    ///
4199    /// * number of lifted and lowered functions,
4200    /// * number of memories
4201    /// * number of inner instances
4202    /// * number of resources
4203    ///
4204    /// If the allocated size per instance is too small then instantiation of a
4205    /// module will fail at runtime with an error indicating how many bytes were
4206    /// needed.
4207    ///
4208    /// In addition to the memory in the runtime for the component itself,
4209    /// components contain one or more core module instances. Each of these
4210    /// require some memory in the runtime as described in
4211    /// [`PoolingAllocationConfig::max_core_instance_size`]. The limit here
4212    /// applies against the sum of all of these individual allocations.
4213    ///
4214    /// The default value for this is 1MiB.
4215    ///
4216    /// This provides an upper-bound on the total size of all component's
4217    /// metadata-related allocations (for both the component and its embedded
4218    /// core module instances), along with
4219    /// [`PoolingAllocationConfig::total_component_instances`]. The upper bound is
4220    ///
4221    /// ```text
4222    /// total_component_instances * max_component_instance_size
4223    /// ```
4224    ///
4225    /// where `max_component_instance_size` is rounded up to the size and alignment
4226    /// of the internal representation of the metadata.
4227    pub fn max_component_instance_size(&mut self, size: usize) -> &mut Self {
4228        self.limits.component_instance_size = size;
4229        self
4230    }
4231
4232    /// The maximum number of core instances a single component may contain
4233    /// (default is unlimited).
4234    ///
4235    /// This method (along with
4236    /// [`PoolingAllocationConfig::max_memories_per_component`],
4237    /// [`PoolingAllocationConfig::max_tables_per_component`], and
4238    /// [`PoolingAllocationConfig::max_component_instance_size`]) allows you to cap
4239    /// the amount of resources a single component allocation consumes.
4240    ///
4241    /// If a component will instantiate more core instances than `count`, then
4242    /// the component will fail to instantiate.
4243    pub fn max_core_instances_per_component(&mut self, count: u32) -> &mut Self {
4244        self.limits.max_core_instances_per_component = count;
4245        self
4246    }
4247
4248    /// The maximum number of Wasm linear memories that a single component may
4249    /// transitively contain (default is unlimited).
4250    ///
4251    /// This method (along with
4252    /// [`PoolingAllocationConfig::max_core_instances_per_component`],
4253    /// [`PoolingAllocationConfig::max_tables_per_component`], and
4254    /// [`PoolingAllocationConfig::max_component_instance_size`]) allows you to cap
4255    /// the amount of resources a single component allocation consumes.
4256    ///
4257    /// If a component transitively contains more linear memories than `count`,
4258    /// then the component will fail to instantiate.
4259    pub fn max_memories_per_component(&mut self, count: u32) -> &mut Self {
4260        self.limits.max_memories_per_component = count;
4261        self
4262    }
4263
4264    /// The maximum number of tables that a single component may transitively
4265    /// contain (default is unlimited).
4266    ///
4267    /// This method (along with
4268    /// [`PoolingAllocationConfig::max_core_instances_per_component`],
4269    /// [`PoolingAllocationConfig::max_memories_per_component`],
4270    /// [`PoolingAllocationConfig::max_component_instance_size`]) allows you to cap
4271    /// the amount of resources a single component allocation consumes.
4272    ///
4273    /// If a component will transitively contains more tables than `count`, then
4274    /// the component will fail to instantiate.
4275    pub fn max_tables_per_component(&mut self, count: u32) -> &mut Self {
4276        self.limits.max_tables_per_component = count;
4277        self
4278    }
4279
4280    /// The maximum number of concurrent Wasm linear memories supported (default
4281    /// is `1000`).
4282    ///
4283    /// This value has a direct impact on the amount of memory allocated by the pooling
4284    /// instance allocator.
4285    ///
4286    /// The pooling instance allocator allocates a memory pool, where each entry
4287    /// in the pool contains the reserved address space for each linear memory
4288    /// supported by an instance.
4289    ///
4290    /// The memory pool will reserve a large quantity of host process address
4291    /// space to elide the bounds checks required for correct WebAssembly memory
4292    /// semantics. Even with 64-bit address spaces, the address space is limited
4293    /// when dealing with a large number of linear memories.
4294    ///
4295    /// For example, on Linux x86_64, the userland address space limit is 128
4296    /// TiB. That might seem like a lot, but each linear memory will *reserve* 6
4297    /// GiB of space by default.
4298    pub fn total_memories(&mut self, count: u32) -> &mut Self {
4299        self.limits.total_memories = count;
4300        self
4301    }
4302
4303    /// The maximum number of concurrent tables supported (default is `1000`).
4304    ///
4305    /// This value has a direct impact on the amount of memory allocated by the
4306    /// pooling instance allocator.
4307    ///
4308    /// The pooling instance allocator allocates a table pool, where each entry
4309    /// in the pool contains the space needed for each WebAssembly table
4310    /// supported by an instance (see `table_elements` to control the size of
4311    /// each table).
4312    pub fn total_tables(&mut self, count: u32) -> &mut Self {
4313        self.limits.total_tables = count;
4314        self
4315    }
4316
4317    /// The maximum number of execution stacks allowed for asynchronous
4318    /// execution, when enabled (default is `1000`).
4319    ///
4320    /// This value has a direct impact on the amount of memory allocated by the
4321    /// pooling instance allocator.
4322    #[cfg(feature = "async")]
4323    pub fn total_stacks(&mut self, count: u32) -> &mut Self {
4324        self.limits.total_stacks = count;
4325        self
4326    }
4327
4328    /// The maximum number of concurrent core instances supported (default is
4329    /// `1000`).
4330    ///
4331    /// This provides an upper-bound on the total size of core instance
4332    /// metadata-related allocations, along with
4333    /// [`PoolingAllocationConfig::max_core_instance_size`]. The upper bound is
4334    ///
4335    /// ```text
4336    /// total_core_instances * max_core_instance_size
4337    /// ```
4338    ///
4339    /// where `max_core_instance_size` is rounded up to the size and alignment of
4340    /// the internal representation of the metadata.
4341    pub fn total_core_instances(&mut self, count: u32) -> &mut Self {
4342        self.limits.total_core_instances = count;
4343        self
4344    }
4345
4346    /// The maximum size, in bytes, allocated for a core instance's `VMContext`
4347    /// metadata.
4348    ///
4349    /// The [`Instance`][crate::Instance] type has a static size but its
4350    /// `VMContext` metadata is dynamically sized depending on the module being
4351    /// instantiated. This size limit loosely correlates to the size of the Wasm
4352    /// module, taking into account factors such as:
4353    ///
4354    /// * number of functions
4355    /// * number of globals
4356    /// * number of memories
4357    /// * number of tables
4358    /// * number of function types
4359    ///
4360    /// If the allocated size per instance is too small then instantiation of a
4361    /// module will fail at runtime with an error indicating how many bytes were
4362    /// needed.
4363    ///
4364    /// The default value for this is 1MiB.
4365    ///
4366    /// This provides an upper-bound on the total size of core instance
4367    /// metadata-related allocations, along with
4368    /// [`PoolingAllocationConfig::total_core_instances`]. The upper bound is
4369    ///
4370    /// ```text
4371    /// total_core_instances * max_core_instance_size
4372    /// ```
4373    ///
4374    /// where `max_core_instance_size` is rounded up to the size and alignment of
4375    /// the internal representation of the metadata.
4376    pub fn max_core_instance_size(&mut self, size: usize) -> &mut Self {
4377        self.limits.core_instance_size = size;
4378        self
4379    }
4380
4381    /// The maximum number of defined tables for a core module (default is `1`).
4382    ///
4383    /// This value controls the capacity of the `VMTableDefinition` table in
4384    /// each instance's `VMContext` structure.
4385    ///
4386    /// The allocated size of the table will be `tables *
4387    /// sizeof(VMTableDefinition)` for each instance regardless of how many
4388    /// tables are defined by an instance's module.
4389    pub fn max_tables_per_module(&mut self, tables: u32) -> &mut Self {
4390        self.limits.max_tables_per_module = tables;
4391        self
4392    }
4393
4394    /// The maximum table elements for any table defined in a module (default is
4395    /// `20000`).
4396    ///
4397    /// If a table's minimum element limit is greater than this value, the
4398    /// module will fail to instantiate.
4399    ///
4400    /// If a table's maximum element limit is unbounded or greater than this
4401    /// value, the maximum will be `table_elements` for the purpose of any
4402    /// `table.grow` instruction.
4403    ///
4404    /// This value is used to reserve the maximum space for each supported
4405    /// table; table elements are pointer-sized in the Wasmtime runtime.
4406    /// Therefore, the space reserved for each instance is `tables *
4407    /// table_elements * sizeof::<*const ()>`.
4408    pub fn table_elements(&mut self, elements: usize) -> &mut Self {
4409        self.limits.table_elements = elements;
4410        self
4411    }
4412
4413    /// The maximum number of defined linear memories for a module (default is
4414    /// `1`).
4415    ///
4416    /// This value controls the capacity of the `VMMemoryDefinition` table in
4417    /// each core instance's `VMContext` structure.
4418    ///
4419    /// The allocated size of the table will be `memories *
4420    /// sizeof(VMMemoryDefinition)` for each core instance regardless of how
4421    /// many memories are defined by the core instance's module.
4422    pub fn max_memories_per_module(&mut self, memories: u32) -> &mut Self {
4423        self.limits.max_memories_per_module = memories;
4424        self
4425    }
4426
4427    /// The maximum byte size that any WebAssembly linear memory may grow to.
4428    ///
4429    /// This option defaults to 4 GiB meaning that for 32-bit linear memories
4430    /// there is no restrictions. 64-bit linear memories will not be allowed to
4431    /// grow beyond 4 GiB by default.
4432    ///
4433    /// If a memory's minimum size is greater than this value, the module will
4434    /// fail to instantiate.
4435    ///
4436    /// If a memory's maximum size is unbounded or greater than this value, the
4437    /// maximum will be `max_memory_size` for the purpose of any `memory.grow`
4438    /// instruction.
4439    ///
4440    /// This value is used to control the maximum accessible space for each
4441    /// linear memory of a core instance. This can be thought of as a simple
4442    /// mechanism like [`Store::limiter`](crate::Store::limiter) to limit memory
4443    /// at runtime. This value can also affect striping/coloring behavior when
4444    /// used in conjunction with
4445    /// [`memory_protection_keys`](PoolingAllocationConfig::memory_protection_keys).
4446    ///
4447    /// The virtual memory reservation size of each linear memory is controlled
4448    /// by the [`Config::memory_reservation`] setting and this method's
4449    /// configuration cannot exceed [`Config::memory_reservation`].
4450    pub fn max_memory_size(&mut self, bytes: usize) -> &mut Self {
4451        self.limits.max_memory_size = bytes;
4452        self
4453    }
4454
4455    /// Configures whether memory protection keys (MPK) should be used for more
4456    /// efficient layout of pool-allocated memories.
4457    ///
4458    /// When using the pooling allocator (see [`Config::allocation_strategy`],
4459    /// [`InstanceAllocationStrategy::Pooling`]), memory protection keys can
4460    /// reduce the total amount of allocated virtual memory by eliminating guard
4461    /// regions between WebAssembly memories in the pool. It does so by
4462    /// "coloring" memory regions with different memory keys and setting which
4463    /// regions are accessible each time executions switches from host to guest
4464    /// (or vice versa).
4465    ///
4466    /// Leveraging MPK requires configuring a smaller-than-default
4467    /// [`max_memory_size`](PoolingAllocationConfig::max_memory_size) to enable
4468    /// this coloring/striping behavior. For example embeddings might want to
4469    /// reduce the default 4G allowance to 128M.
4470    ///
4471    /// MPK is only available on Linux (called `pku` there) and recent x86
4472    /// systems; we check for MPK support at runtime by examining the `CPUID`
4473    /// register. This configuration setting can be in three states:
4474    ///
4475    /// - `auto`: if MPK support is available the guard regions are removed; if
4476    ///   not, the guard regions remain
4477    /// - `yes`: use MPK to eliminate guard regions; fail if MPK is not
4478    ///   supported
4479    /// - `no`: never use MPK
4480    ///
4481    /// By default this value is `no`, but may become `auto` in future
4482    /// releases.
4483    ///
4484    /// __WARNING__: this configuration options is still experimental--use at
4485    /// your own risk! MPK uses kernel and CPU features to protect memory
4486    /// regions; you may observe segmentation faults if anything is
4487    /// misconfigured.
4488    #[cfg(feature = "memory-protection-keys")]
4489    pub fn memory_protection_keys(&mut self, enable: Enabled) -> &mut Self {
4490        self.memory_protection_keys = enable;
4491        self
4492    }
4493
4494    /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime
4495    /// will use.
4496    ///
4497    /// This setting is only applicable when
4498    /// [`PoolingAllocationConfig::memory_protection_keys`] is set to `enable`
4499    /// or `auto`. Configuring this above the HW and OS limits (typically 15)
4500    /// has no effect.
4501    ///
4502    /// If multiple Wasmtime engines are used in the same process, note that all
4503    /// engines will share the same set of allocated keys; this setting will
4504    /// limit how many keys are allocated initially and thus available to all
4505    /// other engines.
4506    #[cfg(feature = "memory-protection-keys")]
4507    pub fn max_memory_protection_keys(&mut self, max: usize) -> &mut Self {
4508        self.max_memory_protection_keys = max;
4509        self
4510    }
4511
4512    /// Check if memory protection keys (MPK) are available on the current host.
4513    ///
4514    /// This is a convenience method for determining MPK availability using the
4515    /// same method that [`Enabled::Auto`] does. See
4516    /// [`PoolingAllocationConfig::memory_protection_keys`] for more
4517    /// information.
4518    #[cfg(feature = "memory-protection-keys")]
4519    pub fn are_memory_protection_keys_available() -> bool {
4520        crate::runtime::vm::mpk::is_supported()
4521    }
4522
4523    /// The maximum number of concurrent GC heaps supported (default is `1000`).
4524    ///
4525    /// This value has a direct impact on the amount of memory allocated by the
4526    /// pooling instance allocator.
4527    ///
4528    /// The pooling instance allocator allocates a GC heap pool, where each
4529    /// entry in the pool contains the space needed for each GC heap used by a
4530    /// store.
4531    #[cfg(feature = "gc")]
4532    pub fn total_gc_heaps(&mut self, count: u32) -> &mut Self {
4533        self.limits.total_gc_heaps = count;
4534        self
4535    }
4536
4537    /// Configures whether the Linux-specific [`PAGEMAP_SCAN` ioctl][ioctl] is
4538    /// used to help reset linear memory.
4539    ///
4540    /// When [`Self::linear_memory_keep_resident`] or
4541    /// [`Self::table_keep_resident`] options are configured to nonzero values
4542    /// the default behavior is to `memset` the lowest addresses of a table or
4543    /// memory back to their original contents. With the `PAGEMAP_SCAN` ioctl on
4544    /// Linux this can be done to more intelligently scan for resident pages in
4545    /// the region and only reset those pages back to their original contents
4546    /// with `memset` rather than assuming the low addresses are all resident.
4547    ///
4548    /// This ioctl has the potential to provide a number of performance benefits
4549    /// in high-reuse and high concurrency scenarios. Notably this enables
4550    /// Wasmtime to scan the entire region of WebAssembly linear memory and
4551    /// manually reset memory back to its original contents, up to
4552    /// [`Self::linear_memory_keep_resident`] bytes, possibly skipping an
4553    /// `madvise` entirely. This can be more efficient by avoiding removing
4554    /// pages from the address space entirely and additionally ensuring that
4555    /// future use of the linear memory doesn't incur page faults as the pages
4556    /// remain resident.
4557    ///
4558    /// At this time this configuration option is still being evaluated as to
4559    /// how appropriate it is for all use cases. It currently defaults to
4560    /// `no` or disabled but may change to `auto`, enable if supported, in the
4561    /// future. This option is only supported on Linux and requires a kernel
4562    /// version of 6.7 or higher.
4563    ///
4564    /// [ioctl]: https://www.man7.org/linux/man-pages/man2/PAGEMAP_SCAN.2const.html
4565    pub fn pagemap_scan(&mut self, enable: Enabled) -> &mut Self {
4566        self.pagemap_scan = enable;
4567        self
4568    }
4569
4570    /// Returns the configured
4571    /// [`PoolingAllocationConfig::decommit_batch_size`], if enabled.
4572    pub fn get_decommit_batch_size(&self) -> usize {
4573        self.decommit_batch_size
4574    }
4575
4576    /// Returns the configured
4577    /// [`PoolingAllocationConfig::max_unused_warm_slots`], if enabled.
4578    pub fn get_max_unused_warm_slots(&self) -> u32 {
4579        self.max_unused_warm_slots
4580    }
4581
4582    /// Returns the configured
4583    /// [`PoolingAllocationConfig::linear_memory_keep_resident`], if
4584    /// enabled.
4585    pub fn get_memory_keep_resident(&self) -> usize {
4586        self.linear_memory_keep_resident
4587    }
4588
4589    /// Returns the configured
4590    /// [`PoolingAllocationConfig::table_keep_resident`], if enabled.
4591    pub fn get_table_keep_resident(&self) -> usize {
4592        self.table_keep_resident
4593    }
4594
4595    /// Returns the configured
4596    /// [`PoolingAllocationConfig::async_stack_keep_resident`], if
4597    /// enabled.
4598    pub fn get_async_stack_keep_resident(&self) -> usize {
4599        self.async_stack_keep_resident
4600    }
4601
4602    /// Returns the configured
4603    /// [`PoolingAllocationConfig::memory_protection_keys`], if enabled.
4604    pub fn get_memory_protection_keys(&self) -> Enabled {
4605        self.memory_protection_keys
4606    }
4607
4608    /// Returns the configured
4609    /// [`PoolingAllocationConfig::max_memory_protection_keys`], if
4610    /// enabled.
4611    pub fn get_max_memory_protection_keys(&self) -> usize {
4612        self.max_memory_protection_keys
4613    }
4614
4615    /// Returns the configured
4616    /// [`PoolingAllocationConfig::pagemap_scan`], if enabled.
4617    pub fn get_pagemap_scan(&self) -> Enabled {
4618        self.pagemap_scan
4619    }
4620
4621    /// Returns the configured
4622    /// [`PoolingAllocationConfig::total_core_instances`], if enabled.
4623    pub fn get_total_core_instances(&self) -> u32 {
4624        self.limits.total_core_instances
4625    }
4626
4627    /// Returns the configured
4628    /// [`PoolingAllocationConfig::total_component_instances`], if
4629    /// enabled.
4630    pub fn get_total_component_instances(&self) -> u32 {
4631        self.limits.total_component_instances
4632    }
4633
4634    /// Returns the configured
4635    /// [`PoolingAllocationConfig::total_memories`], if enabled.
4636    pub fn get_total_memories(&self) -> u32 {
4637        self.limits.total_memories
4638    }
4639
4640    /// Returns the configured
4641    /// [`PoolingAllocationConfig::total_tables`], if enabled.
4642    pub fn get_total_tables(&self) -> u32 {
4643        self.limits.total_tables
4644    }
4645
4646    /// Returns the configured
4647    /// [`PoolingAllocationConfig::total_stacks`], if enabled.
4648    pub fn get_total_stacks(&self) -> u32 {
4649        self.limits.total_stacks
4650    }
4651
4652    /// Returns the configured
4653    /// [`PoolingAllocationConfig::total_gc_heaps`], if enabled.
4654    pub fn get_total_gc_heaps(&self) -> u32 {
4655        self.limits.total_gc_heaps
4656    }
4657
4658    /// Returns the configured
4659    /// [`PoolingAllocationConfig::max_memory_size`], if enabled.
4660    pub fn get_max_memory_size(&self) -> usize {
4661        self.limits.max_memory_size
4662    }
4663
4664    /// Returns the configured
4665    /// [`PoolingAllocationConfig::table_elements`], if enabled.
4666    pub fn get_table_elements(&self) -> usize {
4667        self.limits.table_elements
4668    }
4669
4670    /// Returns the configured
4671    /// [`PoolingAllocationConfig::max_core_instance_size`], if enabled.
4672    pub fn get_max_core_instance_size(&self) -> usize {
4673        self.limits.core_instance_size
4674    }
4675
4676    /// Returns the configured
4677    /// [`PoolingAllocationConfig::max_component_instance_size`], if
4678    /// enabled.
4679    pub fn get_max_component_instance_size(&self) -> usize {
4680        self.limits.component_instance_size
4681    }
4682
4683    /// Returns the configured
4684    /// [`PoolingAllocationConfig::max_core_instances_per_component`], if
4685    /// enabled.
4686    pub fn get_max_core_instances_per_component(&self) -> u32 {
4687        self.limits.max_core_instances_per_component
4688    }
4689
4690    /// Returns the configured
4691    /// [`PoolingAllocationConfig::max_memories_per_component`], if
4692    /// enabled.
4693    pub fn get_max_memories_per_component(&self) -> u32 {
4694        self.limits.max_memories_per_component
4695    }
4696
4697    /// Returns the configured
4698    /// [`PoolingAllocationConfig::max_tables_per_component`], if enabled.
4699    pub fn get_max_tables_per_component(&self) -> u32 {
4700        self.limits.max_tables_per_component
4701    }
4702
4703    /// Returns the configured
4704    /// [`PoolingAllocationConfig::max_tables_per_module`], if enabled.
4705    pub fn get_max_tables_per_module(&self) -> u32 {
4706        self.limits.max_tables_per_module
4707    }
4708
4709    /// Returns the configured
4710    /// [`PoolingAllocationConfig::max_memories_per_module`], if enabled.
4711    pub fn get_max_memories_per_module(&self) -> u32 {
4712        self.limits.max_memories_per_module
4713    }
4714}
4715
4716#[cfg(feature = "std")]
4717fn detect_host_feature(feature: &str) -> Option<bool> {
4718    #[cfg(target_arch = "aarch64")]
4719    {
4720        return match feature {
4721            "lse" => Some(std::arch::is_aarch64_feature_detected!("lse")),
4722            "paca" => Some(std::arch::is_aarch64_feature_detected!("paca")),
4723            "fp16" => Some(std::arch::is_aarch64_feature_detected!("fp16")),
4724            "dotprod" => Some(std::arch::is_aarch64_feature_detected!("dotprod")),
4725            "i8mm" => Some(std::arch::is_aarch64_feature_detected!("i8mm")),
4726
4727            _ => None,
4728        };
4729    }
4730
4731    // `is_s390x_feature_detected` is nightly only for now, so use the
4732    // STORE FACILITY LIST EXTENDED instruction as a temporary measure.
4733    #[cfg(target_arch = "s390x")]
4734    {
4735        let mut facility_list: [u64; 4] = [0; 4];
4736        unsafe {
4737            core::arch::asm!(
4738                "stfle 0({})",
4739                in(reg_addr) facility_list.as_mut_ptr() ,
4740                inout("r0") facility_list.len() as u64 - 1 => _,
4741                options(nostack)
4742            );
4743        }
4744        let get_facility_bit = |n: usize| {
4745            // NOTE: bits are numbered from the left.
4746            facility_list[n / 64] & (1 << (63 - (n % 64))) != 0
4747        };
4748
4749        return match feature {
4750            "mie3" => Some(get_facility_bit(61)),
4751            "mie4" => Some(get_facility_bit(84)),
4752            "vxrs_ext2" => Some(get_facility_bit(148)),
4753            "vxrs_ext3" => Some(get_facility_bit(198)),
4754
4755            _ => None,
4756        };
4757    }
4758
4759    #[cfg(target_arch = "riscv64")]
4760    {
4761        return match feature {
4762            // due to `is_riscv64_feature_detected` is not stable.
4763            // we cannot use it. For now lie and say all features are always
4764            // found to keep tests working.
4765            _ => Some(true),
4766        };
4767    }
4768
4769    #[cfg(target_arch = "x86_64")]
4770    {
4771        return match feature {
4772            "cmpxchg16b" => Some(std::is_x86_feature_detected!("cmpxchg16b")),
4773            "sse3" => Some(std::is_x86_feature_detected!("sse3")),
4774            "ssse3" => Some(std::is_x86_feature_detected!("ssse3")),
4775            "sse4.1" => Some(std::is_x86_feature_detected!("sse4.1")),
4776            "sse4.2" => Some(std::is_x86_feature_detected!("sse4.2")),
4777            "popcnt" => Some(std::is_x86_feature_detected!("popcnt")),
4778            "avx" => Some(std::is_x86_feature_detected!("avx")),
4779            "avx2" => Some(std::is_x86_feature_detected!("avx2")),
4780            "fma" => Some(std::is_x86_feature_detected!("fma")),
4781            "avxvnni" => Some(std::is_x86_feature_detected!("avxvnni")),
4782            "bmi1" => Some(std::is_x86_feature_detected!("bmi1")),
4783            "bmi2" => Some(std::is_x86_feature_detected!("bmi2")),
4784            "avx512bitalg" => Some(std::is_x86_feature_detected!("avx512bitalg")),
4785            "avx512dq" => Some(std::is_x86_feature_detected!("avx512dq")),
4786            "avx512f" => Some(std::is_x86_feature_detected!("avx512f")),
4787            "avx512vl" => Some(std::is_x86_feature_detected!("avx512vl")),
4788            "avx512vbmi" => Some(std::is_x86_feature_detected!("avx512vbmi")),
4789            "avx512vnni" => Some(std::is_x86_feature_detected!("avx512vnni")),
4790            "lzcnt" => Some(std::is_x86_feature_detected!("lzcnt")),
4791
4792            _ => None,
4793        };
4794    }
4795
4796    #[allow(
4797        unreachable_code,
4798        reason = "reachable or not depending on if a target above matches"
4799    )]
4800    {
4801        let _ = feature;
4802        return None;
4803    }
4804}
4805
4806// What follows in this impl block is intended to be a somewhat-mechanical
4807// mostly-complete set of getters for relevant configuration options on
4808// `Config`. The `Config` type does not reflect a complete configuration so
4809// default values cannot be directly read from it. An `Engine`, however,
4810// represents a concrete and complete configuration with all default values
4811// fully specified. The purpose of these getters are then to perform a dual
4812// function of reflecting what was explicitly configured above as well as
4813// defaults that Wasmtime sets.
4814//
4815// The current pattern is:
4816//
4817// * All methods are `get_<config_name>`
4818// * Return values return `T` instead of `Option<T>` where possible unless the
4819//   state for `T` is completely missing.
4820//
4821// This impl is primarily in service of
4822// `wasmtime_cli_flags::CommonOptions::from_engine` at this time, and CLI flags
4823// are not as comprehensive as `Config` options, but it's expected that the set
4824// will settle/grow over time.
4825impl Engine {
4826    /// Returns the configured [`Config::memory_may_move`] value.
4827    pub fn get_memory_may_move(&self) -> bool {
4828        self.tunables().memory_may_move
4829    }
4830
4831    /// Returns the configured [`Config::memory_reservation`] value.
4832    pub fn get_memory_reservation(&self) -> u64 {
4833        self.tunables().memory_reservation
4834    }
4835
4836    /// Returns the configured [`Config::memory_reservation_for_growth`] value.
4837    pub fn get_memory_reservation_for_growth(&self) -> u64 {
4838        self.tunables().memory_reservation_for_growth
4839    }
4840
4841    /// Returns the configured [`Config::memory_guard_size`] value.
4842    pub fn get_memory_guard_size(&self) -> u64 {
4843        self.tunables().memory_guard_size
4844    }
4845
4846    /// Returns the configured [`Config::gc_heap_may_move`] value.
4847    pub fn get_gc_heap_may_move(&self) -> bool {
4848        self.tunables().gc_heap_may_move
4849    }
4850
4851    /// Returns the configured [`Config::gc_heap_reservation`] value.
4852    pub fn get_gc_heap_reservation(&self) -> u64 {
4853        self.tunables().gc_heap_reservation
4854    }
4855
4856    /// Returns the configured [`Config::gc_heap_initial_size`] value.
4857    pub fn get_gc_heap_initial_size(&self) -> u64 {
4858        self.tunables().gc_heap_initial_size
4859    }
4860
4861    /// Returns the configured [`Config::gc_heap_reservation_for_growth`] value.
4862    pub fn get_gc_heap_reservation_for_growth(&self) -> u64 {
4863        self.tunables().gc_heap_reservation_for_growth
4864    }
4865
4866    /// Returns the configured [`Config::gc_heap_guard_size`] value.
4867    pub fn get_gc_heap_guard_size(&self) -> u64 {
4868        self.tunables().gc_heap_guard_size
4869    }
4870
4871    /// Returns the configured [`Config::guard_before_linear_memory`] value.
4872    pub fn get_guard_before_linear_memory(&self) -> bool {
4873        self.tunables().guard_before_linear_memory
4874    }
4875
4876    /// Returns the configured [`Config::table_lazy_init`] value.
4877    pub fn get_table_lazy_init(&self) -> bool {
4878        self.tunables().table_lazy_init
4879    }
4880
4881    /// Returns the configured [`Config::memory_init_cow`] value.
4882    pub fn get_memory_init_cow(&self) -> bool {
4883        self.tunables().memory_init_cow
4884    }
4885
4886    /// Returns the configured [`Config::memory_guaranteed_dense_image_size`] value.
4887    pub fn get_memory_guaranteed_dense_image_size(&self) -> u64 {
4888        self.config().memory_guaranteed_dense_image_size
4889    }
4890
4891    /// Returns the configured [`Config::signals_based_traps`] value.
4892    pub fn get_signals_based_traps(&self) -> bool {
4893        self.tunables().signals_based_traps
4894    }
4895
4896    /// Returns the configured [`Config::gc_zeal_alloc_counter`] value.
4897    pub fn get_gc_zeal_alloc_counter(&self) -> Option<core::num::NonZeroU32> {
4898        self.tunables().gc_zeal_alloc_counter
4899    }
4900
4901    /// Returns the configured [`Config::cranelift_opt_level`] value.
4902    pub fn get_cranelift_opt_level(&self) -> Option<OptLevel> {
4903        #[cfg(any(feature = "cranelift", feature = "winch"))]
4904        if let Some(compiler) = self.compiler() {
4905            let flags = compiler.flags();
4906            let (_, FlagValue::Enum(opt)) = flags.iter().find(|(f, _)| *f == "opt_level")? else {
4907                return None;
4908            };
4909            return match &opt[..] {
4910                "none" => Some(OptLevel::None),
4911                "speed" => Some(OptLevel::Speed),
4912                "speed_and_size" => Some(OptLevel::SpeedAndSize),
4913                _ => None,
4914            };
4915        }
4916        None
4917    }
4918
4919    /// Returns the configured [`Config::cranelift_regalloc_algorithm`] value.
4920    pub fn get_cranelift_regalloc_algorithm(&self) -> Option<RegallocAlgorithm> {
4921        #[cfg(any(feature = "cranelift", feature = "winch"))]
4922        if let Some(compiler) = self.compiler() {
4923            let flags = compiler.flags();
4924            let (_, FlagValue::Enum(opt)) =
4925                flags.iter().find(|(f, _)| *f == "regalloc_algorithm")?
4926            else {
4927                return None;
4928            };
4929            return match &opt[..] {
4930                "backtracking" => Some(RegallocAlgorithm::Backtracking),
4931                "single_pass" => Some(RegallocAlgorithm::SinglePass),
4932                _ => None,
4933            };
4934        }
4935        None
4936    }
4937
4938    /// Returns the configured [`Config::strategy`] value.
4939    pub fn get_strategy(&self) -> Option<Strategy> {
4940        #[cfg(any(feature = "cranelift", feature = "winch"))]
4941        return self.config().compiler_config.as_ref()?.strategy;
4942        #[cfg(not(any(feature = "cranelift", feature = "winch")))]
4943        return None;
4944    }
4945
4946    /// Returns the configured [`Config::collector`] value.
4947    pub fn get_collector(&self) -> Option<Collector> {
4948        #[cfg(feature = "gc")]
4949        return Some(self.config().collector);
4950        #[cfg(not(feature = "gc"))]
4951        return None;
4952    }
4953
4954    /// Returns the configured [`Config::cranelift_debug_verifier`] value.
4955    pub fn get_cranelift_debug_verifier(&self) -> Option<bool> {
4956        #[cfg(any(feature = "cranelift", feature = "winch"))]
4957        if let Some(compiler) = self.compiler() {
4958            let flags = compiler.flags();
4959            let (_, FlagValue::Bool(b)) = flags.iter().find(|(f, _)| *f == "enable_verifier")?
4960            else {
4961                return None;
4962            };
4963            return Some(*b);
4964        }
4965        None
4966    }
4967
4968    /// Returns the configured [`Config::compiler_inlining`] value.
4969    pub fn get_compiler_inlining(&self) -> Inlining {
4970        self.tunables().inlining
4971    }
4972
4973    /// Returns the configured [`Config::native_unwind_info`] value.
4974    pub fn get_native_unwind_info(&self) -> Option<bool> {
4975        #[cfg(any(feature = "cranelift", feature = "winch"))]
4976        if let Some(compiler) = self.compiler() {
4977            let flags = compiler.flags();
4978            let (_, FlagValue::Bool(b)) = flags.iter().find(|(f, _)| *f == "unwind_info")? else {
4979                return None;
4980            };
4981            return Some(*b);
4982        }
4983        None
4984    }
4985
4986    /// Returns the configured [`Config::parallel_compilation`] value.
4987    pub fn get_parallel_compilation(&self) -> bool {
4988        self.config().parallel_compilation
4989    }
4990
4991    /// Returns the configured [`Config::metadata_for_internal_asserts`] value.
4992    pub fn get_metadata_for_internal_asserts(&self) -> bool {
4993        self.tunables().metadata_for_internal_asserts
4994    }
4995
4996    /// Returns the configured [`Config::metadata_for_gc_heap_corruption`] value.
4997    pub fn get_metadata_for_gc_heap_corruption(&self) -> bool {
4998        self.tunables().metadata_for_gc_heap_corruption
4999    }
5000
5001    /// Returns the runtime pooling allocator configuration, if the pooling
5002    /// allocator is in use.
5003    pub fn get_pooling_config(&self) -> Option<&PoolingAllocationConfig> {
5004        #[cfg(feature = "pooling-allocator")]
5005        {
5006            Some(self.allocator().as_pooling()?.config())
5007        }
5008        #[cfg(not(feature = "pooling-allocator"))]
5009        {
5010            None
5011        }
5012    }
5013
5014    /// Returns the configured wasm proposals enabled in this engine.
5015    pub fn get_wasm_features(&self) -> WasmFeatures {
5016        self.features()
5017    }
5018
5019    /// Returns the configured [`Config::async_stack_size`] value.
5020    pub fn get_async_stack_size(&self) -> usize {
5021        self.config().async_stack_size
5022    }
5023
5024    /// Returns the configured [`Config::async_stack_zeroing`] value.
5025    pub fn get_async_stack_zeroing(&self) -> bool {
5026        self.config().async_stack_zeroing
5027    }
5028
5029    /// Returns the configured [`Config::wasm_branch_hinting`] value.
5030    pub fn get_wasm_branch_hinting(&self) -> bool {
5031        self.tunables().branch_hinting
5032    }
5033
5034    /// Returns the configured [`Config::concurrency_support`] value.
5035    pub fn get_concurrency_support(&self) -> bool {
5036        self.tunables().concurrency_support
5037    }
5038
5039    /// Returns the configured [`Config::epoch_interruption`] value.
5040    pub fn get_epoch_interruption(&self) -> bool {
5041        self.tunables().epoch_interruption
5042    }
5043
5044    /// Returns the configured [`Config::consume_fuel`] value.
5045    pub fn get_consume_fuel(&self) -> bool {
5046        self.tunables().consume_fuel
5047    }
5048
5049    /// Returns the configured [`Config::max_wasm_stack`] value.
5050    pub fn get_max_wasm_stack(&self) -> usize {
5051        self.config().max_wasm_stack
5052    }
5053
5054    /// Returns the configured [`Config::cranelift_nan_canonicalization`] value.
5055    pub fn get_cranelift_nan_canonicalization(&self) -> Option<bool> {
5056        #[cfg(any(feature = "cranelift", feature = "winch"))]
5057        if let Some(compiler) = self.compiler() {
5058            let flags = compiler.flags();
5059            let (_, FlagValue::Bool(b)) = flags
5060                .iter()
5061                .find(|(f, _)| *f == "enable_nan_canonicalization")?
5062            else {
5063                return None;
5064            };
5065            return Some(*b);
5066        }
5067        None
5068    }
5069
5070    /// Returns the configured [`Config::relaxed_simd_deterministic`] value.
5071    pub fn get_relaxed_simd_deterministic(&self) -> bool {
5072        self.tunables().relaxed_simd_deterministic
5073    }
5074
5075    /// Returns the configured [`Config::shared_memory`] value.
5076    pub fn get_shared_memory(&self) -> bool {
5077        self.config().shared_memory
5078    }
5079
5080    /// Returns the configured [`Config::generate_address_map`] value.
5081    pub fn get_generate_address_map(&self) -> bool {
5082        self.tunables().generate_address_map
5083    }
5084
5085    /// Returns the configured [`Config::debug_info`] value.
5086    pub fn get_debug_info(&self) -> bool {
5087        self.tunables().debug_native
5088    }
5089
5090    /// Returns the configured [`Config::guest_debug`] value.
5091    pub fn get_guest_debug(&self) -> bool {
5092        self.tunables().debug_guest
5093    }
5094
5095    /// Returns the configured [`Config::debug_symbols`] value.
5096    pub fn get_debug_symbols(&self) -> bool {
5097        self.tunables().debug_symbols
5098    }
5099
5100    /// Returns the configured [`Config::wasm_backtrace_max_frames`] value.
5101    pub fn get_wasm_backtrace_max_frames(&self) -> usize {
5102        self.config()
5103            .wasm_backtrace_max_frames
5104            .map(|f| f.get())
5105            .unwrap_or(0)
5106    }
5107
5108    /// Returns the configured [`Config::target`] value.
5109    pub fn get_target(&self) -> Option<String> {
5110        #[cfg(any(feature = "cranelift", feature = "winch"))]
5111        if let Some(compiler) = self.compiler() {
5112            return Some(compiler.triple().to_string());
5113        }
5114        None
5115    }
5116
5117    /// Returns the enabled flags via [`Config::cranelift_flag_enable`].
5118    pub fn get_cranelift_flags_enabled(&self) -> impl Iterator<Item = &str> {
5119        #[cfg(any(feature = "cranelift", feature = "winch"))]
5120        if let Some(config) = &self.config().compiler_config {
5121            return config
5122                .flags
5123                .iter()
5124                .filter_map(|(k, v)| match v {
5125                    UserSpecified::Yes => Some(k.as_str()),
5126                    UserSpecified::No => None,
5127                })
5128                .collect::<Vec<_>>()
5129                .into_iter();
5130        }
5131
5132        Vec::new().into_iter()
5133    }
5134
5135    /// Returns the enabled flags via [`Config::cranelift_flag_set`].
5136    pub fn get_cranelift_flags_set(&self) -> impl Iterator<Item = (&str, &str)> {
5137        #[cfg(any(feature = "cranelift", feature = "winch"))]
5138        if let Some(config) = &self.config().compiler_config {
5139            return config
5140                .settings
5141                .iter()
5142                .filter_map(|(k, (v, s))| match s {
5143                    UserSpecified::Yes => Some((k.as_str(), v.as_str())),
5144                    UserSpecified::No => None,
5145                })
5146                .collect::<Vec<_>>()
5147                .into_iter();
5148        }
5149
5150        Vec::new().into_iter()
5151    }
5152}