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