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