wasmtime_environ/tunables.rs
1use crate::prelude::*;
2use crate::{IndexType, Limits, Memory, TripleExt};
3use core::num::NonZeroU32;
4use core::{fmt, str::FromStr};
5use serde_derive::{Deserialize, Serialize};
6use target_lexicon::{PointerWidth, Triple};
7use wasmparser::Operator;
8
9macro_rules! define_tunables {
10 (
11 $(#[$outer_attr:meta])*
12 pub struct $tunables:ident {
13 $(
14 $(#[$field_attr:meta])*
15 pub $field:ident : $field_ty:ty,
16 )*
17 }
18
19 pub struct $config_tunables:ident {
20 ...
21 }
22 ) => {
23 $(#[$outer_attr])*
24 pub struct $tunables {
25 $(
26 $(#[$field_attr])*
27 pub $field: $field_ty,
28 )*
29 }
30
31 /// Optional tunable configuration options used in `wasmtime::Config`
32 #[derive(Default, Clone)]
33 #[expect(missing_docs, reason = "macro-generated fields")]
34 pub struct $config_tunables {
35 $(pub $field: Option<$field_ty>,)*
36 }
37
38 impl $config_tunables {
39 /// Formats configured fields into `f`.
40 pub fn format(&self, f: &mut fmt::DebugStruct<'_,'_>) {
41 $(
42 if let Some(val) = &self.$field {
43 f.field(stringify!($field), val);
44 }
45 )*
46 }
47
48 /// Configure the `Tunables` provided.
49 pub fn configure(&self, tunables: &mut Tunables) {
50 $(
51 if let Some(val) = &self.$field {
52 tunables.$field = val.clone();
53 }
54 )*
55 }
56 }
57 };
58}
59
60define_tunables! {
61 /// Tunable parameters for WebAssembly compilation.
62 #[derive(Clone, Hash, Serialize, Deserialize, Debug)]
63 pub struct Tunables {
64 /// The garbage collector implementation to use, which implies the layout of
65 /// GC objects and barriers that must be emitted in Wasm code.
66 pub collector: Option<Collector>,
67
68 /// Initial size, in bytes, to be allocated for linear memories.
69 pub memory_reservation: u64,
70
71 /// The size, in bytes, of the guard page region for linear memories.
72 pub memory_guard_size: u64,
73
74 /// The size, in bytes, to allocate at the end of a relocated linear
75 /// memory for growth.
76 pub memory_reservation_for_growth: u64,
77
78 /// Whether or not to generate native DWARF debug information.
79 pub debug_native: bool,
80
81 /// Whether we are enabling precise Wasm-level debugging in
82 /// the guest.
83 pub debug_guest: bool,
84
85 /// Whether or not to retain DWARF sections in compiled modules.
86 pub parse_wasm_debuginfo: bool,
87
88 /// Whether or not fuel is enabled for generated code, meaning that fuel
89 /// will be consumed every time a wasm instruction is executed.
90 pub consume_fuel: bool,
91
92 /// The cost of each operator. If fuel is not enabled, this is ignored.
93 pub operator_cost: OperatorCostStrategy,
94
95 /// Whether or not we use epoch-based interruption.
96 pub epoch_interruption: bool,
97
98 /// Whether or not linear memories are allowed to be reallocated after
99 /// initial allocation at runtime.
100 pub memory_may_move: bool,
101
102 /// Whether or not linear memory allocations will have a guard region at the
103 /// beginning of the allocation in addition to the end.
104 pub guard_before_linear_memory: bool,
105
106 /// Whether to initialize tables lazily, so that instantiation is fast but
107 /// indirect calls are a little slower. If false, tables are initialized
108 /// eagerly from any active element segments that apply to them during
109 /// instantiation.
110 pub table_lazy_init: bool,
111
112 /// Indicates whether an address map from compiled native code back to wasm
113 /// offsets in the original file is generated.
114 pub generate_address_map: bool,
115
116 /// Flag for the component module whether adapter modules have debug
117 /// assertions baked into them.
118 pub debug_adapter_modules: bool,
119
120 /// Whether or not lowerings for relaxed simd instructions are forced to
121 /// be deterministic.
122 pub relaxed_simd_deterministic: bool,
123
124 /// Whether or not Wasm functions target the winch abi.
125 pub winch_callable: bool,
126
127 /// Whether or not the host will be using native signals (e.g. SIGILL,
128 /// SIGSEGV, etc) to implement traps.
129 pub signals_based_traps: bool,
130
131 /// Whether CoW images might be used to initialize linear memories.
132 pub memory_init_cow: bool,
133
134 /// Whether to enable inlining in Wasmtime's compilation orchestration
135 /// or not.
136 pub inlining: Inlining,
137
138 /// The size of "small callees" that can be inlined regardless of the
139 /// caller's size.
140 pub inlining_small_callee_size: u32,
141
142 /// The general size threshold for the sum of the caller's and callee's
143 /// sizes, past which we will generally not inline calls anymore.
144 pub inlining_sum_size_threshold: u32,
145
146 /// Whether any component model feature related to concurrency is
147 /// enabled.
148 pub concurrency_support: bool,
149
150 /// Whether recording in RR is enabled or not. This is used primarily
151 /// to signal checksum computation for compiled artifacts.
152 pub recording: bool,
153
154 /// An allocation counter that triggers GC when it reaches zero.
155 ///
156 /// Decremented on every allocation and when it hits zero, a GC is
157 /// forced and the counter is reset. Only effective when
158 /// `cfg(gc_zeal)` is enabled.
159 pub gc_zeal_alloc_counter: Option<NonZeroU32>,
160
161 /// Initial size, in bytes, to be allocated for GC heaps.
162 ///
163 /// This is the same as `memory_reservation` but for GC heaps.
164 pub gc_heap_reservation: u64,
165
166 /// The size, in bytes, of the guard page region for GC heaps.
167 ///
168 /// This is the same as `memory_guard_size` but for GC heaps.
169 pub gc_heap_guard_size: u64,
170
171 /// The size, in bytes, to allocate at the end of a relocated GC heap
172 /// for growth.
173 ///
174 /// This is the same as `memory_reservation_for_growth` but for GC
175 /// heaps.
176 pub gc_heap_reservation_for_growth: u64,
177
178 /// Whether or not GC heaps are allowed to be reallocated after initial
179 /// allocation at runtime.
180 ///
181 /// This is the same as `memory_may_move` but for GC heaps.
182 pub gc_heap_may_move: bool,
183
184 /// Boolean to track whether compiled code retains metadata necessary to
185 /// report extra information on internal assertions failing.
186 pub metadata_for_internal_asserts: bool,
187
188 /// Boolean to track whether compiled code retains metadata necessary to
189 /// report extra information on gc heap corruption being detected.
190 pub metadata_for_gc_heap_corruption: bool,
191 }
192
193 pub struct ConfigTunables {
194 ...
195 }
196}
197
198impl Tunables {
199 /// Returns a `Tunables` configuration assumed for running code on the host.
200 pub fn default_host() -> Self {
201 if cfg!(miri) {
202 Tunables::default_miri()
203 } else if cfg!(target_pointer_width = "32") {
204 Tunables::default_u32()
205 } else if cfg!(target_pointer_width = "64") {
206 Tunables::default_u64()
207 } else {
208 panic!("unsupported target_pointer_width");
209 }
210 }
211
212 /// Returns the default set of tunables for the given target triple.
213 pub fn default_for_target(target: &Triple) -> Result<Self> {
214 if cfg!(miri) {
215 return Ok(Tunables::default_miri());
216 }
217 let mut ret = match target
218 .pointer_width()
219 .map_err(|_| format_err!("failed to retrieve target pointer width"))?
220 {
221 PointerWidth::U32 => Tunables::default_u32(),
222 PointerWidth::U64 => Tunables::default_u64(),
223 _ => bail!("unsupported target pointer width"),
224 };
225
226 // Pulley targets never use signals-based-traps and also can't benefit
227 // from guard pages, so disable them.
228 if target.is_pulley() {
229 ret.signals_based_traps = false;
230 ret.memory_guard_size = 0;
231 ret.gc_heap_guard_size = 0;
232 }
233 Ok(ret)
234 }
235
236 /// Returns the default set of tunables for running under MIRI.
237 pub fn default_miri() -> Tunables {
238 Tunables {
239 collector: None,
240
241 // No virtual memory tricks are available on miri so make these
242 // limits quite conservative.
243 memory_reservation: 1 << 20,
244 memory_guard_size: 0,
245 memory_reservation_for_growth: 0,
246
247 // General options which have the same defaults regardless of
248 // architecture.
249 debug_native: false,
250 parse_wasm_debuginfo: true,
251 consume_fuel: false,
252 operator_cost: OperatorCostStrategy::Default,
253 epoch_interruption: false,
254 memory_may_move: true,
255 guard_before_linear_memory: true,
256 table_lazy_init: true,
257 generate_address_map: true,
258 debug_adapter_modules: false,
259 relaxed_simd_deterministic: false,
260 winch_callable: false,
261 signals_based_traps: false,
262 memory_init_cow: true,
263 inlining: Inlining::No,
264 inlining_small_callee_size: 50,
265 inlining_sum_size_threshold: 2000,
266 debug_guest: false,
267 concurrency_support: true,
268 recording: false,
269 gc_zeal_alloc_counter: None,
270 gc_heap_reservation: 0,
271 gc_heap_guard_size: 0,
272 gc_heap_reservation_for_growth: 0,
273 gc_heap_may_move: true,
274 metadata_for_internal_asserts: false,
275 metadata_for_gc_heap_corruption: true,
276 }
277 }
278
279 /// Returns the default set of tunables for running under a 32-bit host.
280 pub fn default_u32() -> Tunables {
281 Tunables {
282 // For 32-bit we scale way down to 10MB of reserved memory. This
283 // impacts performance severely but allows us to have more than a
284 // few instances running around.
285 memory_reservation: 10 * (1 << 20),
286 memory_guard_size: 0x1_0000,
287 memory_reservation_for_growth: 1 << 20, // 1MB
288 signals_based_traps: true,
289
290 // GC heaps on 32-bit: conservative defaults similar to linear
291 // memories.
292 gc_heap_reservation: 10 * (1 << 20),
293 gc_heap_guard_size: 0x1_0000,
294 gc_heap_reservation_for_growth: 1 << 20, // 1MB
295
296 ..Tunables::default_miri()
297 }
298 }
299
300 /// Returns the default set of tunables for running under a 64-bit host.
301 pub fn default_u64() -> Tunables {
302 Tunables {
303 // 64-bit has tons of address space to static memories can have 4gb
304 // address space reservations liberally by default, allowing us to
305 // help eliminate bounds checks.
306 //
307 // A 32MiB default guard size is then allocated so we can remove
308 // explicit bounds checks if any static offset is less than this
309 // value. SpiderMonkey found, for example, that in a large corpus of
310 // wasm modules 20MiB was the maximum offset so this is the
311 // power-of-two-rounded up from that and matches SpiderMonkey.
312 memory_reservation: 1 << 32,
313 memory_guard_size: 32 << 20,
314
315 // We've got lots of address space on 64-bit so use a larger
316 // grow-into-this area, but on 32-bit we aren't as lucky. Miri is
317 // not exactly fast so reduce memory consumption instead of trying
318 // to avoid memory movement.
319 memory_reservation_for_growth: 2 << 30, // 2GB
320
321 // GC heaps on 64-bit: use 4GiB reservation and 32MiB guard pages
322 // to enable bounds check elision, matching linear memory defaults.
323 gc_heap_reservation: 1 << 32,
324 gc_heap_guard_size: 32 << 20,
325 gc_heap_reservation_for_growth: 2 << 30, // 2GB
326
327 signals_based_traps: true,
328 ..Tunables::default_miri()
329 }
330 }
331
332 /// Get the GC heap's memory type, given our configured tunables.
333 pub fn gc_heap_memory_type(&self) -> Memory {
334 Memory {
335 idx_type: IndexType::I32,
336 limits: Limits { min: 0, max: None },
337 shared: false,
338 // We *could* try to match the target architecture's page size, but that
339 // would require exercising a page size for memories that we don't
340 // otherwise support for Wasm; we conservatively avoid that, and just
341 // use the default Wasm page size, for now.
342 page_size_log2: 16,
343 }
344 }
345}
346
347/// Whether a heap is backing a linear memory or a GC heap.
348///
349/// This is used by [`MemoryTunables`] to select between the memory tunables and
350/// the GC heap tunables.
351#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
352pub enum MemoryKind {
353 /// A WebAssembly linear memory.
354 LinearMemory,
355 /// A GC heap for garbage-collected objects.
356 GcHeap,
357}
358
359/// A view into a [`Tunables`] that selects the appropriate linear-memory or
360/// GC-heap flavor of each tunable based on a [`MemoryKind`].
361pub struct MemoryTunables<'a> {
362 tunables: &'a Tunables,
363 kind: MemoryKind,
364}
365
366impl<'a> MemoryTunables<'a> {
367 /// Create a new `MemoryTunables` view.
368 pub fn new(tunables: &'a Tunables, kind: MemoryKind) -> Self {
369 Self { tunables, kind }
370 }
371
372 /// The virtual memory reservation for this kind of memory.
373 pub fn reservation(&self) -> u64 {
374 match self.kind {
375 MemoryKind::LinearMemory => self.tunables.memory_reservation,
376 MemoryKind::GcHeap => self.tunables.gc_heap_reservation,
377 }
378 }
379
380 /// The size of the guard page region for this kind of memory.
381 pub fn guard_size(&self) -> u64 {
382 match self.kind {
383 MemoryKind::LinearMemory => self.tunables.memory_guard_size,
384 MemoryKind::GcHeap => self.tunables.gc_heap_guard_size,
385 }
386 }
387
388 /// Extra virtual memory to reserve beyond the initially mapped pages for
389 /// this kind of memory.
390 pub fn reservation_for_growth(&self) -> u64 {
391 match self.kind {
392 MemoryKind::LinearMemory => self.tunables.memory_reservation_for_growth,
393 MemoryKind::GcHeap => self.tunables.gc_heap_reservation_for_growth,
394 }
395 }
396
397 /// Whether this kind of memory's base pointer may be relocated at runtime.
398 pub fn may_move(&self) -> bool {
399 match self.kind {
400 MemoryKind::LinearMemory => self.tunables.memory_may_move,
401 MemoryKind::GcHeap => self.tunables.gc_heap_may_move,
402 }
403 }
404
405 /// Get the underlying tunables.
406 ///
407 /// This is ONLY for accessing tunable fields that DO NOT come in a
408 /// linear-memory flavor and a GC-heap flavor.
409 pub fn tunables(&self) -> &'a Tunables {
410 self.tunables
411 }
412}
413
414/// The garbage collector implementation to use.
415#[derive(Clone, Copy, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
416pub enum Collector {
417 /// The deferred reference-counting collector.
418 DeferredReferenceCounting,
419 /// The null collector.
420 Null,
421 /// The copying collector.
422 Copying,
423}
424
425impl fmt::Display for Collector {
426 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
427 match self {
428 Collector::DeferredReferenceCounting => write!(f, "deferred reference-counting"),
429 Collector::Null => write!(f, "null"),
430 Collector::Copying => write!(f, "copying"),
431 }
432 }
433}
434
435/// Inlining modes supported by Wasmtime.
436#[derive(Clone, Copy, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
437pub enum Inlining {
438 /// All inlining is enabled wherever possible.
439 ///
440 /// This includes inter-module inlining (across modules) as well as
441 /// intra-module inlining (within a module).
442 ///
443 /// Note that backtraces may omit inlined stack frames.
444 Yes,
445
446 /// Inter-module inlining (across modules) is allowed, but intra-module
447 /// (within a module) is only allowed when the module is using GC.
448 ///
449 /// Note that backtraces may omit inlined stack frames.
450 InterModuleAndIntraGc,
451
452 /// Inter-module inlining (across modules) is allowed, but intra-module
453 /// (within a module) is not allowed.
454 ///
455 /// Note that backtraces may omit inlined stack frames.
456 InterModule,
457
458 /// No module inlining is allowed, either inter- or intra-module. Only
459 /// inlining Wasmtime's intrinsics are allowed.
460 ///
461 /// This option, for example, never emits WebAssembly stack frames from
462 /// backtraces.
463 Intrinsics,
464
465 /// Inlining is disabled entirely.
466 No,
467}
468
469impl FromStr for Inlining {
470 type Err = Error;
471
472 fn from_str(s: &str) -> Result<Self, Self::Err> {
473 match s {
474 "y" | "yes" | "true" => Ok(Self::Yes),
475 "n" | "no" | "false" => Ok(Self::No),
476 "gc" => Ok(Self::InterModuleAndIntraGc),
477 "inter-module" => Ok(Self::InterModuleAndIntraGc),
478 "intrinsics" => Ok(Self::Intrinsics),
479 _ => bail!(
480 "invalid intra-module inlining option string: `{s}`, \
481 only yes,no,gc,inter-module,intrinsics accepted"
482 ),
483 }
484 }
485}
486
487impl fmt::Display for Inlining {
488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
489 match self {
490 Inlining::Yes => write!(f, "yes"),
491 Inlining::InterModuleAndIntraGc => write!(f, "gc"),
492 Inlining::InterModule => write!(f, "inter-module"),
493 Inlining::Intrinsics => write!(f, "intrinsics"),
494 Inlining::No => write!(f, "no"),
495 }
496 }
497}
498
499/// The cost of each operator.
500///
501/// Note: a more dynamic approach (e.g. a user-supplied callback) can be
502/// added as a variant in the future if needed.
503#[derive(Clone, Hash, Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
504pub enum OperatorCostStrategy {
505 /// A table of operator costs.
506 Table(Box<OperatorCost>),
507
508 /// Each cost defaults to 1 fuel unit, except `Nop`, `Drop` and
509 /// a few control flow operators.
510 #[default]
511 Default,
512}
513
514impl OperatorCostStrategy {
515 /// Create a new operator cost strategy with a table of costs.
516 pub fn table(cost: OperatorCost) -> Self {
517 OperatorCostStrategy::Table(Box::new(cost))
518 }
519
520 /// Get the cost of an operator.
521 pub fn cost(&self, op: &Operator) -> i64 {
522 match self {
523 OperatorCostStrategy::Table(cost) => cost.cost(op),
524 OperatorCostStrategy::Default => default_operator_cost(op),
525 }
526 }
527}
528
529const fn default_operator_cost(op: &Operator) -> i64 {
530 match op {
531 // Nop and drop generate no code, so don't consume fuel for them.
532 Operator::Nop | Operator::Drop => 0,
533
534 // Control flow may create branches, but is generally cheap and
535 // free, so don't consume fuel. Note the lack of `if` since some
536 // cost is incurred with the conditional check.
537 Operator::Block { .. }
538 | Operator::Loop { .. }
539 | Operator::Unreachable
540 | Operator::Return
541 | Operator::Else
542 | Operator::End => 0,
543
544 // Everything else, just call it one operation.
545 _ => 1,
546 }
547}
548
549macro_rules! default_cost {
550 // Nop and drop generate no code, so don't consume fuel for them.
551 (Nop) => {
552 0
553 };
554 (Drop) => {
555 0
556 };
557
558 // Control flow may create branches, but is generally cheap and
559 // free, so don't consume fuel. Note the lack of `if` since some
560 // cost is incurred with the conditional check.
561 (Block) => {
562 0
563 };
564 (Loop) => {
565 0
566 };
567 (Unreachable) => {
568 0
569 };
570 (Return) => {
571 0
572 };
573 (Else) => {
574 0
575 };
576 (End) => {
577 0
578 };
579
580 // Everything else, just call it one operation.
581 ($op:ident) => {
582 1
583 };
584}
585
586macro_rules! define_operator_cost {
587 ($(@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*) )*) => {
588 /// The fuel cost of each operator in a table.
589 #[derive(Clone, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
590 #[allow(missing_docs, non_snake_case, reason = "to avoid triggering clippy lints")]
591 pub struct OperatorCost {
592 $(
593 pub $op: u8,
594 )*
595 }
596
597 impl OperatorCost {
598 /// Returns the cost of the given operator.
599 pub fn cost(&self, op: &Operator) -> i64 {
600 match op {
601 $(
602 Operator::$op $({ $($arg: _),* })? => self.$op as i64,
603 )*
604 unknown => panic!("unknown op: {unknown:?}"),
605 }
606 }
607 }
608
609 impl OperatorCost {
610 /// Creates a new `OperatorCost` table with default costs for each operator.
611 pub const fn new() -> Self {
612 Self {
613 $(
614 $op: default_cost!($op),
615 )*
616 }
617 }
618 }
619
620 impl Default for OperatorCost {
621 fn default() -> Self {
622 Self::new()
623 }
624 }
625 }
626}
627
628wasmparser::for_each_operator!(define_operator_cost);