Skip to main content

wasmtime/
config.rs

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