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