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