xref: /wasmtime-44.0.1/crates/cli-flags/src/lib.rs (revision eced7c7e)
1 //! Contains the common Wasmtime command line interface (CLI) flags.
2 
3 use anyhow::{Context, Result};
4 use clap::Parser;
5 use serde::Deserialize;
6 use std::{
7     fmt, fs,
8     path::{Path, PathBuf},
9     time::Duration,
10 };
11 use wasmtime::Config;
12 
13 pub mod opt;
14 
15 #[cfg(feature = "logging")]
16 fn init_file_per_thread_logger(prefix: &'static str) {
17     file_per_thread_logger::initialize(prefix);
18     file_per_thread_logger::allow_uninitialized();
19 
20     // Extending behavior of default spawner:
21     // https://docs.rs/rayon/1.1.0/rayon/struct.ThreadPoolBuilder.html#method.spawn_handler
22     // Source code says DefaultSpawner is implementation detail and
23     // shouldn't be used directly.
24     #[cfg(feature = "parallel-compilation")]
25     rayon::ThreadPoolBuilder::new()
26         .spawn_handler(move |thread| {
27             let mut b = std::thread::Builder::new();
28             if let Some(name) = thread.name() {
29                 b = b.name(name.to_owned());
30             }
31             if let Some(stack_size) = thread.stack_size() {
32                 b = b.stack_size(stack_size);
33             }
34             b.spawn(move || {
35                 file_per_thread_logger::initialize(prefix);
36                 thread.run()
37             })?;
38             Ok(())
39         })
40         .build_global()
41         .unwrap();
42 }
43 
44 wasmtime_option_group! {
45     #[derive(PartialEq, Clone, Deserialize)]
46     #[serde(rename_all = "kebab-case", deny_unknown_fields)]
47     pub struct OptimizeOptions {
48         /// Optimization level of generated code (0-2, s; default: 2)
49         #[serde(default)]
50         #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
51         pub opt_level: Option<wasmtime::OptLevel>,
52 
53         /// Register allocator algorithm choice.
54         #[serde(default)]
55         #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
56         pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,
57 
58         /// Do not allow Wasm linear memories to move in the host process's
59         /// address space.
60         pub memory_may_move: Option<bool>,
61 
62         /// Initial virtual memory allocation size for memories.
63         pub memory_reservation: Option<u64>,
64 
65         /// Bytes to reserve at the end of linear memory for growth into.
66         pub memory_reservation_for_growth: Option<u64>,
67 
68         /// Size, in bytes, of guard pages for linear memories.
69         pub memory_guard_size: Option<u64>,
70 
71         /// Indicates whether an unmapped region of memory is placed before all
72         /// linear memories.
73         pub guard_before_linear_memory: Option<bool>,
74 
75         /// Whether to initialize tables lazily, so that instantiation is
76         /// fast but indirect calls are a little slower. If no, tables are
77         /// initialized eagerly from any active element segments that apply to
78         /// them during instantiation. (default: yes)
79         pub table_lazy_init: Option<bool>,
80 
81         /// Enable the pooling allocator, in place of the on-demand allocator.
82         pub pooling_allocator: Option<bool>,
83 
84         /// The number of decommits to do per batch. A batch size of 1
85         /// effectively disables decommit batching. (default: 1)
86         pub pooling_decommit_batch_size: Option<usize>,
87 
88         /// How many bytes to keep resident between instantiations for the
89         /// pooling allocator in linear memories.
90         pub pooling_memory_keep_resident: Option<usize>,
91 
92         /// How many bytes to keep resident between instantiations for the
93         /// pooling allocator in tables.
94         pub pooling_table_keep_resident: Option<usize>,
95 
96         /// Enable memory protection keys for the pooling allocator; this can
97         /// optimize the size of memory slots.
98         #[serde(default)]
99         #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
100         pub pooling_memory_protection_keys: Option<wasmtime::MpkEnabled>,
101 
102         /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime
103         /// will use. (default: 16)
104         pub pooling_max_memory_protection_keys: Option<usize>,
105 
106         /// Configure attempting to initialize linear memory via a
107         /// copy-on-write mapping (default: yes)
108         pub memory_init_cow: Option<bool>,
109 
110         /// Threshold below which CoW images are guaranteed to be used and be
111         /// dense.
112         pub memory_guaranteed_dense_image_size: Option<u64>,
113 
114         /// The maximum number of WebAssembly instances which can be created
115         /// with the pooling allocator.
116         pub pooling_total_core_instances: Option<u32>,
117 
118         /// The maximum number of WebAssembly components which can be created
119         /// with the pooling allocator.
120         pub pooling_total_component_instances: Option<u32>,
121 
122         /// The maximum number of WebAssembly memories which can be created with
123         /// the pooling allocator.
124         pub pooling_total_memories: Option<u32>,
125 
126         /// The maximum number of WebAssembly tables which can be created with
127         /// the pooling allocator.
128         pub pooling_total_tables: Option<u32>,
129 
130         /// The maximum number of WebAssembly stacks which can be created with
131         /// the pooling allocator.
132         pub pooling_total_stacks: Option<u32>,
133 
134         /// The maximum runtime size of each linear memory in the pooling
135         /// allocator, in bytes.
136         pub pooling_max_memory_size: Option<usize>,
137 
138         /// The maximum table elements for any table defined in a module when
139         /// using the pooling allocator.
140         pub pooling_table_elements: Option<usize>,
141 
142         /// The maximum size, in bytes, allocated for a core instance's metadata
143         /// when using the pooling allocator.
144         pub pooling_max_core_instance_size: Option<usize>,
145 
146         /// Configures the maximum number of "unused warm slots" to retain in the
147         /// pooling allocator. (default: 100)
148         pub pooling_max_unused_warm_slots: Option<u32>,
149 
150         /// How much memory, in bytes, to keep resident for async stacks allocated
151         /// with the pooling allocator. (default: 0)
152         pub pooling_async_stack_keep_resident: Option<usize>,
153 
154         /// The maximum size, in bytes, allocated for a component instance's
155         /// `VMComponentContext` metadata. (default: 1MiB)
156         pub pooling_max_component_instance_size: Option<usize>,
157 
158         /// The maximum number of core instances a single component may contain
159         /// (default is unlimited).
160         pub pooling_max_core_instances_per_component: Option<u32>,
161 
162         /// The maximum number of Wasm linear memories that a single component may
163         /// transitively contain (default is unlimited).
164         pub pooling_max_memories_per_component: Option<u32>,
165 
166         /// The maximum number of tables that a single component may transitively
167         /// contain (default is unlimited).
168         pub pooling_max_tables_per_component: Option<u32>,
169 
170         /// The maximum number of defined tables for a core module. (default: 1)
171         pub pooling_max_tables_per_module: Option<u32>,
172 
173         /// The maximum number of defined linear memories for a module. (default: 1)
174         pub pooling_max_memories_per_module: Option<u32>,
175 
176         /// The maximum number of concurrent GC heaps supported. (default: 1000)
177         pub pooling_total_gc_heaps: Option<u32>,
178 
179         /// Enable or disable the use of host signal handlers for traps.
180         pub signals_based_traps: Option<bool>,
181 
182         /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
183         pub dynamic_memory_guard_size: Option<u64>,
184 
185         /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
186         pub static_memory_guard_size: Option<u64>,
187 
188         /// DEPRECATED: Use `-Cmemory-may-move` instead.
189         pub static_memory_forced: Option<bool>,
190 
191         /// DEPRECATED: Use `-Cmemory-reservation=N` instead.
192         pub static_memory_maximum_size: Option<u64>,
193 
194         /// DEPRECATED: Use `-Cmemory-reservation-for-growth=N` instead.
195         pub dynamic_memory_reserved_for_growth: Option<u64>,
196     }
197 
198     enum Optimize {
199         ...
200     }
201 }
202 
203 wasmtime_option_group! {
204     #[derive(PartialEq, Clone, Deserialize)]
205     #[serde(rename_all = "kebab-case", deny_unknown_fields)]
206     pub struct CodegenOptions {
207         /// Either `cranelift` or `winch`.
208         ///
209         /// Currently only `cranelift` and `winch` are supported, but not all
210         /// builds of Wasmtime have both built in.
211         #[serde(default)]
212         #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
213         pub compiler: Option<wasmtime::Strategy>,
214         /// Which garbage collector to use: `drc` or `null`.
215         ///
216         /// `drc` is the deferred reference-counting collector.
217         ///
218         /// `null` is the null garbage collector, which does not collect any
219         /// garbage.
220         ///
221         /// Note that not all builds of Wasmtime will have support for garbage
222         /// collection included.
223         #[serde(default)]
224         #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
225         pub collector: Option<wasmtime::Collector>,
226         /// Enable Cranelift's internal debug verifier (expensive)
227         pub cranelift_debug_verifier: Option<bool>,
228         /// Whether or not to enable caching of compiled modules.
229         pub cache: Option<bool>,
230         /// Configuration for compiled module caching.
231         pub cache_config: Option<String>,
232         /// Whether or not to enable parallel compilation of modules.
233         pub parallel_compilation: Option<bool>,
234         /// Whether to enable proof-carrying code (PCC)-based validation.
235         pub pcc: Option<bool>,
236         /// Controls whether native unwind information is present in compiled
237         /// object files.
238         pub native_unwind_info: Option<bool>,
239 
240         /// Whether to perform function inlining during compilation.
241         pub inlining: Option<bool>,
242 
243         #[prefixed = "cranelift"]
244         #[serde(default)]
245         /// Set a cranelift-specific option. Use `wasmtime settings` to see
246         /// all.
247         pub cranelift: Vec<(String, Option<String>)>,
248     }
249 
250     enum Codegen {
251         ...
252     }
253 }
254 
255 wasmtime_option_group! {
256     #[derive(PartialEq, Clone, Deserialize)]
257     #[serde(rename_all = "kebab-case", deny_unknown_fields)]
258     pub struct DebugOptions {
259         /// Enable generation of DWARF debug information in compiled code.
260         pub debug_info: Option<bool>,
261         /// Configure whether compiled code can map native addresses to wasm.
262         pub address_map: Option<bool>,
263         /// Configure whether logging is enabled.
264         pub logging: Option<bool>,
265         /// Configure whether logs are emitted to files
266         pub log_to_files: Option<bool>,
267         /// Enable coredump generation to this file after a WebAssembly trap.
268         pub coredump: Option<String>,
269     }
270 
271     enum Debug {
272         ...
273     }
274 }
275 
276 wasmtime_option_group! {
277     #[derive(PartialEq, Clone, Deserialize)]
278     #[serde(rename_all = "kebab-case", deny_unknown_fields)]
279     pub struct WasmOptions {
280         /// Enable canonicalization of all NaN values.
281         pub nan_canonicalization: Option<bool>,
282         /// Enable execution fuel with N units fuel, trapping after running out
283         /// of fuel.
284         ///
285         /// Most WebAssembly instructions consume 1 unit of fuel. Some
286         /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0
287         /// units, as any execution cost associated with them involves other
288         /// instructions which do consume fuel.
289         pub fuel: Option<u64>,
290         /// Yield when a global epoch counter changes, allowing for async
291         /// operation without blocking the executor.
292         pub epoch_interruption: Option<bool>,
293         /// Maximum stack size, in bytes, that wasm is allowed to consume before a
294         /// stack overflow is reported.
295         pub max_wasm_stack: Option<usize>,
296         /// Stack size, in bytes, that will be allocated for async stacks.
297         ///
298         /// Note that this must be larger than `max-wasm-stack` and the
299         /// difference between the two is how much stack the host has to execute
300         /// on.
301         pub async_stack_size: Option<usize>,
302         /// Configures whether or not stacks used for async futures are zeroed
303         /// before (re)use as a defense-in-depth mechanism. (default: false)
304         pub async_stack_zeroing: Option<bool>,
305         /// Allow unknown exports when running commands.
306         pub unknown_exports_allow: Option<bool>,
307         /// Allow the main module to import unknown functions, using an
308         /// implementation that immediately traps, when running commands.
309         pub unknown_imports_trap: Option<bool>,
310         /// Allow the main module to import unknown functions, using an
311         /// implementation that returns default values, when running commands.
312         pub unknown_imports_default: Option<bool>,
313         /// Enables memory error checking. (see wmemcheck.md for more info)
314         pub wmemcheck: Option<bool>,
315         /// Maximum size, in bytes, that a linear memory is allowed to reach.
316         ///
317         /// Growth beyond this limit will cause `memory.grow` instructions in
318         /// WebAssembly modules to return -1 and fail.
319         pub max_memory_size: Option<usize>,
320         /// Maximum size, in table elements, that a table is allowed to reach.
321         pub max_table_elements: Option<usize>,
322         /// Maximum number of WebAssembly instances allowed to be created.
323         pub max_instances: Option<usize>,
324         /// Maximum number of WebAssembly tables allowed to be created.
325         pub max_tables: Option<usize>,
326         /// Maximum number of WebAssembly linear memories allowed to be created.
327         pub max_memories: Option<usize>,
328         /// Force a trap to be raised on `memory.grow` and `table.grow` failure
329         /// instead of returning -1 from these instructions.
330         ///
331         /// This is not necessarily a spec-compliant option to enable but can be
332         /// useful for tracking down a backtrace of what is requesting so much
333         /// memory, for example.
334         pub trap_on_grow_failure: Option<bool>,
335         /// Maximum execution time of wasm code before timing out (1, 2s, 100ms, etc)
336         pub timeout: Option<Duration>,
337         /// Configures support for all WebAssembly proposals implemented.
338         pub all_proposals: Option<bool>,
339         /// Configure support for the bulk memory proposal.
340         pub bulk_memory: Option<bool>,
341         /// Configure support for the multi-memory proposal.
342         pub multi_memory: Option<bool>,
343         /// Configure support for the multi-value proposal.
344         pub multi_value: Option<bool>,
345         /// Configure support for the reference-types proposal.
346         pub reference_types: Option<bool>,
347         /// Configure support for the simd proposal.
348         pub simd: Option<bool>,
349         /// Configure support for the relaxed-simd proposal.
350         pub relaxed_simd: Option<bool>,
351         /// Configure forcing deterministic and host-independent behavior of
352         /// the relaxed-simd instructions.
353         ///
354         /// By default these instructions may have architecture-specific behavior as
355         /// allowed by the specification, but this can be used to force the behavior
356         /// of these instructions to match the deterministic behavior classified in
357         /// the specification. Note that enabling this option may come at a
358         /// performance cost.
359         pub relaxed_simd_deterministic: Option<bool>,
360         /// Configure support for the tail-call proposal.
361         pub tail_call: Option<bool>,
362         /// Configure support for the threads proposal.
363         pub threads: Option<bool>,
364         /// Configure support for the shared-everything-threads proposal.
365         pub shared_everything_threads: Option<bool>,
366         /// Configure support for the memory64 proposal.
367         pub memory64: Option<bool>,
368         /// Configure support for the component-model proposal.
369         pub component_model: Option<bool>,
370         /// Component model support for async lifting/lowering.
371         pub component_model_async: Option<bool>,
372         /// Component model support for async lifting/lowering: this corresponds
373         /// to the �� emoji in the component model specification.
374         pub component_model_async_builtins: Option<bool>,
375         /// Component model support for async lifting/lowering: this corresponds
376         /// to the �� emoji in the component model specification.
377         pub component_model_async_stackful: Option<bool>,
378         /// Component model support for `error-context`: this corresponds
379         /// to the �� emoji in the component model specification.
380         pub component_model_error_context: Option<bool>,
381         /// GC support in the component model: this corresponds to the �� emoji
382         /// in the component model specification.
383         pub component_model_gc: Option<bool>,
384         /// Configure support for the function-references proposal.
385         pub function_references: Option<bool>,
386         /// Configure support for the stack-switching proposal.
387         pub stack_switching: Option<bool>,
388         /// Configure support for the GC proposal.
389         pub gc: Option<bool>,
390         /// Configure support for the custom-page-sizes proposal.
391         pub custom_page_sizes: Option<bool>,
392         /// Configure support for the wide-arithmetic proposal.
393         pub wide_arithmetic: Option<bool>,
394         /// Configure support for the extended-const proposal.
395         pub extended_const: Option<bool>,
396         /// Configure support for the exceptions proposal.
397         pub exceptions: Option<bool>,
398         /// DEPRECATED: Configure support for the legacy exceptions proposal.
399         pub legacy_exceptions: Option<bool>,
400     }
401 
402     enum Wasm {
403         ...
404     }
405 }
406 
407 wasmtime_option_group! {
408     #[derive(PartialEq, Clone, Deserialize)]
409     #[serde(rename_all = "kebab-case", deny_unknown_fields)]
410     pub struct WasiOptions {
411         /// Enable support for WASI CLI APIs, including filesystems, sockets, clocks, and random.
412         pub cli: Option<bool>,
413         /// Enable WASI APIs marked as: @unstable(feature = cli-exit-with-code)
414         pub cli_exit_with_code: Option<bool>,
415         /// Deprecated alias for `cli`
416         pub common: Option<bool>,
417         /// Enable support for WASI neural network imports (experimental)
418         pub nn: Option<bool>,
419         /// Enable support for WASI threading imports (experimental). Implies preview2=false.
420         pub threads: Option<bool>,
421         /// Enable support for WASI HTTP imports
422         pub http: Option<bool>,
423         /// Number of distinct write calls to the outgoing body's output-stream
424         /// that the implementation will buffer.
425         /// Default: 1.
426         pub http_outgoing_body_buffer_chunks: Option<usize>,
427         /// Maximum size allowed in a write call to the outgoing body's output-stream.
428         /// Default: 1024 * 1024.
429         pub http_outgoing_body_chunk_size: Option<usize>,
430         /// Enable support for WASI config imports (experimental)
431         pub config: Option<bool>,
432         /// Enable support for WASI key-value imports (experimental)
433         pub keyvalue: Option<bool>,
434         /// Inherit environment variables and file descriptors following the
435         /// systemd listen fd specification (UNIX only) (legacy wasip1
436         /// implementation only)
437         pub listenfd: Option<bool>,
438         /// Grant access to the given TCP listen socket (experimental, legacy
439         /// wasip1 implementation only)
440         #[serde(default)]
441         pub tcplisten: Vec<String>,
442         /// Enable support for WASI TLS (Transport Layer Security) imports (experimental)
443         pub tls: Option<bool>,
444         /// Implement WASI Preview1 using new Preview2 implementation (true, default) or legacy
445         /// implementation (false)
446         pub preview2: Option<bool>,
447         /// Pre-load machine learning graphs (i.e., models) for use by wasi-nn.
448         ///
449         /// Each use of the flag will preload a ML model from the host directory
450         /// using the given model encoding. The model will be mapped to the
451         /// directory name: e.g., `--wasi-nn-graph openvino:/foo/bar` will preload
452         /// an OpenVINO model named `bar`. Note that which model encodings are
453         /// available is dependent on the backends implemented in the
454         /// `wasmtime_wasi_nn` crate.
455         #[serde(skip)]
456         pub nn_graph: Vec<WasiNnGraph>,
457         /// Flag for WASI preview2 to inherit the host's network within the
458         /// guest so it has full access to all addresses/ports/etc.
459         pub inherit_network: Option<bool>,
460         /// Indicates whether `wasi:sockets/ip-name-lookup` is enabled or not.
461         pub allow_ip_name_lookup: Option<bool>,
462         /// Indicates whether `wasi:sockets` TCP support is enabled or not.
463         pub tcp: Option<bool>,
464         /// Indicates whether `wasi:sockets` UDP support is enabled or not.
465         pub udp: Option<bool>,
466         /// Enable WASI APIs marked as: @unstable(feature = network-error-code)
467         pub network_error_code: Option<bool>,
468         /// Allows imports from the `wasi_unstable` core wasm module.
469         pub preview0: Option<bool>,
470         /// Inherit all environment variables from the parent process.
471         ///
472         /// This option can be further overwritten with `--env` flags.
473         pub inherit_env: Option<bool>,
474         /// Pass a wasi config variable to the program.
475         #[serde(skip)]
476         pub config_var: Vec<KeyValuePair>,
477         /// Preset data for the In-Memory provider of WASI key-value API.
478         #[serde(skip)]
479         pub keyvalue_in_memory_data: Vec<KeyValuePair>,
480         /// Enable support for WASIp3 APIs.
481         pub p3: Option<bool>,
482     }
483 
484     enum Wasi {
485         ...
486     }
487 }
488 
489 #[derive(Debug, Clone, PartialEq)]
490 pub struct WasiNnGraph {
491     pub format: String,
492     pub dir: String,
493 }
494 
495 #[derive(Debug, Clone, PartialEq)]
496 pub struct KeyValuePair {
497     pub key: String,
498     pub value: String,
499 }
500 
501 /// Common options for commands that translate WebAssembly modules
502 #[derive(Parser, Clone, Deserialize)]
503 #[serde(deny_unknown_fields)]
504 pub struct CommonOptions {
505     // These options groups are used to parse `-O` and such options but aren't
506     // the raw form consumed by the CLI. Instead they're pushed into the `pub`
507     // fields below as part of the `configure` method.
508     //
509     // Ideally clap would support `pub opts: OptimizeOptions` and parse directly
510     // into that but it does not appear to do so for multiple `-O` flags for
511     // now.
512     /// Optimization and tuning related options for wasm performance, `-O help` to
513     /// see all.
514     #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")]
515     #[serde(skip)]
516     opts_raw: Vec<opt::CommaSeparated<Optimize>>,
517 
518     /// Codegen-related configuration options, `-C help` to see all.
519     #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")]
520     #[serde(skip)]
521     codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
522 
523     /// Debug-related configuration options, `-D help` to see all.
524     #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")]
525     #[serde(skip)]
526     debug_raw: Vec<opt::CommaSeparated<Debug>>,
527 
528     /// Options for configuring semantic execution of WebAssembly, `-W help` to see
529     /// all.
530     #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")]
531     #[serde(skip)]
532     wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
533 
534     /// Options for configuring WASI and its proposals, `-S help` to see all.
535     #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")]
536     #[serde(skip)]
537     wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
538 
539     // These fields are filled in by the `configure` method below via the
540     // options parsed from the CLI above. This is what the CLI should use.
541     #[arg(skip)]
542     #[serde(skip)]
543     configured: bool,
544 
545     #[arg(skip)]
546     #[serde(rename = "optimize", default)]
547     pub opts: OptimizeOptions,
548 
549     #[arg(skip)]
550     #[serde(rename = "codegen", default)]
551     pub codegen: CodegenOptions,
552 
553     #[arg(skip)]
554     #[serde(rename = "debug", default)]
555     pub debug: DebugOptions,
556 
557     #[arg(skip)]
558     #[serde(rename = "wasm", default)]
559     pub wasm: WasmOptions,
560 
561     #[arg(skip)]
562     #[serde(rename = "wasi", default)]
563     pub wasi: WasiOptions,
564 
565     /// The target triple; default is the host triple
566     #[arg(long, value_name = "TARGET")]
567     #[serde(skip)]
568     pub target: Option<String>,
569 
570     /// Use the specified TOML configuration file.
571     /// This TOML configuration file can provide same configuration options as the
572     /// `--optimize`, `--codgen`, `--debug`, `--wasm`, `--wasi` CLI options, with a couple exceptions.
573     ///
574     /// Additional options specified on the command line will take precedent over options loaded from
575     /// this TOML file.
576     #[arg(long = "config", value_name = "FILE")]
577     #[serde(skip)]
578     pub config: Option<PathBuf>,
579 }
580 
581 macro_rules! match_feature {
582     (
583         [$feat:tt : $config:expr]
584         $val:ident => $e:expr,
585         $p:pat => err,
586     ) => {
587         #[cfg(feature = $feat)]
588         {
589             if let Some($val) = $config {
590                 $e;
591             }
592         }
593         #[cfg(not(feature = $feat))]
594         {
595             if let Some($p) = $config {
596                 anyhow::bail!(concat!("support for ", $feat, " disabled at compile time"));
597             }
598         }
599     };
600 }
601 
602 impl CommonOptions {
603     /// Creates a blank new set of [`CommonOptions`] that can be configured.
604     pub fn new() -> CommonOptions {
605         CommonOptions {
606             opts_raw: Vec::new(),
607             codegen_raw: Vec::new(),
608             debug_raw: Vec::new(),
609             wasm_raw: Vec::new(),
610             wasi_raw: Vec::new(),
611             configured: true,
612             opts: Default::default(),
613             codegen: Default::default(),
614             debug: Default::default(),
615             wasm: Default::default(),
616             wasi: Default::default(),
617             target: None,
618             config: None,
619         }
620     }
621 
622     fn configure(&mut self) -> Result<()> {
623         if self.configured {
624             return Ok(());
625         }
626         self.configured = true;
627         if let Some(toml_config_path) = &self.config {
628             let toml_options = CommonOptions::from_file(toml_config_path)?;
629             self.opts = toml_options.opts;
630             self.codegen = toml_options.codegen;
631             self.debug = toml_options.debug;
632             self.wasm = toml_options.wasm;
633             self.wasi = toml_options.wasi;
634         }
635         self.opts.configure_with(&self.opts_raw);
636         self.codegen.configure_with(&self.codegen_raw);
637         self.debug.configure_with(&self.debug_raw);
638         self.wasm.configure_with(&self.wasm_raw);
639         self.wasi.configure_with(&self.wasi_raw);
640         Ok(())
641     }
642 
643     pub fn init_logging(&mut self) -> Result<()> {
644         self.configure()?;
645         if self.debug.logging == Some(false) {
646             return Ok(());
647         }
648         #[cfg(feature = "logging")]
649         if self.debug.log_to_files == Some(true) {
650             let prefix = "wasmtime.dbg.";
651             init_file_per_thread_logger(prefix);
652         } else {
653             use std::io::IsTerminal;
654             use tracing_subscriber::{EnvFilter, FmtSubscriber};
655             let builder = FmtSubscriber::builder()
656                 .with_writer(std::io::stderr)
657                 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
658                 .with_ansi(std::io::stderr().is_terminal());
659             if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
660                 builder
661                     .with_level(false)
662                     .with_target(false)
663                     .without_time()
664                     .init()
665             } else {
666                 builder.init();
667             }
668         }
669         #[cfg(not(feature = "logging"))]
670         if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
671             anyhow::bail!("support for logging disabled at compile time");
672         }
673         Ok(())
674     }
675 
676     pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
677         self.configure()?;
678         let mut config = Config::new();
679 
680         match_feature! {
681             ["cranelift" : self.codegen.compiler]
682             strategy => config.strategy(strategy),
683             _ => err,
684         }
685         match_feature! {
686             ["gc" : self.codegen.collector]
687             collector => config.collector(collector),
688             _ => err,
689         }
690         if let Some(target) = &self.target {
691             config.target(target)?;
692         }
693         match_feature! {
694             ["cranelift" : self.codegen.cranelift_debug_verifier]
695             enable => config.cranelift_debug_verifier(enable),
696             true => err,
697         }
698         if let Some(enable) = self.debug.debug_info {
699             config.debug_info(enable);
700         }
701         if self.debug.coredump.is_some() {
702             #[cfg(feature = "coredump")]
703             config.coredump_on_trap(true);
704             #[cfg(not(feature = "coredump"))]
705             anyhow::bail!("support for coredumps disabled at compile time");
706         }
707         match_feature! {
708             ["cranelift" : self.opts.opt_level]
709             level => config.cranelift_opt_level(level),
710             _ => err,
711         }
712         match_feature! {
713             ["cranelift": self.opts.regalloc_algorithm]
714             algo => config.cranelift_regalloc_algorithm(algo),
715             _ => err,
716         }
717         match_feature! {
718             ["cranelift" : self.wasm.nan_canonicalization]
719             enable => config.cranelift_nan_canonicalization(enable),
720             true => err,
721         }
722         match_feature! {
723             ["cranelift" : self.codegen.pcc]
724             enable => config.cranelift_pcc(enable),
725             true => err,
726         }
727 
728         self.enable_wasm_features(&mut config)?;
729 
730         #[cfg(feature = "cranelift")]
731         for (name, value) in self.codegen.cranelift.iter() {
732             let name = name.replace('-', "_");
733             unsafe {
734                 match value {
735                     Some(val) => {
736                         config.cranelift_flag_set(&name, val);
737                     }
738                     None => {
739                         config.cranelift_flag_enable(&name);
740                     }
741                 }
742             }
743         }
744         #[cfg(not(feature = "cranelift"))]
745         if !self.codegen.cranelift.is_empty() {
746             anyhow::bail!("support for cranelift disabled at compile time");
747         }
748 
749         #[cfg(feature = "cache")]
750         if self.codegen.cache != Some(false) {
751             use wasmtime::Cache;
752             let cache = match &self.codegen.cache_config {
753                 Some(path) => Cache::from_file(Some(Path::new(path)))?,
754                 None => Cache::from_file(None)?,
755             };
756             config.cache(Some(cache));
757         }
758         #[cfg(not(feature = "cache"))]
759         if self.codegen.cache == Some(true) {
760             anyhow::bail!("support for caching disabled at compile time");
761         }
762 
763         match_feature! {
764             ["parallel-compilation" : self.codegen.parallel_compilation]
765             enable => config.parallel_compilation(enable),
766             true => err,
767         }
768 
769         let memory_reservation = self
770             .opts
771             .memory_reservation
772             .or(self.opts.static_memory_maximum_size);
773         if let Some(size) = memory_reservation {
774             config.memory_reservation(size);
775         }
776 
777         if let Some(enable) = self.opts.static_memory_forced {
778             config.memory_may_move(!enable);
779         }
780         if let Some(enable) = self.opts.memory_may_move {
781             config.memory_may_move(enable);
782         }
783 
784         let memory_guard_size = self
785             .opts
786             .static_memory_guard_size
787             .or(self.opts.dynamic_memory_guard_size)
788             .or(self.opts.memory_guard_size);
789         if let Some(size) = memory_guard_size {
790             config.memory_guard_size(size);
791         }
792 
793         let mem_for_growth = self
794             .opts
795             .memory_reservation_for_growth
796             .or(self.opts.dynamic_memory_reserved_for_growth);
797         if let Some(size) = mem_for_growth {
798             config.memory_reservation_for_growth(size);
799         }
800         if let Some(enable) = self.opts.guard_before_linear_memory {
801             config.guard_before_linear_memory(enable);
802         }
803         if let Some(enable) = self.opts.table_lazy_init {
804             config.table_lazy_init(enable);
805         }
806 
807         // If fuel has been configured, set the `consume fuel` flag on the config.
808         if self.wasm.fuel.is_some() {
809             config.consume_fuel(true);
810         }
811 
812         if let Some(enable) = self.wasm.epoch_interruption {
813             config.epoch_interruption(enable);
814         }
815         if let Some(enable) = self.debug.address_map {
816             config.generate_address_map(enable);
817         }
818         if let Some(enable) = self.opts.memory_init_cow {
819             config.memory_init_cow(enable);
820         }
821         if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
822             config.memory_guaranteed_dense_image_size(size);
823         }
824         if let Some(enable) = self.opts.signals_based_traps {
825             config.signals_based_traps(enable);
826         }
827         if let Some(enable) = self.codegen.native_unwind_info {
828             config.native_unwind_info(enable);
829         }
830         if let Some(enable) = self.codegen.inlining {
831             config.compiler_inlining(enable);
832         }
833 
834         // async_stack_size enabled by either async or stack-switching, so
835         // cannot directly use match_feature!
836         #[cfg(any(feature = "async", feature = "stack-switching"))]
837         {
838             if let Some(size) = self.wasm.async_stack_size {
839                 config.async_stack_size(size);
840             }
841         }
842         #[cfg(not(any(feature = "async", feature = "stack-switching")))]
843         {
844             if let Some(_size) = self.wasm.async_stack_size {
845                 anyhow::bail!(concat!(
846                     "support for async/stack-switching disabled at compile time"
847                 ));
848             }
849         }
850 
851         match_feature! {
852             ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
853             enable => {
854                 if enable {
855                     let mut cfg = wasmtime::PoolingAllocationConfig::default();
856                     if let Some(size) = self.opts.pooling_memory_keep_resident {
857                         cfg.linear_memory_keep_resident(size);
858                     }
859                     if let Some(size) = self.opts.pooling_table_keep_resident {
860                         cfg.table_keep_resident(size);
861                     }
862                     if let Some(limit) = self.opts.pooling_total_core_instances {
863                         cfg.total_core_instances(limit);
864                     }
865                     if let Some(limit) = self.opts.pooling_total_component_instances {
866                         cfg.total_component_instances(limit);
867                     }
868                     if let Some(limit) = self.opts.pooling_total_memories {
869                         cfg.total_memories(limit);
870                     }
871                     if let Some(limit) = self.opts.pooling_total_tables {
872                         cfg.total_tables(limit);
873                     }
874                     if let Some(limit) = self.opts.pooling_table_elements
875                         .or(self.wasm.max_table_elements)
876                     {
877                         cfg.table_elements(limit);
878                     }
879                     if let Some(limit) = self.opts.pooling_max_core_instance_size {
880                         cfg.max_core_instance_size(limit);
881                     }
882                     match_feature! {
883                         ["async" : self.opts.pooling_total_stacks]
884                         limit => cfg.total_stacks(limit),
885                         _ => err,
886                     }
887                     if let Some(max) = self.opts.pooling_max_memory_size
888                         .or(self.wasm.max_memory_size)
889                     {
890                         cfg.max_memory_size(max);
891                     }
892                     if let Some(size) = self.opts.pooling_decommit_batch_size {
893                         cfg.decommit_batch_size(size);
894                     }
895                     if let Some(max) = self.opts.pooling_max_unused_warm_slots {
896                         cfg.max_unused_warm_slots(max);
897                     }
898                     match_feature! {
899                         ["async" : self.opts.pooling_async_stack_keep_resident]
900                         size => cfg.async_stack_keep_resident(size),
901                         _ => err,
902                     }
903                     if let Some(max) = self.opts.pooling_max_component_instance_size {
904                         cfg.max_component_instance_size(max);
905                     }
906                     if let Some(max) = self.opts.pooling_max_core_instances_per_component {
907                         cfg.max_core_instances_per_component(max);
908                     }
909                     if let Some(max) = self.opts.pooling_max_memories_per_component {
910                         cfg.max_memories_per_component(max);
911                     }
912                     if let Some(max) = self.opts.pooling_max_tables_per_component {
913                         cfg.max_tables_per_component(max);
914                     }
915                     if let Some(max) = self.opts.pooling_max_tables_per_module {
916                         cfg.max_tables_per_module(max);
917                     }
918                     if let Some(max) = self.opts.pooling_max_memories_per_module {
919                         cfg.max_memories_per_module(max);
920                     }
921                     match_feature! {
922                         ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
923                         enable => cfg.memory_protection_keys(enable),
924                         _ => err,
925                     }
926                     match_feature! {
927                         ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
928                         max => cfg.max_memory_protection_keys(max),
929                         _ => err,
930                     }
931                     match_feature! {
932                         ["gc" : self.opts.pooling_total_gc_heaps]
933                         max => cfg.total_gc_heaps(max),
934                         _ => err,
935                     }
936                     config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
937                 }
938             },
939             true => err,
940         }
941 
942         if self.opts.pooling_memory_protection_keys.is_some()
943             && !self.opts.pooling_allocator.unwrap_or(false)
944         {
945             anyhow::bail!("memory protection keys require the pooling allocator");
946         }
947 
948         if self.opts.pooling_max_memory_protection_keys.is_some()
949             && !self.opts.pooling_memory_protection_keys.is_some()
950         {
951             anyhow::bail!(
952                 "max memory protection keys requires memory protection keys to be enabled"
953             );
954         }
955 
956         match_feature! {
957             ["async" : self.wasm.async_stack_zeroing]
958             enable => config.async_stack_zeroing(enable),
959             _ => err,
960         }
961 
962         if let Some(max) = self.wasm.max_wasm_stack {
963             config.max_wasm_stack(max);
964 
965             // If `-Wasync-stack-size` isn't passed then automatically adjust it
966             // to the wasm stack size provided here too. That prevents the need
967             // to pass both when one can generally be inferred from the other.
968             #[cfg(any(feature = "async", feature = "stack-switching"))]
969             if self.wasm.async_stack_size.is_none() {
970                 const DEFAULT_HOST_STACK: usize = 512 << 10;
971                 config.async_stack_size(max + DEFAULT_HOST_STACK);
972             }
973         }
974 
975         if let Some(enable) = self.wasm.relaxed_simd_deterministic {
976             config.relaxed_simd_deterministic(enable);
977         }
978         match_feature! {
979             ["cranelift" : self.wasm.wmemcheck]
980             enable => config.wmemcheck(enable),
981             true => err,
982         }
983 
984         Ok(config)
985     }
986 
987     pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
988         let all = self.wasm.all_proposals;
989 
990         if let Some(enable) = self.wasm.simd.or(all) {
991             config.wasm_simd(enable);
992         }
993         if let Some(enable) = self.wasm.relaxed_simd.or(all) {
994             config.wasm_relaxed_simd(enable);
995         }
996         if let Some(enable) = self.wasm.bulk_memory.or(all) {
997             config.wasm_bulk_memory(enable);
998         }
999         if let Some(enable) = self.wasm.multi_value.or(all) {
1000             config.wasm_multi_value(enable);
1001         }
1002         if let Some(enable) = self.wasm.tail_call.or(all) {
1003             config.wasm_tail_call(enable);
1004         }
1005         if let Some(enable) = self.wasm.multi_memory.or(all) {
1006             config.wasm_multi_memory(enable);
1007         }
1008         if let Some(enable) = self.wasm.memory64.or(all) {
1009             config.wasm_memory64(enable);
1010         }
1011         if let Some(enable) = self.wasm.stack_switching {
1012             config.wasm_stack_switching(enable);
1013         }
1014         if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1015             config.wasm_custom_page_sizes(enable);
1016         }
1017         if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1018             config.wasm_wide_arithmetic(enable);
1019         }
1020         if let Some(enable) = self.wasm.extended_const.or(all) {
1021             config.wasm_extended_const(enable);
1022         }
1023         if let Some(enable) = self.wasm.exceptions.or(all) {
1024             config.wasm_exceptions(enable);
1025         }
1026         if let Some(enable) = self.wasm.legacy_exceptions.or(all) {
1027             #[expect(deprecated, reason = "forwarding CLI flag")]
1028             config.wasm_legacy_exceptions(enable);
1029         }
1030 
1031         macro_rules! handle_conditionally_compiled {
1032             ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1033                 if let Some(enable) = self.wasm.$field.or(all) {
1034                     #[cfg(feature = $feature)]
1035                     config.$method(enable);
1036                     #[cfg(not(feature = $feature))]
1037                     if enable && all.is_none() {
1038                         anyhow::bail!("support for {} was disabled at compile-time", $feature);
1039                     }
1040                 }
1041             )*)
1042         }
1043 
1044         handle_conditionally_compiled! {
1045             ("component-model", component_model, wasm_component_model)
1046             ("component-model-async", component_model_async, wasm_component_model_async)
1047             ("component-model-async", component_model_async_builtins, wasm_component_model_async_builtins)
1048             ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1049             ("component-model", component_model_error_context, wasm_component_model_error_context)
1050             ("threads", threads, wasm_threads)
1051             ("gc", gc, wasm_gc)
1052             ("gc", reference_types, wasm_reference_types)
1053             ("gc", function_references, wasm_function_references)
1054             ("stack-switching", stack_switching, wasm_stack_switching)
1055         }
1056 
1057         if let Some(enable) = self.wasm.component_model_gc {
1058             #[cfg(all(feature = "component-model", feature = "gc"))]
1059             config.wasm_component_model_gc(enable);
1060             #[cfg(not(all(feature = "component-model", feature = "gc")))]
1061             if enable && all.is_none() {
1062                 anyhow::bail!("support for `component-model-gc` was disabled at compile time")
1063             }
1064         }
1065 
1066         Ok(())
1067     }
1068 
1069     pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
1070         let path_ref = path.as_ref();
1071         let file_contents = fs::read_to_string(path_ref)
1072             .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1073         toml::from_str::<CommonOptions>(&file_contents)
1074             .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1075     }
1076 }
1077 
1078 #[cfg(test)]
1079 mod tests {
1080     use wasmtime::{OptLevel, RegallocAlgorithm};
1081 
1082     use super::*;
1083 
1084     #[test]
1085     fn from_toml() {
1086         // empty toml
1087         let empty_toml = "";
1088         let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1089         common_options.config(None).unwrap();
1090 
1091         // basic toml
1092         let basic_toml = r#"
1093             [optimize]
1094             [codegen]
1095             [debug]
1096             [wasm]
1097             [wasi]
1098         "#;
1099         let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1100         common_options.config(None).unwrap();
1101 
1102         // toml with custom deserialization to match CLI flag parsing
1103         for (opt_value, expected) in [
1104             ("0", Some(OptLevel::None)),
1105             ("1", Some(OptLevel::Speed)),
1106             ("2", Some(OptLevel::Speed)),
1107             ("\"s\"", Some(OptLevel::SpeedAndSize)),
1108             ("\"hello\"", None), // should fail
1109             ("3", None),         // should fail
1110         ] {
1111             let toml = format!(
1112                 r#"
1113                     [optimize]
1114                     opt-level = {opt_value}
1115                 "#,
1116             );
1117             let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1118                 .ok()
1119                 .and_then(|common_options| common_options.opts.opt_level);
1120 
1121             assert_eq!(
1122                 parsed_opt_level, expected,
1123                 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1124             );
1125         }
1126 
1127         // Regalloc algorithm
1128         for (regalloc_value, expected) in [
1129             ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1130             ("\"hello\"", None), // should fail
1131             ("3", None),         // should fail
1132             ("true", None),      // should fail
1133         ] {
1134             let toml = format!(
1135                 r#"
1136                     [optimize]
1137                     regalloc-algorithm = {regalloc_value}
1138                 "#,
1139             );
1140             let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1141                 .ok()
1142                 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1143             assert_eq!(
1144                 parsed_regalloc_algorithm, expected,
1145                 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1146             );
1147         }
1148 
1149         // Strategy
1150         for (strategy_value, expected) in [
1151             ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1152             ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1153             ("\"hello\"", None), // should fail
1154             ("5", None),         // should fail
1155             ("true", None),      // should fail
1156         ] {
1157             let toml = format!(
1158                 r#"
1159                     [codegen]
1160                     compiler = {strategy_value}
1161                 "#,
1162             );
1163             let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1164                 .ok()
1165                 .and_then(|common_options| common_options.codegen.compiler);
1166             assert_eq!(
1167                 parsed_strategy, expected,
1168                 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1169             );
1170         }
1171 
1172         // Collector
1173         for (collector_value, expected) in [
1174             (
1175                 "\"drc\"",
1176                 Some(wasmtime::Collector::DeferredReferenceCounting),
1177             ),
1178             ("\"null\"", Some(wasmtime::Collector::Null)),
1179             ("\"hello\"", None), // should fail
1180             ("5", None),         // should fail
1181             ("true", None),      // should fail
1182         ] {
1183             let toml = format!(
1184                 r#"
1185                     [codegen]
1186                     collector = {collector_value}
1187                 "#,
1188             );
1189             let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1190                 .ok()
1191                 .and_then(|common_options| common_options.codegen.collector);
1192             assert_eq!(
1193                 parsed_collector, expected,
1194                 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1195             );
1196         }
1197     }
1198 }
1199 
1200 impl Default for CommonOptions {
1201     fn default() -> CommonOptions {
1202         CommonOptions::new()
1203     }
1204 }
1205 
1206 impl fmt::Display for CommonOptions {
1207     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1208         let CommonOptions {
1209             codegen_raw,
1210             codegen,
1211             debug_raw,
1212             debug,
1213             opts_raw,
1214             opts,
1215             wasm_raw,
1216             wasm,
1217             wasi_raw,
1218             wasi,
1219             configured,
1220             target,
1221             config,
1222         } = self;
1223         if let Some(target) = target {
1224             write!(f, "--target {target} ")?;
1225         }
1226         if let Some(config) = config {
1227             write!(f, "--config {} ", config.display())?;
1228         }
1229 
1230         let codegen_flags;
1231         let opts_flags;
1232         let wasi_flags;
1233         let wasm_flags;
1234         let debug_flags;
1235 
1236         if *configured {
1237             codegen_flags = codegen.to_options();
1238             debug_flags = debug.to_options();
1239             wasi_flags = wasi.to_options();
1240             wasm_flags = wasm.to_options();
1241             opts_flags = opts.to_options();
1242         } else {
1243             codegen_flags = codegen_raw
1244                 .iter()
1245                 .flat_map(|t| t.0.iter())
1246                 .cloned()
1247                 .collect();
1248             debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1249             wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1250             wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1251             opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1252         }
1253 
1254         for flag in codegen_flags {
1255             write!(f, "-C{flag} ")?;
1256         }
1257         for flag in opts_flags {
1258             write!(f, "-O{flag} ")?;
1259         }
1260         for flag in wasi_flags {
1261             write!(f, "-S{flag} ")?;
1262         }
1263         for flag in wasm_flags {
1264             write!(f, "-W{flag} ")?;
1265         }
1266         for flag in debug_flags {
1267             write!(f, "-D{flag} ")?;
1268         }
1269 
1270         Ok(())
1271     }
1272 }
1273