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