Skip to main content

wasmtime_cli_flags/
lib.rs

1//! A utility crate for managing Wasmtime configuration options in a
2//! serializable format.
3//!
4//! This crate primarily provides a [`CommonOptions`] structure which can be
5//! parsed from CLI flags via [`clap`] or with [`serde::Deserialize`]. This
6//! structure can additionally be created from a [`wasmtime::Engine`] to
7//! serialize some of the significant configuration options affecting an engine.
8//!
9//! This is intended to be a shared way for embedders to configure Wasmtime with
10//! serializable configuration. The source of truth for Wasmtime's configuration
11//! is the [`Config`] type but this additionally serves as a means of creating
12//! that type.
13
14use std::num::NonZeroUsize;
15use std::{fmt, num::NonZeroU32, path::PathBuf, time::Duration};
16use wasmtime::{Config, Engine, Result, WasmBacktraceDetails, WasmFeatures, bail};
17
18pub mod opt;
19
20#[cfg(feature = "logging")]
21fn init_file_per_thread_logger(prefix: &'static str) {
22    file_per_thread_logger::initialize(prefix);
23    file_per_thread_logger::allow_uninitialized();
24
25    // Extending behavior of default spawner:
26    // https://docs.rs/rayon/1.1.0/rayon/struct.ThreadPoolBuilder.html#method.spawn_handler
27    // Source code says DefaultSpawner is implementation detail and
28    // shouldn't be used directly.
29    #[cfg(feature = "parallel-compilation")]
30    rayon::ThreadPoolBuilder::new()
31        .spawn_handler(move |thread| {
32            let mut b = std::thread::Builder::new();
33            if let Some(name) = thread.name() {
34                b = b.name(name.to_owned());
35            }
36            if let Some(stack_size) = thread.stack_size() {
37                b = b.stack_size(stack_size);
38            }
39            b.spawn(move || {
40                file_per_thread_logger::initialize(prefix);
41                thread.run()
42            })?;
43            Ok(())
44        })
45        .build_global()
46        .unwrap();
47}
48
49wasmtime_option_group! {
50    pub struct OptimizeOptions {
51        /// Optimization level of generated code (0-2, s; default: 2)
52        #[serde(default)]
53        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
54        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
55        pub opt_level: Option<wasmtime::OptLevel>,
56
57        /// Register allocator algorithm choice.
58        #[serde(default)]
59        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
60        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
61        pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,
62
63        /// Do not allow Wasm linear memories to move in the host process's
64        /// address space.
65        pub memory_may_move: Option<bool>,
66
67        /// Initial virtual memory allocation size for memories.
68        pub memory_reservation: Option<u64>,
69
70        /// Bytes to reserve at the end of linear memory for growth into.
71        pub memory_reservation_for_growth: Option<u64>,
72
73        /// Size, in bytes, of guard pages for linear memories.
74        pub memory_guard_size: Option<u64>,
75
76        /// Do not allow the GC heap to move in the host process's address
77        /// space.
78        pub gc_heap_may_move: Option<bool>,
79
80        /// Initial virtual memory allocation size for the GC heap.
81        pub gc_heap_reservation: Option<u64>,
82
83        /// Bytes to reserve at the end of the GC heap for growth into.
84        pub gc_heap_reservation_for_growth: Option<u64>,
85
86        /// Size, in bytes, of guard pages for the GC heap.
87        pub gc_heap_guard_size: Option<u64>,
88
89        /// Initial allocated size for the GC heap.
90        pub gc_heap_initial_size: Option<u64>,
91
92        /// Indicates whether an unmapped region of memory is placed before all
93        /// linear memories.
94        pub guard_before_linear_memory: Option<bool>,
95
96        /// Whether to initialize tables lazily, so that instantiation is
97        /// fast but indirect calls are a little slower. If no, tables are
98        /// initialized eagerly from any active element segments that apply to
99        /// them during instantiation. (default: yes)
100        pub table_lazy_init: Option<bool>,
101
102        /// Enable the pooling allocator, in place of the on-demand allocator.
103        pub pooling_allocator: Option<bool>,
104
105        /// The number of decommits to do per batch. A batch size of 1
106        /// effectively disables decommit batching. (default: 1)
107        pub pooling_decommit_batch_size: Option<usize>,
108
109        /// How many bytes to keep resident between instantiations for the
110        /// pooling allocator in linear memories.
111        pub pooling_memory_keep_resident: Option<usize>,
112
113        /// How many bytes to keep resident between instantiations for the
114        /// pooling allocator in tables.
115        pub pooling_table_keep_resident: Option<usize>,
116
117        /// Enable memory protection keys for the pooling allocator; this can
118        /// optimize the size of memory slots.
119        #[serde(default)]
120        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
121        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
122        pub pooling_memory_protection_keys: Option<wasmtime::Enabled>,
123
124        /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime
125        /// will use. (default: 16)
126        pub pooling_max_memory_protection_keys: Option<usize>,
127
128        /// Configure attempting to initialize linear memory via a
129        /// copy-on-write mapping (default: yes)
130        pub memory_init_cow: Option<bool>,
131
132        /// Threshold below which CoW images are guaranteed to be used and be
133        /// dense.
134        pub memory_guaranteed_dense_image_size: Option<u64>,
135
136        /// The maximum number of WebAssembly instances which can be created
137        /// with the pooling allocator.
138        pub pooling_total_core_instances: Option<u32>,
139
140        /// The maximum number of WebAssembly components which can be created
141        /// with the pooling allocator.
142        pub pooling_total_component_instances: Option<u32>,
143
144        /// The maximum number of WebAssembly memories which can be created with
145        /// the pooling allocator.
146        pub pooling_total_memories: Option<u32>,
147
148        /// The maximum number of WebAssembly tables which can be created with
149        /// the pooling allocator.
150        pub pooling_total_tables: Option<u32>,
151
152        /// The maximum number of WebAssembly stacks which can be created with
153        /// the pooling allocator.
154        pub pooling_total_stacks: Option<u32>,
155
156        /// The maximum runtime size of each linear memory in the pooling
157        /// allocator, in bytes.
158        pub pooling_max_memory_size: Option<usize>,
159
160        /// The maximum table elements for any table defined in a module when
161        /// using the pooling allocator.
162        pub pooling_table_elements: Option<usize>,
163
164        /// The maximum size, in bytes, allocated for a core instance's metadata
165        /// when using the pooling allocator.
166        pub pooling_max_core_instance_size: Option<usize>,
167
168        /// Configures the maximum number of "unused warm slots" to retain in the
169        /// pooling allocator. (default: 100)
170        pub pooling_max_unused_warm_slots: Option<u32>,
171
172        /// How much memory, in bytes, to keep resident for async stacks allocated
173        /// with the pooling allocator. (default: 0)
174        pub pooling_async_stack_keep_resident: Option<usize>,
175
176        /// The maximum size, in bytes, allocated for a component instance's
177        /// `VMComponentContext` metadata. (default: 1MiB)
178        pub pooling_max_component_instance_size: Option<usize>,
179
180        /// The maximum number of core instances a single component may contain
181        /// (default is unlimited).
182        pub pooling_max_core_instances_per_component: Option<u32>,
183
184        /// The maximum number of Wasm linear memories that a single component may
185        /// transitively contain (default is unlimited).
186        pub pooling_max_memories_per_component: Option<u32>,
187
188        /// The maximum number of tables that a single component may transitively
189        /// contain (default is unlimited).
190        pub pooling_max_tables_per_component: Option<u32>,
191
192        /// The maximum number of defined tables for a core module. (default: 1)
193        pub pooling_max_tables_per_module: Option<u32>,
194
195        /// The maximum number of defined linear memories for a module. (default: 1)
196        pub pooling_max_memories_per_module: Option<u32>,
197
198        /// The maximum number of concurrent GC heaps supported. (default: 1000)
199        pub pooling_total_gc_heaps: Option<u32>,
200
201        /// Enable or disable the use of host signal handlers for traps.
202        pub signals_based_traps: Option<bool>,
203
204        /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
205        pub dynamic_memory_guard_size: Option<u64>,
206
207        /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
208        pub static_memory_guard_size: Option<u64>,
209
210        /// DEPRECATED: Use `-Cmemory-may-move` instead.
211        pub static_memory_forced: Option<bool>,
212
213        /// DEPRECATED: Use `-Cmemory-reservation=N` instead.
214        pub static_memory_maximum_size: Option<u64>,
215
216        /// DEPRECATED: Use `-Cmemory-reservation-for-growth=N` instead.
217        pub dynamic_memory_reserved_for_growth: Option<u64>,
218
219        /// Whether or not `PAGEMAP_SCAN` ioctls are used to reset linear
220        /// memory.
221        #[serde(default)]
222        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
223        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
224        pub pooling_pagemap_scan: Option<wasmtime::Enabled>,
225
226        /// XXX: For internal fuzzing and debugging use only!
227        #[doc(hidden)]
228        pub gc_zeal_alloc_counter: Option<NonZeroU32>,
229    }
230
231    enum Optimize {
232        ...
233    }
234}
235
236wasmtime_option_group! {
237    pub struct CodegenOptions {
238        /// Either `cranelift` or `winch`.
239        ///
240        /// Currently only `cranelift` and `winch` are supported, but not all
241        /// builds of Wasmtime have both built in.
242        #[serde(default)]
243        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
244        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
245        pub compiler: Option<wasmtime::Strategy>,
246        /// Which garbage collector to use: `drc`, `null`, or `copying`.
247        ///
248        /// `drc` is the deferred reference-counting collector.
249        ///
250        /// `null` is the null garbage collector, which does not collect any
251        /// garbage.
252        ///
253        /// `copying` is the copying garbage collector (not yet implemented).
254        ///
255        /// Note that not all builds of Wasmtime will have support for garbage
256        /// collection included.
257        #[serde(default)]
258        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
259        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
260        pub collector: Option<wasmtime::Collector>,
261        /// Enable Cranelift's internal debug verifier (expensive)
262        pub cranelift_debug_verifier: Option<bool>,
263        /// Whether or not to enable caching of compiled modules.
264        pub cache: Option<bool>,
265        /// Configuration for compiled module caching.
266        pub cache_config: Option<String>,
267        /// Whether or not to enable parallel compilation of modules.
268        pub parallel_compilation: Option<bool>,
269        /// Controls whether native unwind information is present in compiled
270        /// object files.
271        pub native_unwind_info: Option<bool>,
272
273        /// Whether to perform function inlining during compilation.
274        #[serde(default)]
275        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
276        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
277        pub inlining: Option<wasmtime::Inlining>,
278
279        /// Whether or not trap metadata is present for wasm internal assertions
280        /// in compiled code.
281        pub metadata_for_internal_asserts: Option<bool>,
282        /// Whether or not trap metadata is present for detection of gc
283        /// corruption in compiled code.
284        pub metadata_for_gc_heap_corruption: Option<bool>,
285
286        #[prefixed = "cranelift"]
287        #[serde(default)]
288        /// Set a cranelift-specific option. Use `wasmtime settings` to see
289        /// all.
290        pub cranelift: Vec<(String, Option<String>)>,
291    }
292
293    enum Codegen {
294        ...
295    }
296}
297
298wasmtime_option_group! {
299    pub struct DebugOptions {
300        /// Enable generation of DWARF debug information in compiled code.
301        pub debug_info: Option<bool>,
302        /// Enable guest debugging insrumentation.
303        pub guest_debug: Option<bool>,
304        /// Configure whether compiled code can map native addresses to wasm.
305        pub address_map: Option<bool>,
306        /// Configure whether logging is enabled.
307        pub logging: Option<bool>,
308        /// Configure whether logs are emitted to files
309        pub log_to_files: Option<bool>,
310        /// Enable coredump generation to this file after a WebAssembly trap.
311        pub coredump: Option<String>,
312        /// Load the given debugger component and attach it to the
313        /// main module or component.
314        pub debugger: Option<PathBuf>,
315        /// Pass the given command-line arguments to the debugger
316        /// component. May be specified multiple times.
317        #[serde(default)]
318        pub arg: Vec<String>,
319        /// Allow the debugger component to inherit stdin.Off by
320        /// default.
321        pub inherit_stdin: Option<bool>,
322        /// Allow the debugger component to inherit stdout. Off by
323        /// default.
324        pub inherit_stdout: Option<bool>,
325        /// Allow the debugger component to inherit stderr. Off by
326        /// default.
327        pub inherit_stderr: Option<bool>,
328        /// Maximum number of frames to capture in backtraces.
329        pub max_backtrace: Option<usize>,
330        /// Whether or not `*.cwasm` files have symbols in them.
331        pub symbols: Option<bool>,
332    }
333
334    enum Debug {
335        ...
336    }
337}
338
339wasmtime_option_group! {
340    pub struct WasmOptions {
341        /// Enable canonicalization of all NaN values.
342        pub nan_canonicalization: Option<bool>,
343        /// Enable execution fuel with N units fuel, trapping after running out
344        /// of fuel.
345        ///
346        /// Most WebAssembly instructions consume 1 unit of fuel. Some
347        /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0
348        /// units, as any execution cost associated with them involves other
349        /// instructions which do consume fuel.
350        pub fuel: Option<u64>,
351        /// Yield when a global epoch counter changes, allowing for async
352        /// operation without blocking the executor.
353        pub epoch_interruption: Option<bool>,
354        /// Maximum stack size, in bytes, that wasm is allowed to consume before a
355        /// stack overflow is reported.
356        pub max_wasm_stack: Option<usize>,
357        /// Stack size, in bytes, that will be allocated for async stacks.
358        ///
359        /// Note that this must be larger than `max-wasm-stack` and the
360        /// difference between the two is how much stack the host has to execute
361        /// on.
362        pub async_stack_size: Option<usize>,
363        /// Configures whether or not stacks used for async futures are zeroed
364        /// before (re)use as a defense-in-depth mechanism. (default: false)
365        pub async_stack_zeroing: Option<bool>,
366        /// Allow unknown exports when running commands.
367        pub unknown_exports_allow: Option<bool>,
368        /// Allow the main module to import unknown functions, using an
369        /// implementation that immediately traps, when running commands.
370        pub unknown_imports_trap: Option<bool>,
371        /// Allow the main module to import unknown functions, using an
372        /// implementation that returns default values, when running commands.
373        pub unknown_imports_default: Option<bool>,
374        /// Enables memory error checking. (see wmemcheck.md for more info)
375        pub wmemcheck: Option<bool>,
376        /// Maximum size, in bytes, that a linear memory is allowed to reach.
377        ///
378        /// Growth beyond this limit will cause `memory.grow` instructions in
379        /// WebAssembly modules to return -1 and fail.
380        pub max_memory_size: Option<usize>,
381        /// Maximum size, in table elements, that a table is allowed to reach.
382        pub max_table_elements: Option<usize>,
383        /// Maximum number of WebAssembly instances allowed to be created.
384        pub max_instances: Option<usize>,
385        /// Maximum number of WebAssembly tables allowed to be created.
386        pub max_tables: Option<usize>,
387        /// Maximum number of WebAssembly linear memories allowed to be created.
388        pub max_memories: Option<usize>,
389        /// Force a trap to be raised on `memory.grow` and `table.grow` failure
390        /// instead of returning -1 from these instructions.
391        ///
392        /// This is not necessarily a spec-compliant option to enable but can be
393        /// useful for tracking down a backtrace of what is requesting so much
394        /// memory, for example.
395        pub trap_on_grow_failure: Option<bool>,
396        /// Maximum execution time of wasm code before timing out (1, 2s, 100ms, etc)
397        pub timeout: Option<Duration>,
398        /// Configures support for all WebAssembly proposals implemented.
399        pub all_proposals: Option<bool>,
400        /// Configure support for the bulk memory proposal.
401        pub bulk_memory: Option<bool>,
402        /// Configure support for the multi-memory proposal.
403        pub multi_memory: Option<bool>,
404        /// Configure support for the multi-value proposal.
405        pub multi_value: Option<bool>,
406        /// Configure support for the reference-types proposal.
407        pub reference_types: Option<bool>,
408        /// Configure support for the simd proposal.
409        pub simd: Option<bool>,
410        /// Configure support for the relaxed-simd proposal.
411        pub relaxed_simd: Option<bool>,
412        /// Configure forcing deterministic and host-independent behavior of
413        /// the relaxed-simd instructions.
414        ///
415        /// By default these instructions may have architecture-specific behavior as
416        /// allowed by the specification, but this can be used to force the behavior
417        /// of these instructions to match the deterministic behavior classified in
418        /// the specification. Note that enabling this option may come at a
419        /// performance cost.
420        pub relaxed_simd_deterministic: Option<bool>,
421        /// Configure support for the tail-call proposal.
422        pub tail_call: Option<bool>,
423        /// Configure support for the threads proposal.
424        pub threads: Option<bool>,
425        /// Configure the ability to create a `shared` memory.
426        pub shared_memory: Option<bool>,
427        /// Configure support for the shared-everything-threads proposal.
428        pub shared_everything_threads: Option<bool>,
429        /// Configure support for the memory64 proposal.
430        pub memory64: Option<bool>,
431        /// Configure support for the component-model proposal.
432        pub component_model: Option<bool>,
433        /// Component model support for async lifting/lowering.
434        pub component_model_async: Option<bool>,
435        /// Component model support for async lifting/lowering: this corresponds
436        /// to the 🚝 emoji in the component model specification.
437        pub component_model_more_async_builtins: Option<bool>,
438        /// Component model support for async lifting/lowering: this corresponds
439        /// to the 🚟 emoji in the component model specification.
440        pub component_model_async_stackful: Option<bool>,
441        /// Component model support for threading: this corresponds
442        /// to the 🧵 emoji in the component model specification.
443        pub component_model_threading: Option<bool>,
444        /// Component model support for `error-context`: this corresponds
445        /// to the 📝 emoji in the component model specification.
446        pub component_model_error_context: Option<bool>,
447        /// GC support in the component model: this corresponds to the 🛸 emoji
448        /// in the component model specification.
449        pub component_model_gc: Option<bool>,
450        /// Map support in the component model.
451        pub component_model_map: Option<bool>,
452        /// Component model support for `memory64`: this corresponds
453        /// to the 🐘 emoji in the component model specification.
454        pub component_model_memory64: Option<bool>,
455        /// Configure support for the function-references proposal.
456        pub function_references: Option<bool>,
457        /// Configure support for the stack-switching proposal.
458        pub stack_switching: Option<bool>,
459        /// Configure support for the GC proposal.
460        pub gc: Option<bool>,
461        /// Configure support for the custom-page-sizes proposal.
462        pub custom_page_sizes: Option<bool>,
463        /// Configure support for the wide-arithmetic proposal.
464        pub wide_arithmetic: Option<bool>,
465        /// Configure support for the branch-hinting proposal.
466        pub branch_hinting: Option<bool>,
467        /// Configure support for the extended-const proposal.
468        pub extended_const: Option<bool>,
469        /// Configure support for the exceptions proposal.
470        pub exceptions: Option<bool>,
471        /// Whether or not any GC infrastructure in Wasmtime is enabled or not.
472        pub gc_support: Option<bool>,
473        /// Component model support for fixed-length lists: this corresponds
474        /// to the 🔧 emoji in the component model specification
475        pub component_model_fixed_length_lists: Option<bool>,
476        /// Component model support for `(implements ...)`, corresponds to the
477        /// 🏷️ emoji in the upstream spec.
478        pub component_model_implements: Option<bool>,
479        /// Whether or not any concurrency infrastructure in Wasmtime is
480        /// enabled or not.
481        pub concurrency_support: Option<bool>,
482    }
483
484    enum Wasm {
485        ...
486    }
487}
488
489wasmtime_option_group! {
490    pub struct WasiOptions {
491        /// Enable support for WASI CLI APIs, including filesystems, sockets, clocks, and random.
492        pub cli: Option<bool>,
493        /// Enable WASI APIs marked as: @unstable(feature = cli-exit-with-code)
494        pub cli_exit_with_code: Option<bool>,
495        /// Deprecated alias for `cli`
496        pub common: Option<bool>,
497        /// Enable support for WASI neural network imports (experimental)
498        pub nn: Option<bool>,
499        /// Enable support for WASI threading imports (experimental). Implies preview2=false.
500        pub threads: Option<bool>,
501        /// Enable support for WASI HTTP imports
502        pub http: Option<bool>,
503        /// Number of distinct write calls to the outgoing body's output-stream
504        /// that the implementation will buffer.
505        /// Default: 1.
506        pub http_outgoing_body_buffer_chunks: Option<usize>,
507        /// Maximum size allowed in a write call to the outgoing body's output-stream.
508        /// Default: 1024 * 1024.
509        pub http_outgoing_body_chunk_size: Option<usize>,
510        /// Enable support for WASI config imports (experimental)
511        pub config: Option<bool>,
512        /// Enable support for WASI key-value imports (experimental)
513        pub keyvalue: Option<bool>,
514        /// Inherit environment variables and file descriptors following the
515        /// systemd listen fd specification (UNIX only) (legacy wasip1
516        /// implementation only)
517        pub listenfd: Option<bool>,
518        /// Grant access to the given TCP listen socket (experimental, legacy
519        /// wasip1 implementation only)
520        #[serde(default)]
521        pub tcplisten: Vec<String>,
522        /// Enable support for WASI TLS (Transport Layer Security) imports (experimental)
523        pub tls: Option<bool>,
524        /// Implement WASI Preview1 using new Preview2 implementation (true, default) or legacy
525        /// implementation (false)
526        pub preview2: Option<bool>,
527        /// Pre-load machine learning graphs (i.e., models) for use by wasi-nn.
528        ///
529        /// Each use of the flag will preload a ML model from the host directory
530        /// using the given model encoding. The model will be mapped to the
531        /// directory name: e.g., `--wasi-nn-graph openvino:/foo/bar` will preload
532        /// an OpenVINO model named `bar`. Note that which model encodings are
533        /// available is dependent on the backends implemented in the
534        /// `wasmtime_wasi_nn` crate.
535        #[serde(skip)]
536        pub nn_graph: Vec<WasiNnGraph>,
537        /// Flag for WASI preview2 to inherit the host's network within the
538        /// guest so it has full access to all addresses/ports/etc.
539        pub inherit_network: Option<bool>,
540        /// Indicates whether `wasi:sockets/ip-name-lookup` is enabled or not.
541        pub allow_ip_name_lookup: Option<bool>,
542        /// Indicates whether `wasi:sockets` TCP support is enabled or not.
543        pub tcp: Option<bool>,
544        /// Indicates whether `wasi:sockets` UDP support is enabled or not.
545        pub udp: Option<bool>,
546        /// Enable WASI APIs marked as: @unstable(feature = network-error-code)
547        pub network_error_code: Option<bool>,
548        /// Allows imports from the `wasi_unstable` core wasm module.
549        pub preview0: Option<bool>,
550        /// Inherit all environment variables from the parent process.
551        ///
552        /// This option can be further overwritten with `--env` flags.
553        pub inherit_env: Option<bool>,
554        /// Inherit stdin from the parent process. On by default.
555        pub inherit_stdin: Option<bool>,
556        /// Inherit stdout from the parent process. On by default.
557        pub inherit_stdout: Option<bool>,
558        /// Inherit stderr from the parent process. On by default.
559        pub inherit_stderr: Option<bool>,
560        /// Initial current working directory reported through `wasi:cli/environment`.
561        pub cwd: Option<String>,
562        /// Pass a wasi config variable to the program.
563        #[serde(skip)]
564        pub config_var: Vec<KeyValuePair>,
565        /// Preset data for the In-Memory provider of WASI key-value API.
566        #[serde(skip)]
567        pub keyvalue_in_memory_data: Vec<KeyValuePair>,
568        /// Enable support for WASIp3 APIs.
569        pub p3: Option<bool>,
570        /// Maximum resources the guest is allowed to create simultaneously.
571        pub max_resources: Option<usize>,
572        /// Fuel to use for all hostcalls to limit guest<->host data transfer.
573        pub hostcall_fuel: Option<usize>,
574        /// Maximum number of simultaneously-live component-model handles (e.g.
575        /// resources, streams, futures) per store; allocating past it traps.
576        /// (default: 100000)
577        pub max_component_handles: Option<usize>,
578        /// Maximum value, in bytes, for a wasi-random 0.2
579        /// `get{,-insecure}-random-bytes` `len` parameter. Calls with a value
580        /// exceeding this limit will trap.
581        pub max_random_size: Option<u64>,
582        /// Maximum value, in bytes, for the contents of a wasi-http 0.2
583        /// `fields` resource (aka `headers` and `trailers`). `fields` methods
584        /// which cause the contents to exceed this size limit will trap.
585        pub max_http_fields_size: Option<usize>,
586    }
587
588    enum Wasi {
589        ...
590    }
591}
592
593wasmtime_option_group! {
594    pub struct RecordOptions {
595        /// Filename for the recorded execution trace (or empty string to skip writing a file).
596        pub path: Option<String>,
597        /// Include (optional) signatures to facilitate validation checks during replay
598        /// (see `wasmtime replay` for details).
599        pub validation_metadata: Option<bool>,
600        /// Window size of internal buffering for record events (large windows offer more opportunities
601        /// for coalescing events at the cost of memory usage).
602        pub event_window_size: Option<usize>,
603    }
604
605    enum Record {
606        ...
607    }
608}
609
610#[derive(Debug, Clone, PartialEq)]
611pub struct WasiNnGraph {
612    pub format: String,
613    pub dir: String,
614}
615
616#[derive(Debug, Clone, PartialEq)]
617pub struct KeyValuePair {
618    pub key: String,
619    pub value: String,
620}
621
622/// Common options for commands that translate WebAssembly modules
623#[derive(Clone)]
624#[cfg_attr(feature = "clap", derive(clap::Parser))]
625#[cfg_attr(
626    feature = "serde",
627    derive(serde_derive::Deserialize, serde_derive::Serialize)
628)]
629#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
630pub struct CommonOptions {
631    // These options groups are used to parse `-O` and such options but aren't
632    // the raw form consumed by the CLI. Instead they're pushed into the `pub`
633    // fields below as part of the `configure` method.
634    //
635    // Ideally clap would support `pub opts: OptimizeOptions` and parse directly
636    // into that but it does not appear to do so for multiple `-O` flags for
637    // now.
638    /// Optimization and tuning related options for wasm performance, `-O help` to
639    /// see all.
640    #[cfg_attr(
641        feature = "clap",
642        arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")
643    )]
644    #[cfg_attr(feature = "serde", serde(skip))]
645    opts_raw: Vec<opt::CommaSeparated<Optimize>>,
646
647    /// Codegen-related configuration options, `-C help` to see all.
648    #[cfg_attr(
649        feature = "clap",
650        arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")
651    )]
652    #[cfg_attr(feature = "serde", serde(skip))]
653    codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
654
655    /// Debug-related configuration options, `-D help` to see all.
656    #[cfg_attr(
657        feature = "clap",
658        arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")
659    )]
660    #[cfg_attr(feature = "serde", serde(skip))]
661    debug_raw: Vec<opt::CommaSeparated<Debug>>,
662
663    /// Options for configuring semantic execution of WebAssembly, `-W help` to see
664    /// all.
665    #[cfg_attr(
666        feature = "clap",
667        arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")
668    )]
669    #[cfg_attr(feature = "serde", serde(skip))]
670    wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
671
672    /// Options for configuring WASI and its proposals, `-S help` to see all.
673    #[cfg_attr(
674        feature = "clap",
675        arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")
676    )]
677    #[cfg_attr(feature = "serde", serde(skip))]
678    wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
679
680    /// Options to enable and configure execution recording, `-R help` to see all.
681    ///
682    /// Generates a serialized trace of the Wasm module execution that captures all
683    /// non-determinism observable by the module. This trace can subsequently be
684    /// re-executed in a deterministic, embedding-agnostic manner (see the `wasmtime replay` command).
685    ///
686    /// Note: Minimal configuration options for deterministic Wasm semantics will be
687    /// enforced during recording by default (NaN canonicalization, deterministic relaxed SIMD).
688    #[cfg_attr(
689        feature = "clap",
690        arg(short = 'R', long = "record", value_name = "KEY[=VAL[,..]]")
691    )]
692    #[cfg_attr(feature = "serde", serde(skip))]
693    record_raw: Vec<opt::CommaSeparated<Record>>,
694
695    // These fields are filled in by the `configure` method below via the
696    // options parsed from the CLI above. This is what the CLI should use.
697    #[cfg_attr(feature = "clap", arg(skip))]
698    #[cfg_attr(feature = "serde", serde(skip))]
699    configured: bool,
700
701    #[cfg_attr(feature = "clap", arg(skip))]
702    #[cfg_attr(feature = "serde", serde(rename = "optimize", default))]
703    pub opts: OptimizeOptions,
704
705    #[cfg_attr(feature = "clap", arg(skip))]
706    #[cfg_attr(feature = "serde", serde(default))]
707    pub codegen: CodegenOptions,
708
709    #[cfg_attr(feature = "clap", arg(skip))]
710    #[cfg_attr(feature = "serde", serde(default))]
711    pub debug: DebugOptions,
712
713    #[cfg_attr(feature = "clap", arg(skip))]
714    #[cfg_attr(feature = "serde", serde(default))]
715    pub wasm: WasmOptions,
716
717    #[cfg_attr(feature = "clap", arg(skip))]
718    #[cfg_attr(feature = "serde", serde(default))]
719    pub wasi: WasiOptions,
720
721    #[cfg_attr(feature = "clap", arg(skip))]
722    #[cfg_attr(feature = "serde", serde(default))]
723    pub record: RecordOptions,
724
725    /// The target triple; default is the host triple
726    #[cfg_attr(feature = "clap", arg(long, value_name = "TARGET"))]
727    #[cfg_attr(feature = "serde", serde(skip))]
728    pub target: Option<String>,
729
730    /// Use the specified TOML configuration file.
731    /// This TOML configuration file can provide same configuration options as the
732    /// `--optimize`, `--codegen`, `--debug`, `--wasm`, `--wasi` CLI options, with a couple exceptions.
733    ///
734    /// Additional options specified on the command line will take precedent over options loaded from
735    /// this TOML file.
736    #[cfg_attr(feature = "clap", arg(long = "config", value_name = "FILE"))]
737    #[cfg_attr(feature = "serde", serde(skip))]
738    pub config: Option<PathBuf>,
739}
740
741macro_rules! match_feature {
742    (
743        [$feat:tt : $config:expr]
744        $val:ident => $e:expr,
745        $p:pat => err,
746    ) => {
747        #[cfg(feature = $feat)]
748        {
749            if let Some($val) = $config {
750                $e;
751            }
752        }
753        #[cfg(not(feature = $feat))]
754        {
755            if let Some($p) = $config {
756                bail!(concat!("support for ", $feat, " disabled at compile time"));
757            }
758        }
759    };
760}
761
762impl CommonOptions {
763    /// Creates a blank new set of [`CommonOptions`] that can be configured.
764    pub fn new() -> CommonOptions {
765        CommonOptions {
766            opts_raw: Vec::new(),
767            codegen_raw: Vec::new(),
768            debug_raw: Vec::new(),
769            wasm_raw: Vec::new(),
770            wasi_raw: Vec::new(),
771            record_raw: Vec::new(),
772            configured: true,
773            opts: Default::default(),
774            codegen: Default::default(),
775            debug: Default::default(),
776            wasm: Default::default(),
777            wasi: Default::default(),
778            record: Default::default(),
779            target: None,
780            config: None,
781        }
782    }
783
784    fn configure(&mut self) -> Result<()> {
785        if self.configured {
786            return Ok(());
787        }
788        self.configured = true;
789        if let Some(toml_config_path) = &self.config {
790            #[cfg(feature = "toml")]
791            {
792                let toml_options = CommonOptions::from_file(toml_config_path)?;
793                self.opts = toml_options.opts;
794                self.codegen = toml_options.codegen;
795                self.debug = toml_options.debug;
796                self.wasm = toml_options.wasm;
797                self.wasi = toml_options.wasi;
798                self.record = toml_options.record;
799            }
800            #[cfg(not(feature = "toml"))]
801            {
802                bail!(
803                    "support for loading a configuration file from \
804                     {toml_config_path:?} disabled at compile time"
805                );
806            }
807        }
808        self.opts.configure_with(&self.opts_raw);
809        self.codegen.configure_with(&self.codegen_raw);
810        self.debug.configure_with(&self.debug_raw);
811        self.wasm.configure_with(&self.wasm_raw);
812        self.wasi.configure_with(&self.wasi_raw);
813        self.record.configure_with(&self.record_raw);
814        Ok(())
815    }
816
817    pub fn init_logging(&mut self) -> Result<()> {
818        self.configure()?;
819        if self.debug.logging == Some(false) {
820            return Ok(());
821        }
822        #[cfg(feature = "logging")]
823        if self.debug.log_to_files == Some(true) {
824            let prefix = "wasmtime.dbg.";
825            init_file_per_thread_logger(prefix);
826        } else {
827            use std::io::IsTerminal;
828            use tracing_subscriber::{EnvFilter, FmtSubscriber};
829            let builder = FmtSubscriber::builder()
830                .with_writer(std::io::stderr)
831                .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
832                .with_ansi(std::io::stderr().is_terminal());
833            if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
834                builder
835                    .with_level(false)
836                    .with_target(false)
837                    .without_time()
838                    .init()
839            } else {
840                builder.init();
841            }
842        }
843        #[cfg(not(feature = "logging"))]
844        if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
845            bail!("support for logging disabled at compile time");
846        }
847        Ok(())
848    }
849
850    pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
851        self.configure()?;
852        let mut config = Config::new();
853
854        match_feature! {
855            ["cranelift" : self.codegen.compiler]
856            strategy => config.strategy(strategy),
857            _ => err,
858        }
859        match_feature! {
860            ["gc" : self.codegen.collector]
861            collector => config.collector(collector),
862            _ => err,
863        }
864        if let Some(target) = &self.target {
865            config.target(target)?;
866        }
867        match_feature! {
868            ["cranelift" : self.codegen.cranelift_debug_verifier]
869            enable => config.cranelift_debug_verifier(enable),
870            true => err,
871        }
872        if let Some(enable) = self.debug.debug_info {
873            config.debug_info(enable);
874        }
875        match_feature! {
876            ["debug" : self.debug.guest_debug]
877            enable => config.guest_debug(enable),
878            _ => err,
879        }
880        if self.debug.coredump.is_some() {
881            #[cfg(feature = "coredump")]
882            config.coredump_on_trap(true);
883            #[cfg(not(feature = "coredump"))]
884            bail!("support for coredumps disabled at compile time");
885        }
886        match_feature! {
887            ["cranelift" : self.opts.opt_level]
888            level => config.cranelift_opt_level(level),
889            _ => err,
890        }
891        match_feature! {
892            ["cranelift": self.opts.regalloc_algorithm]
893            algo => config.cranelift_regalloc_algorithm(algo),
894            _ => err,
895        }
896        match_feature! {
897            ["cranelift" : self.wasm.nan_canonicalization]
898            enable => config.cranelift_nan_canonicalization(enable),
899            true => err,
900        }
901
902        self.enable_wasm_features(&mut config)?;
903
904        #[cfg(feature = "cranelift")]
905        for (name, value) in self.codegen.cranelift.iter() {
906            let name = name.replace('-', "_");
907            unsafe {
908                match value {
909                    Some(val) => {
910                        config.cranelift_flag_set(&name, val);
911                    }
912                    None => {
913                        config.cranelift_flag_enable(&name);
914                    }
915                }
916            }
917        }
918        #[cfg(not(feature = "cranelift"))]
919        if !self.codegen.cranelift.is_empty() {
920            bail!("support for cranelift disabled at compile time");
921        }
922
923        #[cfg(feature = "cache")]
924        if self.codegen.cache != Some(false) {
925            use wasmtime::Cache;
926            let cache = match &self.codegen.cache_config {
927                Some(path) => Cache::from_file(Some(std::path::Path::new(path)))?,
928                None => Cache::from_file(None)?,
929            };
930            config.cache(Some(cache));
931        }
932        #[cfg(not(feature = "cache"))]
933        if self.codegen.cache == Some(true) {
934            bail!("support for caching disabled at compile time");
935        }
936
937        match_feature! {
938            ["parallel-compilation" : self.codegen.parallel_compilation]
939            enable => config.parallel_compilation(enable),
940            true => err,
941        }
942
943        let memory_reservation = self
944            .opts
945            .memory_reservation
946            .or(self.opts.static_memory_maximum_size);
947        if let Some(size) = memory_reservation {
948            config.memory_reservation(size);
949        }
950
951        if let Some(enable) = self.opts.static_memory_forced {
952            config.memory_may_move(!enable);
953        }
954        if let Some(enable) = self.opts.memory_may_move {
955            config.memory_may_move(enable);
956        }
957
958        let memory_guard_size = self
959            .opts
960            .static_memory_guard_size
961            .or(self.opts.dynamic_memory_guard_size)
962            .or(self.opts.memory_guard_size);
963        if let Some(size) = memory_guard_size {
964            config.memory_guard_size(size);
965        }
966
967        let mem_for_growth = self
968            .opts
969            .memory_reservation_for_growth
970            .or(self.opts.dynamic_memory_reserved_for_growth);
971        if let Some(size) = mem_for_growth {
972            config.memory_reservation_for_growth(size);
973        }
974        if let Some(enable) = self.opts.guard_before_linear_memory {
975            config.guard_before_linear_memory(enable);
976        }
977
978        if let Some(size) = self.opts.gc_heap_reservation {
979            config.gc_heap_reservation(size);
980        }
981        if let Some(enable) = self.opts.gc_heap_may_move {
982            config.gc_heap_may_move(enable);
983        }
984        if let Some(size) = self.opts.gc_heap_guard_size {
985            config.gc_heap_guard_size(size);
986        }
987        if let Some(size) = self.opts.gc_heap_reservation_for_growth {
988            config.gc_heap_reservation_for_growth(size);
989        }
990
991        if let Some(size) = self.opts.gc_heap_initial_size {
992            config.gc_heap_initial_size(size);
993        }
994
995        if let Some(enable) = self.opts.table_lazy_init {
996            config.table_lazy_init(enable);
997        }
998
999        if let Some(n) = self.opts.gc_zeal_alloc_counter
1000            && (cfg!(gc_zeal) || cfg!(fuzzing))
1001        {
1002            config.gc_zeal_alloc_counter(Some(n))?;
1003        }
1004
1005        // If fuel has been configured, set the `consume fuel` flag on the config.
1006        if self.wasm.fuel.is_some() {
1007            config.consume_fuel(true);
1008        }
1009
1010        if let Some(enable) = self.wasm.epoch_interruption {
1011            config.epoch_interruption(enable);
1012        }
1013        if let Some(enable) = self.debug.address_map {
1014            config.generate_address_map(enable);
1015        }
1016        if let Some(frames) = self.debug.max_backtrace {
1017            match NonZeroUsize::new(frames) {
1018                None => {
1019                    config.wasm_backtrace_details(WasmBacktraceDetails::Disable);
1020                }
1021                Some(amt) => {
1022                    config.wasm_backtrace_max_frames(Some(amt));
1023                }
1024            }
1025        }
1026        if let Some(enable) = self.debug.symbols {
1027            config.debug_symbols(enable);
1028        }
1029        if let Some(enable) = self.opts.memory_init_cow {
1030            config.memory_init_cow(enable);
1031        }
1032        if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
1033            config.memory_guaranteed_dense_image_size(size);
1034        }
1035        if let Some(enable) = self.opts.signals_based_traps {
1036            config.signals_based_traps(enable);
1037        }
1038        if let Some(enable) = self.codegen.native_unwind_info {
1039            config.native_unwind_info(enable);
1040        }
1041        if let Some(enable) = self.codegen.inlining {
1042            config.compiler_inlining(enable);
1043        }
1044        if let Some(enable) = self.codegen.metadata_for_internal_asserts {
1045            config.metadata_for_internal_asserts(enable);
1046        }
1047        if let Some(enable) = self.codegen.metadata_for_gc_heap_corruption {
1048            config.metadata_for_gc_heap_corruption(enable);
1049        }
1050
1051        // async_stack_size enabled by either async or stack-switching, so
1052        // cannot directly use match_feature!
1053        #[cfg(any(feature = "async", feature = "stack-switching"))]
1054        {
1055            if let Some(size) = self.wasm.async_stack_size {
1056                config.async_stack_size(size);
1057            }
1058        }
1059        #[cfg(not(any(feature = "async", feature = "stack-switching")))]
1060        {
1061            if let Some(_size) = self.wasm.async_stack_size {
1062                bail!(concat!(
1063                    "support for async/stack-switching disabled at compile time"
1064                ));
1065            }
1066        }
1067
1068        match_feature! {
1069            ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
1070            enable => {
1071                if enable {
1072                    let mut cfg = wasmtime::PoolingAllocationConfig::default();
1073                    if let Some(size) = self.opts.pooling_memory_keep_resident {
1074                        cfg.linear_memory_keep_resident(size);
1075                    }
1076                    if let Some(size) = self.opts.pooling_table_keep_resident {
1077                        cfg.table_keep_resident(size);
1078                    }
1079                    if let Some(limit) = self.opts.pooling_total_core_instances {
1080                        cfg.total_core_instances(limit);
1081                    }
1082                    if let Some(limit) = self.opts.pooling_total_component_instances {
1083                        cfg.total_component_instances(limit);
1084                    }
1085                    if let Some(limit) = self.opts.pooling_total_memories {
1086                        cfg.total_memories(limit);
1087                    }
1088                    if let Some(limit) = self.opts.pooling_total_tables {
1089                        cfg.total_tables(limit);
1090                    }
1091                    if let Some(limit) = self.opts.pooling_table_elements
1092                        .or(self.wasm.max_table_elements)
1093                    {
1094                        cfg.table_elements(limit);
1095                    }
1096                    if let Some(limit) = self.opts.pooling_max_core_instance_size {
1097                        cfg.max_core_instance_size(limit);
1098                    }
1099                    match_feature! {
1100                        ["async" : self.opts.pooling_total_stacks]
1101                        limit => cfg.total_stacks(limit),
1102                        _ => err,
1103                    }
1104                    if let Some(max) = self.opts.pooling_max_memory_size
1105                        .or(self.wasm.max_memory_size)
1106                    {
1107                        cfg.max_memory_size(max);
1108                    }
1109                    if let Some(size) = self.opts.pooling_decommit_batch_size {
1110                        cfg.decommit_batch_size(size);
1111                    }
1112                    if let Some(max) = self.opts.pooling_max_unused_warm_slots {
1113                        cfg.max_unused_warm_slots(max);
1114                    }
1115                    match_feature! {
1116                        ["async" : self.opts.pooling_async_stack_keep_resident]
1117                        size => cfg.async_stack_keep_resident(size),
1118                        _ => err,
1119                    }
1120                    if let Some(max) = self.opts.pooling_max_component_instance_size {
1121                        cfg.max_component_instance_size(max);
1122                    }
1123                    if let Some(max) = self.opts.pooling_max_core_instances_per_component {
1124                        cfg.max_core_instances_per_component(max);
1125                    }
1126                    if let Some(max) = self.opts.pooling_max_memories_per_component {
1127                        cfg.max_memories_per_component(max);
1128                    }
1129                    if let Some(max) = self.opts.pooling_max_tables_per_component {
1130                        cfg.max_tables_per_component(max);
1131                    }
1132                    if let Some(max) = self.opts.pooling_max_tables_per_module {
1133                        cfg.max_tables_per_module(max);
1134                    }
1135                    if let Some(max) = self.opts.pooling_max_memories_per_module {
1136                        cfg.max_memories_per_module(max);
1137                    }
1138                    match_feature! {
1139                        ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
1140                        enable => cfg.memory_protection_keys(enable),
1141                        _ => err,
1142                    }
1143                    match_feature! {
1144                        ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
1145                        max => cfg.max_memory_protection_keys(max),
1146                        _ => err,
1147                    }
1148                    match_feature! {
1149                        ["gc" : self.opts.pooling_total_gc_heaps]
1150                        max => cfg.total_gc_heaps(max),
1151                        _ => err,
1152                    }
1153                    if let Some(enabled) = self.opts.pooling_pagemap_scan {
1154                        cfg.pagemap_scan(enabled);
1155                    }
1156                    config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
1157                }
1158            },
1159            true => err,
1160        }
1161
1162        if self.opts.pooling_memory_protection_keys.is_some()
1163            && !self.opts.pooling_allocator.unwrap_or(false)
1164        {
1165            bail!("memory protection keys require the pooling allocator");
1166        }
1167
1168        if self.opts.pooling_max_memory_protection_keys.is_some()
1169            && !self.opts.pooling_memory_protection_keys.is_some()
1170        {
1171            bail!("max memory protection keys requires memory protection keys to be enabled");
1172        }
1173
1174        match_feature! {
1175            ["async" : self.wasm.async_stack_zeroing]
1176            enable => config.async_stack_zeroing(enable),
1177            _ => err,
1178        }
1179
1180        if let Some(max) = self.wasm.max_wasm_stack {
1181            config.max_wasm_stack(max);
1182
1183            // If `-Wasync-stack-size` isn't passed then automatically adjust it
1184            // to the wasm stack size provided here too. That prevents the need
1185            // to pass both when one can generally be inferred from the other.
1186            #[cfg(any(feature = "async", feature = "stack-switching"))]
1187            if self.wasm.async_stack_size.is_none() {
1188                const DEFAULT_HOST_STACK: usize = 512 << 10;
1189                config.async_stack_size(max + DEFAULT_HOST_STACK);
1190            }
1191        }
1192
1193        if let Some(enable) = self.wasm.relaxed_simd_deterministic {
1194            config.relaxed_simd_deterministic(enable);
1195        }
1196        match_feature! {
1197            ["cranelift" : self.wasm.wmemcheck]
1198            enable => config.wmemcheck(enable),
1199            true => err,
1200        }
1201
1202        if let Some(enable) = self.wasm.gc_support {
1203            config.gc_support(enable);
1204        }
1205
1206        if let Some(enable) = self.wasm.concurrency_support {
1207            config.concurrency_support(enable);
1208        }
1209
1210        if let Some(enable) = self.wasm.shared_memory {
1211            config.shared_memory(enable);
1212        }
1213
1214        let record = &self.record;
1215        match_feature! {
1216            ["rr" : &record.path]
1217            _path => {
1218                bail!("recording configuration for `rr` feature is not supported yet");
1219            },
1220            _ => err,
1221        }
1222
1223        Ok(config)
1224    }
1225
1226    pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
1227        let all = self.wasm.all_proposals;
1228
1229        if let Some(enable) = self.wasm.simd.or(all) {
1230            config.wasm_simd(enable);
1231        }
1232        if let Some(enable) = self.wasm.relaxed_simd.or(all) {
1233            config.wasm_relaxed_simd(enable);
1234        }
1235        if let Some(enable) = self.wasm.bulk_memory.or(all) {
1236            config.wasm_bulk_memory(enable);
1237        }
1238        if let Some(enable) = self.wasm.multi_value.or(all) {
1239            config.wasm_multi_value(enable);
1240        }
1241        if let Some(enable) = self.wasm.tail_call.or(all) {
1242            config.wasm_tail_call(enable);
1243        }
1244        if let Some(enable) = self.wasm.multi_memory.or(all) {
1245            config.wasm_multi_memory(enable);
1246        }
1247        if let Some(enable) = self.wasm.memory64.or(all) {
1248            config.wasm_memory64(enable);
1249        }
1250        if let Some(enable) = self.wasm.stack_switching {
1251            config.wasm_stack_switching(enable);
1252        }
1253        if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1254            config.wasm_custom_page_sizes(enable);
1255        }
1256        if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1257            config.wasm_wide_arithmetic(enable);
1258        }
1259        // Not included in `all_proposals`: off by default until fuzzed.
1260        if let Some(enable) = self.wasm.branch_hinting {
1261            config.wasm_branch_hinting(enable);
1262        }
1263        if let Some(enable) = self.wasm.extended_const.or(all) {
1264            config.wasm_extended_const(enable);
1265        }
1266
1267        macro_rules! handle_conditionally_compiled {
1268            ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1269                if let Some(enable) = self.wasm.$field.or(all) {
1270                    #[cfg(feature = $feature)]
1271                    config.$method(enable);
1272                    #[cfg(not(feature = $feature))]
1273                    if enable && all.is_none() {
1274                        bail!("support for {} was disabled at compile-time", $feature);
1275                    }
1276                }
1277            )*)
1278        }
1279
1280        handle_conditionally_compiled! {
1281            ("component-model", component_model, wasm_component_model)
1282            ("component-model-async", component_model_async, wasm_component_model_async)
1283            ("component-model-async", component_model_more_async_builtins, wasm_component_model_more_async_builtins)
1284            ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1285            ("component-model-async", component_model_threading, wasm_component_model_threading)
1286            ("component-model", component_model_error_context, wasm_component_model_error_context)
1287            ("component-model", component_model_map, wasm_component_model_map)
1288            ("component-model", component_model_fixed_length_lists, wasm_component_model_fixed_length_lists)
1289            ("component-model", component_model_implements, wasm_component_model_implements)
1290            ("component-model", component_model_memory64, wasm_component_model_memory64)
1291            ("threads", threads, wasm_threads)
1292            ("gc", gc, wasm_gc)
1293            ("gc", reference_types, wasm_reference_types)
1294            ("gc", function_references, wasm_function_references)
1295            ("gc", exceptions, wasm_exceptions)
1296            ("stack-switching", stack_switching, wasm_stack_switching)
1297        }
1298
1299        if let Some(enable) = self.wasm.component_model_gc {
1300            #[cfg(all(feature = "component-model", feature = "gc"))]
1301            config.wasm_component_model_gc(enable);
1302            #[cfg(not(all(feature = "component-model", feature = "gc")))]
1303            if enable && all.is_none() {
1304                bail!("support for `component-model-gc` was disabled at compile time")
1305            }
1306        }
1307
1308        Ok(())
1309    }
1310
1311    #[cfg(feature = "toml")]
1312    pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
1313        use wasmtime::error::Context;
1314
1315        let path_ref = path.as_ref();
1316        let file_contents = std::fs::read_to_string(path_ref)
1317            .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1318        toml::from_str::<CommonOptions>(&file_contents)
1319            .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1320    }
1321
1322    /// Creates an instance of [`CommonOptions`] by reflecting on the
1323    /// configuration present in the provided [`Engine`].
1324    ///
1325    /// This will extract all configuration values that can be set by this
1326    /// [`CommonOptions`] into a [`Config`] into the returned structure to the
1327    /// best of its ability. Not all configuration options present on [`Engine`]
1328    /// can be reflected back into [`CommonOptions`], and not all options on
1329    /// [`CommonOptions`] can be set on an [`Engine`]. This means that this
1330    /// is a lossy operation that doesn't fully capture 100% of the
1331    /// configuration of [`Engine`]. That being said, however, it can capture
1332    /// almost all of the configuration related to codegen and major other
1333    /// configuration options.
1334    pub fn from_engine(engine: &Engine) -> Self {
1335        let features = engine.get_wasm_features();
1336        let pooling = engine.get_pooling_config();
1337        CommonOptions {
1338            target: engine.get_target(),
1339            opts: OptimizeOptions {
1340                memory_may_move: Some(engine.get_memory_may_move()),
1341                memory_reservation: Some(engine.get_memory_reservation()),
1342                memory_reservation_for_growth: Some(engine.get_memory_reservation_for_growth()),
1343                memory_guard_size: Some(engine.get_memory_guard_size()),
1344                gc_heap_may_move: Some(engine.get_gc_heap_may_move()),
1345                gc_heap_reservation: Some(engine.get_gc_heap_reservation()),
1346                gc_heap_reservation_for_growth: Some(engine.get_gc_heap_reservation_for_growth()),
1347                gc_heap_guard_size: Some(engine.get_gc_heap_guard_size()),
1348                gc_heap_initial_size: Some(engine.get_gc_heap_initial_size()),
1349                guard_before_linear_memory: Some(engine.get_guard_before_linear_memory()),
1350                table_lazy_init: Some(engine.get_table_lazy_init()),
1351                memory_init_cow: Some(engine.get_memory_init_cow()),
1352                memory_guaranteed_dense_image_size: Some(
1353                    engine.get_memory_guaranteed_dense_image_size(),
1354                ),
1355                signals_based_traps: Some(engine.get_signals_based_traps()),
1356                gc_zeal_alloc_counter: engine.get_gc_zeal_alloc_counter(),
1357                opt_level: engine.get_cranelift_opt_level(),
1358                regalloc_algorithm: engine.get_cranelift_regalloc_algorithm(),
1359                pooling_allocator: Some(pooling.is_some()),
1360                pooling_decommit_batch_size: pooling.map(|c| c.get_decommit_batch_size()),
1361                pooling_memory_keep_resident: pooling.map(|c| c.get_memory_keep_resident()),
1362                pooling_table_keep_resident: pooling.map(|c| c.get_table_keep_resident()),
1363                pooling_max_unused_warm_slots: pooling.map(|c| c.get_max_unused_warm_slots()),
1364                pooling_pagemap_scan: pooling.map(|c| c.get_pagemap_scan()),
1365                pooling_total_core_instances: pooling.map(|c| c.get_total_core_instances()),
1366                pooling_total_component_instances: pooling
1367                    .map(|c| c.get_total_component_instances()),
1368                pooling_total_memories: pooling.map(|c| c.get_total_memories()),
1369                pooling_total_tables: pooling.map(|c| c.get_total_tables()),
1370                pooling_max_memory_size: pooling.map(|c| c.get_max_memory_size()),
1371                pooling_table_elements: pooling.map(|c| c.get_table_elements()),
1372                pooling_max_core_instance_size: pooling.map(|c| c.get_max_core_instance_size()),
1373                pooling_max_component_instance_size: pooling
1374                    .map(|c| c.get_max_component_instance_size()),
1375                pooling_max_core_instances_per_component: pooling
1376                    .map(|c| c.get_max_core_instances_per_component()),
1377                pooling_max_memories_per_component: pooling
1378                    .map(|c| c.get_max_memories_per_component()),
1379                pooling_max_tables_per_component: pooling.map(|c| c.get_max_tables_per_component()),
1380                pooling_max_tables_per_module: pooling.map(|c| c.get_max_tables_per_module()),
1381                pooling_max_memories_per_module: pooling.map(|c| c.get_max_memories_per_module()),
1382                pooling_async_stack_keep_resident: pooling
1383                    .map(|c| c.get_async_stack_keep_resident()),
1384                pooling_total_stacks: pooling.map(|c| c.get_total_stacks()),
1385                pooling_total_gc_heaps: pooling.map(|c| c.get_total_gc_heaps()),
1386                pooling_memory_protection_keys: pooling.map(|c| c.get_memory_protection_keys()),
1387                pooling_max_memory_protection_keys: pooling
1388                    .map(|c| c.get_max_memory_protection_keys()),
1389                // Deprecated aliases for the above options; intentionally left
1390                // unset in favor of their replacements.
1391                dynamic_memory_guard_size: None,
1392                static_memory_guard_size: None,
1393                static_memory_forced: None,
1394                static_memory_maximum_size: None,
1395                dynamic_memory_reserved_for_growth: None,
1396            },
1397            codegen: CodegenOptions {
1398                compiler: engine.get_strategy(),
1399                collector: engine.get_collector(),
1400                cranelift_debug_verifier: engine.get_cranelift_debug_verifier(),
1401                inlining: Some(engine.get_compiler_inlining()),
1402                native_unwind_info: engine.get_native_unwind_info(),
1403                parallel_compilation: Some(engine.get_parallel_compilation()),
1404                metadata_for_internal_asserts: Some(engine.get_metadata_for_internal_asserts()),
1405                metadata_for_gc_heap_corruption: Some(engine.get_metadata_for_gc_heap_corruption()),
1406                cranelift: engine
1407                    .get_cranelift_flags_set()
1408                    .map(|(k, v)| (k.to_string(), Some(v.to_string())))
1409                    .chain(
1410                        engine
1411                            .get_cranelift_flags_enabled()
1412                            .map(|k| (k.to_string(), None)),
1413                    )
1414                    .collect(),
1415
1416                // not easily extractable from `Engine` since that supports
1417                // arbitrary code-defined caches.
1418                cache: None,
1419                cache_config: None,
1420            },
1421            debug: DebugOptions {
1422                address_map: Some(engine.get_generate_address_map()),
1423                debug_info: Some(engine.get_debug_info()),
1424                guest_debug: Some(engine.get_guest_debug()),
1425                symbols: Some(engine.get_debug_symbols()),
1426                max_backtrace: Some(engine.get_wasm_backtrace_max_frames()),
1427
1428                // Can't infer a path to emit a core dump to from engine
1429                // configuration.
1430                coredump: None,
1431                // debugger configuration not part of engine config
1432                debugger: None,
1433                arg: Vec::new(),
1434                inherit_stderr: None,
1435                inherit_stdout: None,
1436                inherit_stdin: None,
1437                // logging not part of engine config
1438                log_to_files: None,
1439                logging: None,
1440            },
1441            wasm: WasmOptions {
1442                async_stack_size: Some(engine.get_async_stack_size()),
1443                async_stack_zeroing: Some(engine.get_async_stack_zeroing()),
1444                branch_hinting: Some(engine.get_wasm_branch_hinting()),
1445                bulk_memory: Some(features.contains(WasmFeatures::BULK_MEMORY)),
1446                component_model: Some(features.contains(WasmFeatures::COMPONENT_MODEL)),
1447                component_model_async: Some(features.contains(WasmFeatures::CM_ASYNC)),
1448                component_model_async_stackful: Some(
1449                    features.contains(WasmFeatures::CM_ASYNC_STACKFUL),
1450                ),
1451                component_model_error_context: Some(
1452                    features.contains(WasmFeatures::CM_ERROR_CONTEXT),
1453                ),
1454                component_model_gc: Some(features.contains(WasmFeatures::CM_GC)),
1455                component_model_fixed_length_lists: Some(
1456                    features.contains(WasmFeatures::CM_FIXED_LENGTH_LISTS),
1457                ),
1458                component_model_implements: Some(features.contains(WasmFeatures::CM_IMPLEMENTS)),
1459                component_model_map: Some(features.contains(WasmFeatures::CM_MAP)),
1460                component_model_memory64: Some(features.contains(WasmFeatures::CM64)),
1461                component_model_more_async_builtins: Some(
1462                    features.contains(WasmFeatures::CM_MORE_ASYNC_BUILTINS),
1463                ),
1464                component_model_threading: Some(features.contains(WasmFeatures::CM_THREADING)),
1465                custom_page_sizes: Some(features.contains(WasmFeatures::CUSTOM_PAGE_SIZES)),
1466                exceptions: Some(features.contains(WasmFeatures::EXCEPTIONS)),
1467                extended_const: Some(features.contains(WasmFeatures::EXTENDED_CONST)),
1468                function_references: Some(features.contains(WasmFeatures::FUNCTION_REFERENCES)),
1469                gc: Some(features.contains(WasmFeatures::GC)),
1470                gc_support: Some(features.contains(WasmFeatures::GC_TYPES)),
1471                memory64: Some(features.contains(WasmFeatures::MEMORY64)),
1472                multi_memory: Some(features.contains(WasmFeatures::MULTI_MEMORY)),
1473                multi_value: Some(features.contains(WasmFeatures::MULTI_VALUE)),
1474                reference_types: Some(features.contains(WasmFeatures::REFERENCE_TYPES)),
1475                relaxed_simd: Some(features.contains(WasmFeatures::RELAXED_SIMD)),
1476                shared_everything_threads: Some(
1477                    features.contains(WasmFeatures::SHARED_EVERYTHING_THREADS),
1478                ),
1479                simd: Some(features.contains(WasmFeatures::SIMD)),
1480                stack_switching: Some(features.contains(WasmFeatures::STACK_SWITCHING)),
1481                tail_call: Some(features.contains(WasmFeatures::TAIL_CALL)),
1482                threads: Some(features.contains(WasmFeatures::THREADS)),
1483                wide_arithmetic: Some(features.contains(WasmFeatures::WIDE_ARITHMETIC)),
1484                concurrency_support: Some(engine.get_concurrency_support()),
1485                epoch_interruption: Some(engine.get_epoch_interruption()),
1486                fuel: if engine.get_consume_fuel() {
1487                    Some(1)
1488                } else {
1489                    None
1490                },
1491                max_wasm_stack: Some(engine.get_max_wasm_stack()),
1492                nan_canonicalization: engine.get_cranelift_nan_canonicalization(),
1493                relaxed_simd_deterministic: Some(engine.get_relaxed_simd_deterministic()),
1494                shared_memory: Some(engine.get_shared_memory()),
1495
1496                // This is covered by individual `WasmFeatures::*` flags above.
1497                all_proposals: None,
1498                // These aren't set in `Config` any more, they're just
1499                // historical
1500                max_instances: None,
1501                max_memories: None,
1502                max_memory_size: None,
1503                max_table_elements: None,
1504                max_tables: None,
1505                // not part of engine config, specific to `run` command
1506                timeout: None,
1507                trap_on_grow_failure: None,
1508                unknown_exports_allow: None,
1509                unknown_imports_default: None,
1510                unknown_imports_trap: None,
1511                wmemcheck: None,
1512            },
1513
1514            // Not currently reflected in `Engine`.
1515            record: RecordOptions::default(),
1516
1517            // WASI options aren't reflected in an `Engine`.
1518            wasi: Default::default(),
1519
1520            // CLI flags are represented above, they have default values here.
1521            configured: true,
1522            codegen_raw: Default::default(),
1523            debug_raw: Default::default(),
1524            opts_raw: Default::default(),
1525            record_raw: Default::default(),
1526            wasi_raw: Default::default(),
1527            wasm_raw: Default::default(),
1528
1529            // No external configuration file, it's all above.
1530            config: None,
1531            //
1532            // Note that an exhaustive listing is explicitly used to avoid
1533            // forgetting to configure a field. Please don't add `..something`
1534            // here at the end.
1535        }
1536    }
1537}
1538
1539#[cfg(test)]
1540mod tests {
1541    use wasmtime::{OptLevel, RegallocAlgorithm};
1542
1543    use super::*;
1544
1545    #[test]
1546    fn from_toml() {
1547        // empty toml
1548        let empty_toml = "";
1549        let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1550        common_options.config(None).unwrap();
1551
1552        // basic toml
1553        let basic_toml = r#"
1554            [optimize]
1555            [codegen]
1556            [debug]
1557            [wasm]
1558            [wasi]
1559            [record]
1560        "#;
1561        let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1562        common_options.config(None).unwrap();
1563
1564        // toml with custom deserialization to match CLI flag parsing
1565        for (opt_value, expected) in [
1566            ("0", Some(OptLevel::None)),
1567            ("1", Some(OptLevel::Speed)),
1568            ("2", Some(OptLevel::Speed)),
1569            ("\"s\"", Some(OptLevel::SpeedAndSize)),
1570            ("\"hello\"", None), // should fail
1571            ("3", None),         // should fail
1572        ] {
1573            let toml = format!(
1574                r#"
1575                    [optimize]
1576                    opt-level = {opt_value}
1577                "#,
1578            );
1579            let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1580                .ok()
1581                .and_then(|common_options| common_options.opts.opt_level);
1582
1583            assert_eq!(
1584                parsed_opt_level, expected,
1585                "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1586            );
1587        }
1588
1589        // Regalloc algorithm
1590        for (regalloc_value, expected) in [
1591            ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1592            ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
1593            ("\"hello\"", None), // should fail
1594            ("3", None),         // should fail
1595            ("true", None),      // should fail
1596        ] {
1597            let toml = format!(
1598                r#"
1599                    [optimize]
1600                    regalloc-algorithm = {regalloc_value}
1601                "#,
1602            );
1603            let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1604                .ok()
1605                .and_then(|common_options| common_options.opts.regalloc_algorithm);
1606            assert_eq!(
1607                parsed_regalloc_algorithm, expected,
1608                "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1609            );
1610        }
1611
1612        // Strategy
1613        for (strategy_value, expected) in [
1614            ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1615            ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1616            ("\"hello\"", None), // should fail
1617            ("5", None),         // should fail
1618            ("true", None),      // should fail
1619        ] {
1620            let toml = format!(
1621                r#"
1622                    [codegen]
1623                    compiler = {strategy_value}
1624                "#,
1625            );
1626            let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1627                .ok()
1628                .and_then(|common_options| common_options.codegen.compiler);
1629            assert_eq!(
1630                parsed_strategy, expected,
1631                "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1632            );
1633        }
1634
1635        // Collector
1636        for (collector_value, expected) in [
1637            (
1638                "\"drc\"",
1639                Some(wasmtime::Collector::DeferredReferenceCounting),
1640            ),
1641            ("\"null\"", Some(wasmtime::Collector::Null)),
1642            ("\"copying\"", Some(wasmtime::Collector::Copying)),
1643            ("\"hello\"", None), // should fail
1644            ("5", None),         // should fail
1645            ("true", None),      // should fail
1646        ] {
1647            let toml = format!(
1648                r#"
1649                    [codegen]
1650                    collector = {collector_value}
1651                "#,
1652            );
1653            let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1654                .ok()
1655                .and_then(|common_options| common_options.codegen.collector);
1656            assert_eq!(
1657                parsed_collector, expected,
1658                "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1659            );
1660        }
1661    }
1662}
1663
1664impl Default for CommonOptions {
1665    fn default() -> CommonOptions {
1666        CommonOptions::new()
1667    }
1668}
1669
1670impl fmt::Display for CommonOptions {
1671    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1672        let CommonOptions {
1673            codegen_raw,
1674            codegen,
1675            debug_raw,
1676            debug,
1677            opts_raw,
1678            opts,
1679            wasm_raw,
1680            wasm,
1681            wasi_raw,
1682            wasi,
1683            record_raw,
1684            record,
1685            configured,
1686            target,
1687            config,
1688        } = self;
1689        if let Some(target) = target {
1690            write!(f, "--target {target} ")?;
1691        }
1692        if let Some(config) = config {
1693            write!(f, "--config {} ", config.display())?;
1694        }
1695
1696        let codegen_flags;
1697        let opts_flags;
1698        let wasi_flags;
1699        let wasm_flags;
1700        let debug_flags;
1701        let record_flags;
1702
1703        if *configured {
1704            codegen_flags = codegen.to_options();
1705            debug_flags = debug.to_options();
1706            wasi_flags = wasi.to_options();
1707            wasm_flags = wasm.to_options();
1708            opts_flags = opts.to_options();
1709            record_flags = record.to_options();
1710        } else {
1711            codegen_flags = codegen_raw
1712                .iter()
1713                .flat_map(|t| t.0.iter())
1714                .cloned()
1715                .collect();
1716            debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1717            wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1718            wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1719            opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1720            record_flags = record_raw
1721                .iter()
1722                .flat_map(|t| t.0.iter())
1723                .cloned()
1724                .collect();
1725        }
1726
1727        for flag in codegen_flags {
1728            write!(f, "-C{flag} ")?;
1729        }
1730        for flag in opts_flags {
1731            write!(f, "-O{flag} ")?;
1732        }
1733        for flag in wasi_flags {
1734            write!(f, "-S{flag} ")?;
1735        }
1736        for flag in wasm_flags {
1737            write!(f, "-W{flag} ")?;
1738        }
1739        for flag in debug_flags {
1740            write!(f, "-D{flag} ")?;
1741        }
1742        for flag in record_flags {
1743            write!(f, "-R{flag} ")?;
1744        }
1745
1746        Ok(())
1747    }
1748}