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