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