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