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