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