xref: /wasmtime-44.0.1/crates/cli-flags/src/lib.rs (revision 60fc557c)
1 //! Contains the common Wasmtime command line interface (CLI) flags.
2 
3 use anyhow::Result;
4 use clap::Parser;
5 use std::time::Duration;
6 use wasmtime::Config;
7 
8 pub mod opt;
9 
10 #[cfg(feature = "logging")]
11 fn init_file_per_thread_logger(prefix: &'static str) {
12     file_per_thread_logger::initialize(prefix);
13     file_per_thread_logger::allow_uninitialized();
14 
15     // Extending behavior of default spawner:
16     // https://docs.rs/rayon/1.1.0/rayon/struct.ThreadPoolBuilder.html#method.spawn_handler
17     // Source code says DefaultSpawner is implementation detail and
18     // shouldn't be used directly.
19     #[cfg(feature = "parallel-compilation")]
20     rayon::ThreadPoolBuilder::new()
21         .spawn_handler(move |thread| {
22             let mut b = std::thread::Builder::new();
23             if let Some(name) = thread.name() {
24                 b = b.name(name.to_owned());
25             }
26             if let Some(stack_size) = thread.stack_size() {
27                 b = b.stack_size(stack_size);
28             }
29             b.spawn(move || {
30                 file_per_thread_logger::initialize(prefix);
31                 thread.run()
32             })?;
33             Ok(())
34         })
35         .build_global()
36         .unwrap();
37 }
38 
39 wasmtime_option_group! {
40     #[derive(PartialEq, Clone)]
41     pub struct OptimizeOptions {
42         /// Optimization level of generated code (0-2, s; default: 2)
43         pub opt_level: Option<wasmtime::OptLevel>,
44 
45         /// Do not allow Wasm linear memories to move in the host process's
46         /// address space.
47         pub memory_may_move: Option<bool>,
48 
49         /// Initial virtual memory allocation size for memories.
50         pub memory_reservation: Option<u64>,
51 
52         /// Bytes to reserve at the end of linear memory for growth into.
53         pub memory_reservation_for_growth: Option<u64>,
54 
55         /// Size, in bytes, of guard pages for linear memories.
56         pub memory_guard_size: Option<u64>,
57 
58         /// Indicates whether an unmapped region of memory is placed before all
59         /// linear memories.
60         pub guard_before_linear_memory: Option<bool>,
61 
62         /// Whether to initialize tables lazily, so that instantiation is
63         /// fast but indirect calls are a little slower. If no, tables are
64         /// initialized eagerly from any active element segments that apply to
65         /// them during instantiation. (default: yes)
66         pub table_lazy_init: Option<bool>,
67 
68         /// Enable the pooling allocator, in place of the on-demand allocator.
69         pub pooling_allocator: Option<bool>,
70 
71         /// The number of decommits to do per batch. A batch size of 1
72         /// effectively disables decommit batching. (default: 1)
73         pub pooling_decommit_batch_size: Option<usize>,
74 
75         /// How many bytes to keep resident between instantiations for the
76         /// pooling allocator in linear memories.
77         pub pooling_memory_keep_resident: Option<usize>,
78 
79         /// How many bytes to keep resident between instantiations for the
80         /// pooling allocator in tables.
81         pub pooling_table_keep_resident: Option<usize>,
82 
83         /// Enable memory protection keys for the pooling allocator; this can
84         /// optimize the size of memory slots.
85         pub pooling_memory_protection_keys: Option<bool>,
86 
87         /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime
88         /// will use. (default: 16)
89         pub pooling_max_memory_protection_keys: Option<usize>,
90 
91         /// Configure attempting to initialize linear memory via a
92         /// copy-on-write mapping (default: yes)
93         pub memory_init_cow: Option<bool>,
94 
95         /// The maximum number of WebAssembly instances which can be created
96         /// with the pooling allocator.
97         pub pooling_total_core_instances: Option<u32>,
98 
99         /// The maximum number of WebAssembly components which can be created
100         /// with the pooling allocator.
101         pub pooling_total_component_instances: Option<u32>,
102 
103         /// The maximum number of WebAssembly memories which can be created with
104         /// the pooling allocator.
105         pub pooling_total_memories: Option<u32>,
106 
107         /// The maximum number of WebAssembly tables which can be created with
108         /// the pooling allocator.
109         pub pooling_total_tables: Option<u32>,
110 
111         /// The maximum number of WebAssembly stacks which can be created with
112         /// the pooling allocator.
113         pub pooling_total_stacks: Option<u32>,
114 
115         /// The maximum runtime size of each linear memory in the pooling
116         /// allocator, in bytes.
117         pub pooling_max_memory_size: Option<usize>,
118 
119         /// The maximum table elements for any table defined in a module when
120         /// using the pooling allocator.
121         pub pooling_table_elements: Option<usize>,
122 
123         /// The maximum size, in bytes, allocated for a core instance's metadata
124         /// when using the pooling allocator.
125         pub pooling_max_core_instance_size: Option<usize>,
126 
127         /// Configures the maximum number of "unused warm slots" to retain in the
128         /// pooling allocator. (default: 100)
129         pub pooling_max_unused_warm_slots: Option<u32>,
130 
131         /// Configures whether or not stacks used for async futures are reset to
132         /// zero after usage. (default: false)
133         pub pooling_async_stack_zeroing: Option<bool>,
134 
135         /// How much memory, in bytes, to keep resident for async stacks allocated
136         /// with the pooling allocator. (default: 0)
137         pub pooling_async_stack_keep_resident: Option<usize>,
138 
139         /// The maximum size, in bytes, allocated for a component instance's
140         /// `VMComponentContext` metadata. (default: 1MiB)
141         pub pooling_max_component_instance_size: Option<usize>,
142 
143         /// The maximum number of core instances a single component may contain
144         /// (default is unlimited).
145         pub pooling_max_core_instances_per_component: Option<u32>,
146 
147         /// The maximum number of Wasm linear memories that a single component may
148         /// transitively contain (default is unlimited).
149         pub pooling_max_memories_per_component: Option<u32>,
150 
151         /// The maximum number of tables that a single component may transitively
152         /// contain (default is unlimited).
153         pub pooling_max_tables_per_component: Option<u32>,
154 
155         /// The maximum number of defined tables for a core module. (default: 1)
156         pub pooling_max_tables_per_module: Option<u32>,
157 
158         /// The maximum number of defined linear memories for a module. (default: 1)
159         pub pooling_max_memories_per_module: Option<u32>,
160 
161         /// The maximum number of concurrent GC heaps supported. (default: 1000)
162         pub pooling_total_gc_heaps: Option<u32>,
163 
164         /// Enable or disable the use of host signal handlers for traps.
165         pub signals_based_traps: Option<bool>,
166 
167         /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
168         pub dynamic_memory_guard_size: Option<u64>,
169 
170         /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
171         pub static_memory_guard_size: Option<u64>,
172 
173         /// DEPRECATED: Use `-Cmemory-may-move` instead.
174         pub static_memory_forced: Option<bool>,
175 
176         /// DEPRECATED: Use `-Cmemory-reservation=N` instead.
177         pub static_memory_maximum_size: Option<u64>,
178 
179         /// DEPRECATED: Use `-Cmemory-reservation-for-growth=N` instead.
180         pub dynamic_memory_reserved_for_growth: Option<u64>,
181     }
182 
183     enum Optimize {
184         ...
185     }
186 }
187 
188 wasmtime_option_group! {
189     #[derive(PartialEq, Clone)]
190     pub struct CodegenOptions {
191         /// Either `cranelift` or `winch`.
192         ///
193         /// Currently only `cranelift` and `winch` are supported, but not all
194         /// builds of Wasmtime have both built in.
195         pub compiler: Option<wasmtime::Strategy>,
196         /// Which garbage collector to use: `drc` or `null`.
197         ///
198         /// `drc` is the deferred reference-counting collector.
199         ///
200         /// `null` is the null garbage collector, which does not collect any
201         /// garbage.
202         ///
203         /// Note that not all builds of Wasmtime will have support for garbage
204         /// collection included.
205         pub collector: Option<wasmtime::Collector>,
206         /// Enable Cranelift's internal debug verifier (expensive)
207         pub cranelift_debug_verifier: Option<bool>,
208         /// Whether or not to enable caching of compiled modules.
209         pub cache: Option<bool>,
210         /// Configuration for compiled module caching.
211         pub cache_config: Option<String>,
212         /// Whether or not to enable parallel compilation of modules.
213         pub parallel_compilation: Option<bool>,
214         /// Whether to enable proof-carrying code (PCC)-based validation.
215         pub pcc: Option<bool>,
216         /// Controls whether native unwind information is present in compiled
217         /// object files.
218         pub native_unwind_info: Option<bool>,
219 
220         #[prefixed = "cranelift"]
221         /// Set a cranelift-specific option. Use `wasmtime settings` to see
222         /// all.
223         pub cranelift: Vec<(String, Option<String>)>,
224     }
225 
226     enum Codegen {
227         ...
228     }
229 }
230 
231 wasmtime_option_group! {
232     #[derive(PartialEq, Clone)]
233     pub struct DebugOptions {
234         /// Enable generation of DWARF debug information in compiled code.
235         pub debug_info: Option<bool>,
236         /// Configure whether compiled code can map native addresses to wasm.
237         pub address_map: Option<bool>,
238         /// Configure whether logging is enabled.
239         pub logging: Option<bool>,
240         /// Configure whether logs are emitted to files
241         pub log_to_files: Option<bool>,
242         /// Enable coredump generation to this file after a WebAssembly trap.
243         pub coredump: Option<String>,
244     }
245 
246     enum Debug {
247         ...
248     }
249 }
250 
251 wasmtime_option_group! {
252     #[derive(PartialEq, Clone)]
253     pub struct WasmOptions {
254         /// Enable canonicalization of all NaN values.
255         pub nan_canonicalization: Option<bool>,
256         /// Enable execution fuel with N units fuel, trapping after running out
257         /// of fuel.
258         ///
259         /// Most WebAssembly instructions consume 1 unit of fuel. Some
260         /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0
261         /// units, as any execution cost associated with them involves other
262         /// instructions which do consume fuel.
263         pub fuel: Option<u64>,
264         /// Yield when a global epoch counter changes, allowing for async
265         /// operation without blocking the executor.
266         pub epoch_interruption: Option<bool>,
267         /// Maximum stack size, in bytes, that wasm is allowed to consume before a
268         /// stack overflow is reported.
269         pub max_wasm_stack: Option<usize>,
270         /// Stack size, in bytes, that will be allocated for async stacks.
271         ///
272         /// Note that this must be larger than `max-wasm-stack` and the
273         /// difference between the two is how much stack the host has to execute
274         /// on.
275         pub async_stack_size: Option<usize>,
276         /// Allow unknown exports when running commands.
277         pub unknown_exports_allow: Option<bool>,
278         /// Allow the main module to import unknown functions, using an
279         /// implementation that immediately traps, when running commands.
280         pub unknown_imports_trap: Option<bool>,
281         /// Allow the main module to import unknown functions, using an
282         /// implementation that returns default values, when running commands.
283         pub unknown_imports_default: Option<bool>,
284         /// Enables memory error checking. (see wmemcheck.md for more info)
285         pub wmemcheck: Option<bool>,
286         /// Maximum size, in bytes, that a linear memory is allowed to reach.
287         ///
288         /// Growth beyond this limit will cause `memory.grow` instructions in
289         /// WebAssembly modules to return -1 and fail.
290         pub max_memory_size: Option<usize>,
291         /// Maximum size, in table elements, that a table is allowed to reach.
292         pub max_table_elements: Option<usize>,
293         /// Maximum number of WebAssembly instances allowed to be created.
294         pub max_instances: Option<usize>,
295         /// Maximum number of WebAssembly tables allowed to be created.
296         pub max_tables: Option<usize>,
297         /// Maximum number of WebAssembly linear memories allowed to be created.
298         pub max_memories: Option<usize>,
299         /// Force a trap to be raised on `memory.grow` and `table.grow` failure
300         /// instead of returning -1 from these instructions.
301         ///
302         /// This is not necessarily a spec-compliant option to enable but can be
303         /// useful for tracking down a backtrace of what is requesting so much
304         /// memory, for example.
305         pub trap_on_grow_failure: Option<bool>,
306         /// Maximum execution time of wasm code before timing out (1, 2s, 100ms, etc)
307         pub timeout: Option<Duration>,
308         /// Configures support for all WebAssembly proposals implemented.
309         pub all_proposals: Option<bool>,
310         /// Configure support for the bulk memory proposal.
311         pub bulk_memory: Option<bool>,
312         /// Configure support for the multi-memory proposal.
313         pub multi_memory: Option<bool>,
314         /// Configure support for the multi-value proposal.
315         pub multi_value: Option<bool>,
316         /// Configure support for the reference-types proposal.
317         pub reference_types: Option<bool>,
318         /// Configure support for the simd proposal.
319         pub simd: Option<bool>,
320         /// Configure support for the relaxed-simd proposal.
321         pub relaxed_simd: Option<bool>,
322         /// Configure forcing deterministic and host-independent behavior of
323         /// the relaxed-simd instructions.
324         ///
325         /// By default these instructions may have architecture-specific behavior as
326         /// allowed by the specification, but this can be used to force the behavior
327         /// of these instructions to match the deterministic behavior classified in
328         /// the specification. Note that enabling this option may come at a
329         /// performance cost.
330         pub relaxed_simd_deterministic: Option<bool>,
331         /// Configure support for the tail-call proposal.
332         pub tail_call: Option<bool>,
333         /// Configure support for the threads proposal.
334         pub threads: Option<bool>,
335         /// Configure support for the memory64 proposal.
336         pub memory64: Option<bool>,
337         /// Configure support for the component-model proposal.
338         pub component_model: Option<bool>,
339         /// Configure support for 33+ flags in the component model.
340         pub component_model_more_flags: Option<bool>,
341         /// Component model support for more than one return value.
342         pub component_model_multiple_returns: Option<bool>,
343         /// Configure support for the function-references proposal.
344         pub function_references: Option<bool>,
345         /// Configure support for the GC proposal.
346         pub gc: Option<bool>,
347         /// Configure support for the custom-page-sizes proposal.
348         pub custom_page_sizes: Option<bool>,
349         /// Configure support for the wide-arithmetic proposal.
350         pub wide_arithmetic: Option<bool>,
351     }
352 
353     enum Wasm {
354         ...
355     }
356 }
357 
358 wasmtime_option_group! {
359     #[derive(PartialEq, Clone)]
360     pub struct WasiOptions {
361         /// Enable support for WASI CLI APIs, including filesystems, sockets, clocks, and random.
362         pub cli: Option<bool>,
363         /// Enable WASI APIs marked as: @unstable(feature = cli-exit-with-code)
364         pub cli_exit_with_code: Option<bool>,
365         /// Deprecated alias for `cli`
366         pub common: Option<bool>,
367         /// Enable support for WASI neural network API (experimental)
368         pub nn: Option<bool>,
369         /// Enable support for WASI threading API (experimental)
370         pub threads: Option<bool>,
371         /// Enable support for WASI HTTP API (experimental)
372         pub http: Option<bool>,
373         /// Enable support for WASI config API (experimental)
374         pub config: Option<bool>,
375         /// Enable support for WASI key-value API (experimental)
376         pub keyvalue: Option<bool>,
377         /// Inherit environment variables and file descriptors following the
378         /// systemd listen fd specification (UNIX only)
379         pub listenfd: Option<bool>,
380         /// Grant access to the given TCP listen socket
381         pub tcplisten: Vec<String>,
382         /// Implement WASI CLI APIs with preview2 primitives (experimental).
383         ///
384         /// Indicates that the implementation of WASI preview1 should be backed by
385         /// the preview2 implementation for components.
386         ///
387         /// This will become the default in the future and this option will be
388         /// removed. For now this is primarily here for testing.
389         pub preview2: Option<bool>,
390         /// Pre-load machine learning graphs (i.e., models) for use by wasi-nn.
391         ///
392         /// Each use of the flag will preload a ML model from the host directory
393         /// using the given model encoding. The model will be mapped to the
394         /// directory name: e.g., `--wasi-nn-graph openvino:/foo/bar` will preload
395         /// an OpenVINO model named `bar`. Note that which model encodings are
396         /// available is dependent on the backends implemented in the
397         /// `wasmtime_wasi_nn` crate.
398         pub nn_graph: Vec<WasiNnGraph>,
399         /// Flag for WASI preview2 to inherit the host's network within the
400         /// guest so it has full access to all addresses/ports/etc.
401         pub inherit_network: Option<bool>,
402         /// Indicates whether `wasi:sockets/ip-name-lookup` is enabled or not.
403         pub allow_ip_name_lookup: Option<bool>,
404         /// Indicates whether `wasi:sockets` TCP support is enabled or not.
405         pub tcp: Option<bool>,
406         /// Indicates whether `wasi:sockets` UDP support is enabled or not.
407         pub udp: Option<bool>,
408         /// Enable WASI APIs marked as: @unstable(feature = network-error-code)
409         pub network_error_code: Option<bool>,
410         /// Allows imports from the `wasi_unstable` core wasm module.
411         pub preview0: Option<bool>,
412         /// Inherit all environment variables from the parent process.
413         ///
414         /// This option can be further overwritten with `--env` flags.
415         pub inherit_env: Option<bool>,
416         /// Pass a wasi config variable to the program.
417         pub config_var: Vec<KeyValuePair>,
418         /// Preset data for the In-Memory provider of WASI key-value API.
419         pub keyvalue_in_memory_data: Vec<KeyValuePair>,
420     }
421 
422     enum Wasi {
423         ...
424     }
425 }
426 
427 #[derive(Debug, Clone, PartialEq)]
428 pub struct WasiNnGraph {
429     pub format: String,
430     pub dir: String,
431 }
432 
433 #[derive(Debug, Clone, PartialEq)]
434 pub struct KeyValuePair {
435     pub key: String,
436     pub value: String,
437 }
438 
439 /// Common options for commands that translate WebAssembly modules
440 #[derive(Parser, Clone)]
441 pub struct CommonOptions {
442     // These options groups are used to parse `-O` and such options but aren't
443     // the raw form consumed by the CLI. Instead they're pushed into the `pub`
444     // fields below as part of the `configure` method.
445     //
446     // Ideally clap would support `pub opts: OptimizeOptions` and parse directly
447     // into that but it does not appear to do so for multiple `-O` flags for
448     // now.
449     /// Optimization and tuning related options for wasm performance, `-O help` to
450     /// see all.
451     #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")]
452     opts_raw: Vec<opt::CommaSeparated<Optimize>>,
453 
454     /// Codegen-related configuration options, `-C help` to see all.
455     #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")]
456     codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
457 
458     /// Debug-related configuration options, `-D help` to see all.
459     #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")]
460     debug_raw: Vec<opt::CommaSeparated<Debug>>,
461 
462     /// Options for configuring semantic execution of WebAssembly, `-W help` to see
463     /// all.
464     #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")]
465     wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
466 
467     /// Options for configuring WASI and its proposals, `-S help` to see all.
468     #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")]
469     wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
470 
471     // These fields are filled in by the `configure` method below via the
472     // options parsed from the CLI above. This is what the CLI should use.
473     #[arg(skip)]
474     configured: bool,
475     #[arg(skip)]
476     pub opts: OptimizeOptions,
477     #[arg(skip)]
478     pub codegen: CodegenOptions,
479     #[arg(skip)]
480     pub debug: DebugOptions,
481     #[arg(skip)]
482     pub wasm: WasmOptions,
483     #[arg(skip)]
484     pub wasi: WasiOptions,
485 }
486 
487 macro_rules! match_feature {
488     (
489         [$feat:tt : $config:expr]
490         $val:ident => $e:expr,
491         $p:pat => err,
492     ) => {
493         #[cfg(feature = $feat)]
494         {
495             if let Some($val) = $config {
496                 $e;
497             }
498         }
499         #[cfg(not(feature = $feat))]
500         {
501             if let Some($p) = $config {
502                 anyhow::bail!(concat!("support for ", $feat, " disabled at compile time"));
503             }
504         }
505     };
506 }
507 
508 impl CommonOptions {
509     fn configure(&mut self) {
510         if self.configured {
511             return;
512         }
513         self.configured = true;
514         self.opts.configure_with(&self.opts_raw);
515         self.codegen.configure_with(&self.codegen_raw);
516         self.debug.configure_with(&self.debug_raw);
517         self.wasm.configure_with(&self.wasm_raw);
518         self.wasi.configure_with(&self.wasi_raw);
519     }
520 
521     pub fn init_logging(&mut self) -> Result<()> {
522         self.configure();
523         if self.debug.logging == Some(false) {
524             return Ok(());
525         }
526         #[cfg(feature = "logging")]
527         if self.debug.log_to_files == Some(true) {
528             let prefix = "wasmtime.dbg.";
529             init_file_per_thread_logger(prefix);
530         } else {
531             use std::io::IsTerminal;
532             use tracing_subscriber::{EnvFilter, FmtSubscriber};
533             let b = FmtSubscriber::builder()
534                 .with_writer(std::io::stderr)
535                 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
536                 .with_ansi(std::io::stderr().is_terminal());
537             b.init();
538         }
539         #[cfg(not(feature = "logging"))]
540         if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
541             anyhow::bail!("support for logging disabled at compile time");
542         }
543         Ok(())
544     }
545 
546     pub fn config(
547         &mut self,
548         target: Option<&str>,
549         pooling_allocator_default: Option<bool>,
550     ) -> Result<Config> {
551         self.configure();
552         let mut config = Config::new();
553 
554         match_feature! {
555             ["cranelift" : self.codegen.compiler]
556             strategy => config.strategy(strategy),
557             _ => err,
558         }
559         match_feature! {
560             ["gc" : self.codegen.collector]
561             collector => config.collector(collector),
562             _ => err,
563         }
564         match_feature! {
565             ["cranelift" : target]
566             target => config.target(target)?,
567             _ => err,
568         }
569         match_feature! {
570             ["cranelift" : self.codegen.cranelift_debug_verifier]
571             enable => config.cranelift_debug_verifier(enable),
572             true => err,
573         }
574         if let Some(enable) = self.debug.debug_info {
575             config.debug_info(enable);
576         }
577         if self.debug.coredump.is_some() {
578             #[cfg(feature = "coredump")]
579             config.coredump_on_trap(true);
580             #[cfg(not(feature = "coredump"))]
581             anyhow::bail!("support for coredumps disabled at compile time");
582         }
583         match_feature! {
584             ["cranelift" : self.opts.opt_level]
585             level => config.cranelift_opt_level(level),
586             _ => err,
587         }
588         match_feature! {
589             ["cranelift" : self.wasm.nan_canonicalization]
590             enable => config.cranelift_nan_canonicalization(enable),
591             true => err,
592         }
593         match_feature! {
594             ["cranelift" : self.codegen.pcc]
595             enable => config.cranelift_pcc(enable),
596             true => err,
597         }
598 
599         self.enable_wasm_features(&mut config)?;
600 
601         #[cfg(feature = "cranelift")]
602         for (name, value) in self.codegen.cranelift.iter() {
603             let name = name.replace('-', "_");
604             unsafe {
605                 match value {
606                     Some(val) => {
607                         config.cranelift_flag_set(&name, val);
608                     }
609                     None => {
610                         config.cranelift_flag_enable(&name);
611                     }
612                 }
613             }
614         }
615         #[cfg(not(feature = "cranelift"))]
616         if !self.codegen.cranelift.is_empty() {
617             anyhow::bail!("support for cranelift disabled at compile time");
618         }
619 
620         #[cfg(feature = "cache")]
621         if self.codegen.cache != Some(false) {
622             match &self.codegen.cache_config {
623                 Some(path) => {
624                     config.cache_config_load(path)?;
625                 }
626                 None => {
627                     config.cache_config_load_default()?;
628                 }
629             }
630         }
631         #[cfg(not(feature = "cache"))]
632         if self.codegen.cache == Some(true) {
633             anyhow::bail!("support for caching disabled at compile time");
634         }
635 
636         match_feature! {
637             ["parallel-compilation" : self.codegen.parallel_compilation]
638             enable => config.parallel_compilation(enable),
639             true => err,
640         }
641 
642         if let Some(max) = self
643             .opts
644             .memory_reservation
645             .or(self.opts.static_memory_maximum_size)
646         {
647             config.memory_reservation(max);
648         }
649 
650         if let Some(enable) = self.opts.static_memory_forced {
651             config.memory_may_move(!enable);
652         }
653         if let Some(enable) = self.opts.memory_may_move {
654             config.memory_may_move(enable);
655         }
656 
657         if let Some(size) = self
658             .opts
659             .static_memory_guard_size
660             .or(self.opts.dynamic_memory_guard_size)
661             .or(self.opts.memory_guard_size)
662         {
663             config.memory_guard_size(size);
664         }
665 
666         if let Some(size) = self
667             .opts
668             .memory_reservation_for_growth
669             .or(self.opts.dynamic_memory_reserved_for_growth)
670         {
671             config.memory_reservation_for_growth(size);
672         }
673         if let Some(enable) = self.opts.guard_before_linear_memory {
674             config.guard_before_linear_memory(enable);
675         }
676         if let Some(enable) = self.opts.table_lazy_init {
677             config.table_lazy_init(enable);
678         }
679 
680         // If fuel has been configured, set the `consume fuel` flag on the config.
681         if self.wasm.fuel.is_some() {
682             config.consume_fuel(true);
683         }
684 
685         if let Some(enable) = self.wasm.epoch_interruption {
686             config.epoch_interruption(enable);
687         }
688         if let Some(enable) = self.debug.address_map {
689             config.generate_address_map(enable);
690         }
691         if let Some(enable) = self.opts.memory_init_cow {
692             config.memory_init_cow(enable);
693         }
694         if let Some(enable) = self.opts.signals_based_traps {
695             config.signals_based_traps(enable);
696         }
697         if let Some(enable) = self.codegen.native_unwind_info {
698             config.native_unwind_info(enable);
699         }
700 
701         match_feature! {
702             ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
703             enable => {
704                 if enable {
705                     let mut cfg = wasmtime::PoolingAllocationConfig::default();
706                     if let Some(size) = self.opts.pooling_memory_keep_resident {
707                         cfg.linear_memory_keep_resident(size);
708                     }
709                     if let Some(size) = self.opts.pooling_table_keep_resident {
710                         cfg.table_keep_resident(size);
711                     }
712                     if let Some(limit) = self.opts.pooling_total_core_instances {
713                         cfg.total_core_instances(limit);
714                     }
715                     if let Some(limit) = self.opts.pooling_total_component_instances {
716                         cfg.total_component_instances(limit);
717                     }
718                     if let Some(limit) = self.opts.pooling_total_memories {
719                         cfg.total_memories(limit);
720                     }
721                     if let Some(limit) = self.opts.pooling_total_tables {
722                         cfg.total_tables(limit);
723                     }
724                     if let Some(limit) = self.opts.pooling_table_elements {
725                         cfg.table_elements(limit);
726                     }
727                     if let Some(limit) = self.opts.pooling_max_core_instance_size {
728                         cfg.max_core_instance_size(limit);
729                     }
730                     match_feature! {
731                         ["async" : self.opts.pooling_total_stacks]
732                         limit => cfg.total_stacks(limit),
733                         _ => err,
734                     }
735                     if let Some(max) = self.opts.pooling_max_memory_size {
736                         cfg.max_memory_size(max);
737                     }
738                     if let Some(size) = self.opts.pooling_decommit_batch_size {
739                         cfg.decommit_batch_size(size);
740                     }
741                     if let Some(max) = self.opts.pooling_max_unused_warm_slots {
742                         cfg.max_unused_warm_slots(max);
743                     }
744                     match_feature! {
745                         ["async" : self.opts.pooling_async_stack_zeroing]
746                         enable => cfg.async_stack_zeroing(enable),
747                         _ => err,
748                     }
749                     match_feature! {
750                         ["async" : self.opts.pooling_async_stack_keep_resident]
751                         size => cfg.async_stack_keep_resident(size),
752                         _ => err,
753                     }
754                     if let Some(max) = self.opts.pooling_max_component_instance_size {
755                         cfg.max_component_instance_size(max);
756                     }
757                     if let Some(max) = self.opts.pooling_max_core_instances_per_component {
758                         cfg.max_core_instances_per_component(max);
759                     }
760                     if let Some(max) = self.opts.pooling_max_memories_per_component {
761                         cfg.max_memories_per_component(max);
762                     }
763                     if let Some(max) = self.opts.pooling_max_tables_per_component {
764                         cfg.max_tables_per_component(max);
765                     }
766                     if let Some(max) = self.opts.pooling_max_tables_per_module {
767                         cfg.max_tables_per_module(max);
768                     }
769                     if let Some(max) = self.opts.pooling_max_memories_per_module {
770                         cfg.max_memories_per_module(max);
771                     }
772                     match_feature! {
773                         ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
774                         enable => cfg.memory_protection_keys(if enable {
775                             wasmtime::MpkEnabled::Enable
776                         } else {
777                             wasmtime::MpkEnabled::Disable
778                         }),
779                         _ => err,
780                     }
781                     match_feature! {
782                         ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
783                         max => cfg.max_memory_protection_keys(max),
784                         _ => err,
785                     }
786                     match_feature! {
787                         ["gc" : self.opts.pooling_total_gc_heaps]
788                         max => cfg.total_gc_heaps(max),
789                         _ => err,
790                     }
791                     config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
792                 }
793             },
794             true => err,
795         }
796 
797         if self.opts.pooling_memory_protection_keys.unwrap_or(false)
798             && !self.opts.pooling_allocator.unwrap_or(false)
799         {
800             anyhow::bail!("memory protection keys require the pooling allocator");
801         }
802 
803         if self.opts.pooling_max_memory_protection_keys.is_some()
804             && !self.opts.pooling_memory_protection_keys.unwrap_or(false)
805         {
806             anyhow::bail!(
807                 "max memory protection keys requires memory protection keys to be enabled"
808             );
809         }
810 
811         match_feature! {
812             ["async" : self.wasm.async_stack_size]
813             size => config.async_stack_size(size),
814             _ => err,
815         }
816 
817         if let Some(max) = self.wasm.max_wasm_stack {
818             config.max_wasm_stack(max);
819 
820             // If `-Wasync-stack-size` isn't passed then automatically adjust it
821             // to the wasm stack size provided here too. That prevents the need
822             // to pass both when one can generally be inferred from the other.
823             #[cfg(feature = "async")]
824             if self.wasm.async_stack_size.is_none() {
825                 const DEFAULT_HOST_STACK: usize = 512 << 10;
826                 config.async_stack_size(max + DEFAULT_HOST_STACK);
827             }
828         }
829 
830         if let Some(enable) = self.wasm.relaxed_simd_deterministic {
831             config.relaxed_simd_deterministic(enable);
832         }
833         match_feature! {
834             ["cranelift" : self.wasm.wmemcheck]
835             enable => config.wmemcheck(enable),
836             true => err,
837         }
838 
839         Ok(config)
840     }
841 
842     pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
843         let all = self.wasm.all_proposals;
844 
845         if let Some(enable) = self.wasm.simd.or(all) {
846             config.wasm_simd(enable);
847         }
848         if let Some(enable) = self.wasm.relaxed_simd.or(all) {
849             config.wasm_relaxed_simd(enable);
850         }
851         if let Some(enable) = self.wasm.bulk_memory.or(all) {
852             config.wasm_bulk_memory(enable);
853         }
854         if let Some(enable) = self.wasm.multi_value.or(all) {
855             config.wasm_multi_value(enable);
856         }
857         if let Some(enable) = self.wasm.tail_call.or(all) {
858             config.wasm_tail_call(enable);
859         }
860         if let Some(enable) = self.wasm.multi_memory.or(all) {
861             config.wasm_multi_memory(enable);
862         }
863         if let Some(enable) = self.wasm.memory64.or(all) {
864             config.wasm_memory64(enable);
865         }
866         if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
867             config.wasm_custom_page_sizes(enable);
868         }
869         if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
870             config.wasm_wide_arithmetic(enable);
871         }
872 
873         macro_rules! handle_conditionally_compiled {
874             ($(($feature:tt, $field:tt, $method:tt))*) => ($(
875                 if let Some(enable) = self.wasm.$field.or(all) {
876                     #[cfg(feature = $feature)]
877                     config.$method(enable);
878                     #[cfg(not(feature = $feature))]
879                     if enable && all.is_none() {
880                         anyhow::bail!("support for {} was disabled at compile-time", $feature);
881                     }
882                 }
883             )*)
884         }
885 
886         handle_conditionally_compiled! {
887             ("component-model", component_model, wasm_component_model)
888             ("component-model", component_model_more_flags, wasm_component_model_more_flags)
889             ("component-model", component_model_multiple_returns, wasm_component_model_multiple_returns)
890             ("threads", threads, wasm_threads)
891             ("gc", gc, wasm_gc)
892             ("gc", reference_types, wasm_reference_types)
893             ("gc", function_references, wasm_function_references)
894         }
895         Ok(())
896     }
897 }
898 
899 impl PartialEq for CommonOptions {
900     fn eq(&self, other: &CommonOptions) -> bool {
901         let mut me = self.clone();
902         me.configure();
903         let mut other = other.clone();
904         other.configure();
905         let CommonOptions {
906             opts_raw: _,
907             codegen_raw: _,
908             debug_raw: _,
909             wasm_raw: _,
910             wasi_raw: _,
911             configured: _,
912 
913             opts,
914             codegen,
915             debug,
916             wasm,
917             wasi,
918         } = me;
919         opts == other.opts
920             && codegen == other.codegen
921             && debug == other.debug
922             && wasm == other.wasm
923             && wasi == other.wasi
924     }
925 }
926