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