xref: /wasmtime-44.0.1/crates/cli-flags/src/lib.rs (revision b0ffce1a)
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         /// Byte size of the guard region after dynamic memories are allocated
46         pub dynamic_memory_guard_size: Option<u64>,
47 
48         /// Force using a "static" style for all wasm memories
49         pub static_memory_forced: Option<bool>,
50 
51         /// Maximum size in bytes of wasm memory before it becomes dynamically
52         /// relocatable instead of up-front-reserved.
53         pub static_memory_maximum_size: Option<u64>,
54 
55         /// Byte size of the guard region after static memories are allocated
56         pub static_memory_guard_size: Option<u64>,
57 
58         /// Bytes to reserve at the end of linear memory for growth for dynamic
59         /// memories.
60         pub dynamic_memory_reserved_for_growth: Option<u64>,
61 
62         /// Indicates whether an unmapped region of memory is placed before all
63         /// linear memories.
64         pub guard_before_linear_memory: Option<bool>,
65 
66         /// Whether to initialize tables lazily, so that instantiation is
67         /// fast but indirect calls are a little slower. If no, tables are
68         /// initialized eagerly from any active element segments that apply to
69         /// them during instantiation. (default: yes)
70         pub table_lazy_init: Option<bool>,
71 
72         /// Enable the pooling allocator, in place of the on-demand allocator.
73         pub pooling_allocator: Option<bool>,
74 
75         /// The number of decommits to do per batch. A batch size of 1
76         /// effectively disables decommit batching. (default: 1)
77         pub pooling_decommit_batch_size: Option<u32>,
78 
79         /// How many bytes to keep resident between instantiations for the
80         /// pooling allocator in linear memories.
81         pub pooling_memory_keep_resident: Option<usize>,
82 
83         /// How many bytes to keep resident between instantiations for the
84         /// pooling allocator in tables.
85         pub pooling_table_keep_resident: Option<usize>,
86 
87         /// Enable memory protection keys for the pooling allocator; this can
88         /// optimize the size of memory slots.
89         pub memory_protection_keys: Option<bool>,
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         /// Enable or disable the use of host signal handlers for traps.
128         pub signals_based_traps: Option<bool>,
129     }
130 
131     enum Optimize {
132         ...
133     }
134 }
135 
136 wasmtime_option_group! {
137     #[derive(PartialEq, Clone)]
138     pub struct CodegenOptions {
139         /// Either `cranelift` or `winch`.
140         ///
141         /// Currently only `cranelift` and `winch` are supported, but not all
142         /// builds of Wasmtime have both built in.
143         pub compiler: Option<wasmtime::Strategy>,
144         /// Enable Cranelift's internal debug verifier (expensive)
145         pub cranelift_debug_verifier: Option<bool>,
146         /// Whether or not to enable caching of compiled modules.
147         pub cache: Option<bool>,
148         /// Configuration for compiled module caching.
149         pub cache_config: Option<String>,
150         /// Whether or not to enable parallel compilation of modules.
151         pub parallel_compilation: Option<bool>,
152         /// Whether to enable proof-carrying code (PCC)-based validation.
153         pub pcc: Option<bool>,
154 
155         #[prefixed = "cranelift"]
156         /// Set a cranelift-specific option. Use `wasmtime settings` to see
157         /// all.
158         pub cranelift: Vec<(String, Option<String>)>,
159     }
160 
161     enum Codegen {
162         ...
163     }
164 }
165 
166 wasmtime_option_group! {
167     #[derive(PartialEq, Clone)]
168     pub struct DebugOptions {
169         /// Enable generation of DWARF debug information in compiled code.
170         pub debug_info: Option<bool>,
171         /// Configure whether compiled code can map native addresses to wasm.
172         pub address_map: Option<bool>,
173         /// Configure whether logging is enabled.
174         pub logging: Option<bool>,
175         /// Configure whether logs are emitted to files
176         pub log_to_files: Option<bool>,
177         /// Enable coredump generation to this file after a WebAssembly trap.
178         pub coredump: Option<String>,
179     }
180 
181     enum Debug {
182         ...
183     }
184 }
185 
186 wasmtime_option_group! {
187     #[derive(PartialEq, Clone)]
188     pub struct WasmOptions {
189         /// Enable canonicalization of all NaN values.
190         pub nan_canonicalization: Option<bool>,
191         /// Enable execution fuel with N units fuel, trapping after running out
192         /// of fuel.
193         ///
194         /// Most WebAssembly instructions consume 1 unit of fuel. Some
195         /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0
196         /// units, as any execution cost associated with them involves other
197         /// instructions which do consume fuel.
198         pub fuel: Option<u64>,
199         /// Yield when a global epoch counter changes, allowing for async
200         /// operation without blocking the executor.
201         pub epoch_interruption: Option<bool>,
202         /// Maximum stack size, in bytes, that wasm is allowed to consume before a
203         /// stack overflow is reported.
204         pub max_wasm_stack: Option<usize>,
205         /// Allow unknown exports when running commands.
206         pub unknown_exports_allow: Option<bool>,
207         /// Allow the main module to import unknown functions, using an
208         /// implementation that immediately traps, when running commands.
209         pub unknown_imports_trap: Option<bool>,
210         /// Allow the main module to import unknown functions, using an
211         /// implementation that returns default values, when running commands.
212         pub unknown_imports_default: Option<bool>,
213         /// Enables memory error checking. (see wmemcheck.md for more info)
214         pub wmemcheck: Option<bool>,
215         /// Maximum size, in bytes, that a linear memory is allowed to reach.
216         ///
217         /// Growth beyond this limit will cause `memory.grow` instructions in
218         /// WebAssembly modules to return -1 and fail.
219         pub max_memory_size: Option<usize>,
220         /// Maximum size, in table elements, that a table is allowed to reach.
221         pub max_table_elements: Option<usize>,
222         /// Maximum number of WebAssembly instances allowed to be created.
223         pub max_instances: Option<usize>,
224         /// Maximum number of WebAssembly tables allowed to be created.
225         pub max_tables: Option<usize>,
226         /// Maximum number of WebAssembly linear memories allowed to be created.
227         pub max_memories: Option<usize>,
228         /// Force a trap to be raised on `memory.grow` and `table.grow` failure
229         /// instead of returning -1 from these instructions.
230         ///
231         /// This is not necessarily a spec-compliant option to enable but can be
232         /// useful for tracking down a backtrace of what is requesting so much
233         /// memory, for example.
234         pub trap_on_grow_failure: Option<bool>,
235         /// Maximum execution time of wasm code before timing out (1, 2s, 100ms, etc)
236         pub timeout: Option<Duration>,
237         /// Configures support for all WebAssembly proposals implemented.
238         pub all_proposals: Option<bool>,
239         /// Configure support for the bulk memory proposal.
240         pub bulk_memory: Option<bool>,
241         /// Configure support for the multi-memory proposal.
242         pub multi_memory: Option<bool>,
243         /// Configure support for the multi-value proposal.
244         pub multi_value: Option<bool>,
245         /// Configure support for the reference-types proposal.
246         pub reference_types: Option<bool>,
247         /// Configure support for the simd proposal.
248         pub simd: Option<bool>,
249         /// Configure support for the relaxed-simd proposal.
250         pub relaxed_simd: Option<bool>,
251         /// Configure forcing deterministic and host-independent behavior of
252         /// the relaxed-simd instructions.
253         ///
254         /// By default these instructions may have architecture-specific behavior as
255         /// allowed by the specification, but this can be used to force the behavior
256         /// of these instructions to match the deterministic behavior classified in
257         /// the specification. Note that enabling this option may come at a
258         /// performance cost.
259         pub relaxed_simd_deterministic: Option<bool>,
260         /// Configure support for the tail-call proposal.
261         pub tail_call: Option<bool>,
262         /// Configure support for the threads proposal.
263         pub threads: Option<bool>,
264         /// Configure support for the memory64 proposal.
265         pub memory64: Option<bool>,
266         /// Configure support for the component-model proposal.
267         pub component_model: Option<bool>,
268         /// Configure support for 33+ flags in the component model.
269         pub component_model_more_flags: Option<bool>,
270         /// Component model support for more than one return value.
271         pub component_model_multiple_returns: Option<bool>,
272         /// Configure support for the function-references proposal.
273         pub function_references: Option<bool>,
274         /// Configure support for the GC proposal.
275         pub gc: Option<bool>,
276         /// Configure support for the custom-page-sizes proposal.
277         pub custom_page_sizes: Option<bool>,
278     }
279 
280     enum Wasm {
281         ...
282     }
283 }
284 
285 wasmtime_option_group! {
286     #[derive(PartialEq, Clone)]
287     pub struct WasiOptions {
288         /// Enable support for WASI CLI APIs, including filesystems, sockets, clocks, and random.
289         pub cli: Option<bool>,
290         /// Deprecated alias for `cli`
291         pub common: Option<bool>,
292         /// Enable support for WASI neural network API (experimental)
293         pub nn: Option<bool>,
294         /// Enable support for WASI threading API (experimental)
295         pub threads: Option<bool>,
296         /// Enable support for WASI HTTP API (experimental)
297         pub http: Option<bool>,
298         /// Enable support for WASI runtime config API (experimental)
299         pub runtime_config: Option<bool>,
300         /// Enable support for WASI key-value API (experimental)
301         pub keyvalue: Option<bool>,
302         /// Inherit environment variables and file descriptors following the
303         /// systemd listen fd specification (UNIX only)
304         pub listenfd: Option<bool>,
305         /// Grant access to the given TCP listen socket
306         pub tcplisten: Vec<String>,
307         /// Implement WASI CLI APIs with preview2 primitives (experimental).
308         ///
309         /// Indicates that the implementation of WASI preview1 should be backed by
310         /// the preview2 implementation for components.
311         ///
312         /// This will become the default in the future and this option will be
313         /// removed. For now this is primarily here for testing.
314         pub preview2: Option<bool>,
315         /// Pre-load machine learning graphs (i.e., models) for use by wasi-nn.
316         ///
317         /// Each use of the flag will preload a ML model from the host directory
318         /// using the given model encoding. The model will be mapped to the
319         /// directory name: e.g., `--wasi-nn-graph openvino:/foo/bar` will preload
320         /// an OpenVINO model named `bar`. Note that which model encodings are
321         /// available is dependent on the backends implemented in the
322         /// `wasmtime_wasi_nn` crate.
323         pub nn_graph: Vec<WasiNnGraph>,
324         /// Flag for WASI preview2 to inherit the host's network within the
325         /// guest so it has full access to all addresses/ports/etc.
326         pub inherit_network: Option<bool>,
327         /// Indicates whether `wasi:sockets/ip-name-lookup` is enabled or not.
328         pub allow_ip_name_lookup: Option<bool>,
329         /// Indicates whether `wasi:sockets` TCP support is enabled or not.
330         pub tcp: Option<bool>,
331         /// Indicates whether `wasi:sockets` UDP support is enabled or not.
332         pub udp: Option<bool>,
333         /// Allows imports from the `wasi_unstable` core wasm module.
334         pub preview0: Option<bool>,
335         /// Inherit all environment variables from the parent process.
336         ///
337         /// This option can be further overwritten with `--env` flags.
338         pub inherit_env: Option<bool>,
339         /// Pass a wasi runtime config variable to the program.
340         pub runtime_config_var: Vec<KeyValuePair>,
341         /// Preset data for the In-Memory provider of WASI key-value API.
342         pub keyvalue_in_memory_data: Vec<KeyValuePair>,
343     }
344 
345     enum Wasi {
346         ...
347     }
348 }
349 
350 #[derive(Debug, Clone, PartialEq)]
351 pub struct WasiNnGraph {
352     pub format: String,
353     pub dir: String,
354 }
355 
356 #[derive(Debug, Clone, PartialEq)]
357 pub struct KeyValuePair {
358     pub key: String,
359     pub value: String,
360 }
361 
362 /// Common options for commands that translate WebAssembly modules
363 #[derive(Parser, Clone)]
364 pub struct CommonOptions {
365     // These options groups are used to parse `-O` and such options but aren't
366     // the raw form consumed by the CLI. Instead they're pushed into the `pub`
367     // fields below as part of the `configure` method.
368     //
369     // Ideally clap would support `pub opts: OptimizeOptions` and parse directly
370     // into that but it does not appear to do so for multiple `-O` flags for
371     // now.
372     /// Optimization and tuning related options for wasm performance, `-O help` to
373     /// see all.
374     #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")]
375     opts_raw: Vec<opt::CommaSeparated<Optimize>>,
376 
377     /// Codegen-related configuration options, `-C help` to see all.
378     #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")]
379     codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
380 
381     /// Debug-related configuration options, `-D help` to see all.
382     #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")]
383     debug_raw: Vec<opt::CommaSeparated<Debug>>,
384 
385     /// Options for configuring semantic execution of WebAssembly, `-W help` to see
386     /// all.
387     #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")]
388     wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
389 
390     /// Options for configuring WASI and its proposals, `-S help` to see all.
391     #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")]
392     wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
393 
394     // These fields are filled in by the `configure` method below via the
395     // options parsed from the CLI above. This is what the CLI should use.
396     #[arg(skip)]
397     configured: bool,
398     #[arg(skip)]
399     pub opts: OptimizeOptions,
400     #[arg(skip)]
401     pub codegen: CodegenOptions,
402     #[arg(skip)]
403     pub debug: DebugOptions,
404     #[arg(skip)]
405     pub wasm: WasmOptions,
406     #[arg(skip)]
407     pub wasi: WasiOptions,
408 }
409 
410 macro_rules! match_feature {
411     (
412         [$feat:tt : $config:expr]
413         $val:ident => $e:expr,
414         $p:pat => err,
415     ) => {
416         #[cfg(feature = $feat)]
417         {
418             if let Some($val) = $config {
419                 $e;
420             }
421         }
422         #[cfg(not(feature = $feat))]
423         {
424             if let Some($p) = $config {
425                 anyhow::bail!(concat!("support for ", $feat, " disabled at compile time"));
426             }
427         }
428     };
429 }
430 
431 impl CommonOptions {
432     fn configure(&mut self) {
433         if self.configured {
434             return;
435         }
436         self.configured = true;
437         self.opts.configure_with(&self.opts_raw);
438         self.codegen.configure_with(&self.codegen_raw);
439         self.debug.configure_with(&self.debug_raw);
440         self.wasm.configure_with(&self.wasm_raw);
441         self.wasi.configure_with(&self.wasi_raw);
442     }
443 
444     pub fn init_logging(&mut self) -> Result<()> {
445         self.configure();
446         if self.debug.logging == Some(false) {
447             return Ok(());
448         }
449         #[cfg(feature = "logging")]
450         if self.debug.log_to_files == Some(true) {
451             let prefix = "wasmtime.dbg.";
452             init_file_per_thread_logger(prefix);
453         } else {
454             use std::io::IsTerminal;
455             use tracing_subscriber::{EnvFilter, FmtSubscriber};
456             let b = FmtSubscriber::builder()
457                 .with_writer(std::io::stderr)
458                 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
459                 .with_ansi(std::io::stderr().is_terminal());
460             b.init();
461         }
462         #[cfg(not(feature = "logging"))]
463         if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
464             anyhow::bail!("support for logging disabled at compile time");
465         }
466         Ok(())
467     }
468 
469     pub fn config(
470         &mut self,
471         target: Option<&str>,
472         pooling_allocator_default: Option<bool>,
473     ) -> Result<Config> {
474         self.configure();
475         let mut config = Config::new();
476 
477         match_feature! {
478             ["cranelift" : self.codegen.compiler]
479             strategy => config.strategy(strategy),
480             _ => err,
481         }
482         match_feature! {
483             ["cranelift" : target]
484             target => config.target(target)?,
485             _ => err,
486         }
487         match_feature! {
488             ["cranelift" : self.codegen.cranelift_debug_verifier]
489             enable => config.cranelift_debug_verifier(enable),
490             true => err,
491         }
492         if let Some(enable) = self.debug.debug_info {
493             config.debug_info(enable);
494         }
495         if self.debug.coredump.is_some() {
496             #[cfg(feature = "coredump")]
497             config.coredump_on_trap(true);
498             #[cfg(not(feature = "coredump"))]
499             anyhow::bail!("support for coredumps disabled at compile time");
500         }
501         match_feature! {
502             ["cranelift" : self.opts.opt_level]
503             level => config.cranelift_opt_level(level),
504             _ => err,
505         }
506         match_feature! {
507             ["cranelift" : self.wasm.nan_canonicalization]
508             enable => config.cranelift_nan_canonicalization(enable),
509             true => err,
510         }
511         match_feature! {
512             ["cranelift" : self.codegen.pcc]
513             enable => config.cranelift_pcc(enable),
514             true => err,
515         }
516 
517         self.enable_wasm_features(&mut config)?;
518 
519         #[cfg(feature = "cranelift")]
520         for (name, value) in self.codegen.cranelift.iter() {
521             let name = name.replace('-', "_");
522             unsafe {
523                 match value {
524                     Some(val) => {
525                         config.cranelift_flag_set(&name, val);
526                     }
527                     None => {
528                         config.cranelift_flag_enable(&name);
529                     }
530                 }
531             }
532         }
533         #[cfg(not(feature = "cranelift"))]
534         if !self.codegen.cranelift.is_empty() {
535             anyhow::bail!("support for cranelift disabled at compile time");
536         }
537 
538         #[cfg(feature = "cache")]
539         if self.codegen.cache != Some(false) {
540             match &self.codegen.cache_config {
541                 Some(path) => {
542                     config.cache_config_load(path)?;
543                 }
544                 None => {
545                     config.cache_config_load_default()?;
546                 }
547             }
548         }
549         #[cfg(not(feature = "cache"))]
550         if self.codegen.cache == Some(true) {
551             anyhow::bail!("support for caching disabled at compile time");
552         }
553 
554         match_feature! {
555             ["parallel-compilation" : self.codegen.parallel_compilation]
556             enable => config.parallel_compilation(enable),
557             true => err,
558         }
559 
560         if let Some(max) = self.opts.static_memory_maximum_size {
561             config.static_memory_maximum_size(max);
562         }
563 
564         if let Some(enable) = self.opts.static_memory_forced {
565             config.static_memory_forced(enable);
566         }
567 
568         if let Some(size) = self.opts.static_memory_guard_size {
569             config.static_memory_guard_size(size);
570         }
571 
572         if let Some(size) = self.opts.dynamic_memory_guard_size {
573             config.dynamic_memory_guard_size(size);
574         }
575         if let Some(size) = self.opts.dynamic_memory_reserved_for_growth {
576             config.dynamic_memory_reserved_for_growth(size);
577         }
578         if let Some(enable) = self.opts.guard_before_linear_memory {
579             config.guard_before_linear_memory(enable);
580         }
581         if let Some(enable) = self.opts.table_lazy_init {
582             config.table_lazy_init(enable);
583         }
584 
585         // If fuel has been configured, set the `consume fuel` flag on the config.
586         if self.wasm.fuel.is_some() {
587             config.consume_fuel(true);
588         }
589 
590         if let Some(enable) = self.wasm.epoch_interruption {
591             config.epoch_interruption(enable);
592         }
593         if let Some(enable) = self.debug.address_map {
594             config.generate_address_map(enable);
595         }
596         if let Some(enable) = self.opts.memory_init_cow {
597             config.memory_init_cow(enable);
598         }
599         if let Some(enable) = self.opts.signals_based_traps {
600             config.signals_based_traps(enable);
601         }
602 
603         match_feature! {
604             ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
605             enable => {
606                 if enable {
607                     let mut cfg = wasmtime::PoolingAllocationConfig::default();
608                     if let Some(size) = self.opts.pooling_memory_keep_resident {
609                         cfg.linear_memory_keep_resident(size);
610                     }
611                     if let Some(size) = self.opts.pooling_table_keep_resident {
612                         cfg.table_keep_resident(size);
613                     }
614                     if let Some(limit) = self.opts.pooling_total_core_instances {
615                         cfg.total_core_instances(limit);
616                     }
617                     if let Some(limit) = self.opts.pooling_total_component_instances {
618                         cfg.total_component_instances(limit);
619                     }
620                     if let Some(limit) = self.opts.pooling_total_memories {
621                         cfg.total_memories(limit);
622                     }
623                     if let Some(limit) = self.opts.pooling_total_tables {
624                         cfg.total_tables(limit);
625                     }
626                     if let Some(limit) = self.opts.pooling_table_elements {
627                         cfg.table_elements(limit);
628                     }
629                     if let Some(limit) = self.opts.pooling_max_core_instance_size {
630                         cfg.max_core_instance_size(limit);
631                     }
632                     match_feature! {
633                         ["async" : self.opts.pooling_total_stacks]
634                         limit => cfg.total_stacks(limit),
635                         _ => err,
636                     }
637                     if let Some(limit) = self.opts.pooling_max_memory_size {
638                         cfg.max_memory_size(limit);
639                     }
640                     match_feature! {
641                         ["memory-protection-keys" : self.opts.memory_protection_keys]
642                         enable => cfg.memory_protection_keys(if enable {
643                             wasmtime::MpkEnabled::Enable
644                         } else {
645                             wasmtime::MpkEnabled::Disable
646                         }),
647                         _ => err,
648                     }
649                     config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
650                 }
651             },
652             true => err,
653         }
654 
655         if self.opts.memory_protection_keys.unwrap_or(false)
656             && !self.opts.pooling_allocator.unwrap_or(false)
657         {
658             anyhow::bail!("memory protection keys require the pooling allocator");
659         }
660 
661         if let Some(max) = self.wasm.max_wasm_stack {
662             config.max_wasm_stack(max);
663         }
664 
665         if let Some(enable) = self.wasm.relaxed_simd_deterministic {
666             config.relaxed_simd_deterministic(enable);
667         }
668         match_feature! {
669             ["cranelift" : self.wasm.wmemcheck]
670             enable => config.wmemcheck(enable),
671             true => err,
672         }
673 
674         Ok(config)
675     }
676 
677     pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
678         let all = self.wasm.all_proposals;
679 
680         if let Some(enable) = self.wasm.simd.or(all) {
681             config.wasm_simd(enable);
682         }
683         if let Some(enable) = self.wasm.relaxed_simd.or(all) {
684             config.wasm_relaxed_simd(enable);
685         }
686         if let Some(enable) = self.wasm.bulk_memory.or(all) {
687             config.wasm_bulk_memory(enable);
688         }
689         if let Some(enable) = self.wasm.multi_value.or(all) {
690             config.wasm_multi_value(enable);
691         }
692         if let Some(enable) = self.wasm.tail_call.or(all) {
693             config.wasm_tail_call(enable);
694         }
695         if let Some(enable) = self.wasm.multi_memory.or(all) {
696             config.wasm_multi_memory(enable);
697         }
698         if let Some(enable) = self.wasm.memory64.or(all) {
699             config.wasm_memory64(enable);
700         }
701         if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
702             config.wasm_custom_page_sizes(enable);
703         }
704 
705         macro_rules! handle_conditionally_compiled {
706             ($(($feature:tt, $field:tt, $method:tt))*) => ($(
707                 if let Some(enable) = self.wasm.$field.or(all) {
708                     #[cfg(feature = $feature)]
709                     config.$method(enable);
710                     #[cfg(not(feature = $feature))]
711                     if enable && all.is_none() {
712                         anyhow::bail!("support for {} was disabled at compile-time", $feature);
713                     }
714                 }
715             )*)
716         }
717 
718         handle_conditionally_compiled! {
719             ("component-model", component_model, wasm_component_model)
720             ("component-model", component_model_more_flags, wasm_component_model_more_flags)
721             ("component-model", component_model_multiple_returns, wasm_component_model_multiple_returns)
722             ("threads", threads, wasm_threads)
723             ("gc", gc, wasm_gc)
724             ("gc", reference_types, wasm_reference_types)
725             ("gc", function_references, wasm_function_references)
726         }
727         Ok(())
728     }
729 }
730 
731 impl PartialEq for CommonOptions {
732     fn eq(&self, other: &CommonOptions) -> bool {
733         let mut me = self.clone();
734         me.configure();
735         let mut other = other.clone();
736         other.configure();
737         let CommonOptions {
738             opts_raw: _,
739             codegen_raw: _,
740             debug_raw: _,
741             wasm_raw: _,
742             wasi_raw: _,
743             configured: _,
744 
745             opts,
746             codegen,
747             debug,
748             wasm,
749             wasi,
750         } = me;
751         opts == other.opts
752             && codegen == other.codegen
753             && debug == other.debug
754             && wasm == other.wasm
755             && wasi == other.wasi
756     }
757 }
758