Skip to main content

wasmtime/
config.rs

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