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