Skip to main content

wasmtime/
config.rs

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