1 //! Contains the common Wasmtime command line interface (CLI) flags. 2 3 use anyhow::Result; 4 use clap::Parser; 5 use std::time::Duration; 6 use wasmtime::Config; 7 8 pub mod opt; 9 10 #[cfg(feature = "logging")] 11 fn init_file_per_thread_logger(prefix: &'static str) { 12 file_per_thread_logger::initialize(prefix); 13 file_per_thread_logger::allow_uninitialized(); 14 15 // Extending behavior of default spawner: 16 // https://docs.rs/rayon/1.1.0/rayon/struct.ThreadPoolBuilder.html#method.spawn_handler 17 // Source code says DefaultSpawner is implementation detail and 18 // shouldn't be used directly. 19 #[cfg(feature = "parallel-compilation")] 20 rayon::ThreadPoolBuilder::new() 21 .spawn_handler(move |thread| { 22 let mut b = std::thread::Builder::new(); 23 if let Some(name) = thread.name() { 24 b = b.name(name.to_owned()); 25 } 26 if let Some(stack_size) = thread.stack_size() { 27 b = b.stack_size(stack_size); 28 } 29 b.spawn(move || { 30 file_per_thread_logger::initialize(prefix); 31 thread.run() 32 })?; 33 Ok(()) 34 }) 35 .build_global() 36 .unwrap(); 37 } 38 39 wasmtime_option_group! { 40 #[derive(PartialEq, Clone)] 41 pub struct OptimizeOptions { 42 /// Optimization level of generated code (0-2, s; default: 2) 43 pub opt_level: Option<wasmtime::OptLevel>, 44 45 /// Register allocator algorithm choice. 46 pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>, 47 48 /// Do not allow Wasm linear memories to move in the host process's 49 /// address space. 50 pub memory_may_move: Option<bool>, 51 52 /// Initial virtual memory allocation size for memories. 53 pub memory_reservation: Option<u64>, 54 55 /// Bytes to reserve at the end of linear memory for growth into. 56 pub memory_reservation_for_growth: Option<u64>, 57 58 /// Size, in bytes, of guard pages for linear memories. 59 pub memory_guard_size: Option<u64>, 60 61 /// Indicates whether an unmapped region of memory is placed before all 62 /// linear memories. 63 pub guard_before_linear_memory: Option<bool>, 64 65 /// Whether to initialize tables lazily, so that instantiation is 66 /// fast but indirect calls are a little slower. If no, tables are 67 /// initialized eagerly from any active element segments that apply to 68 /// them during instantiation. (default: yes) 69 pub table_lazy_init: Option<bool>, 70 71 /// Enable the pooling allocator, in place of the on-demand allocator. 72 pub pooling_allocator: Option<bool>, 73 74 /// The number of decommits to do per batch. A batch size of 1 75 /// effectively disables decommit batching. (default: 1) 76 pub pooling_decommit_batch_size: Option<usize>, 77 78 /// How many bytes to keep resident between instantiations for the 79 /// pooling allocator in linear memories. 80 pub pooling_memory_keep_resident: Option<usize>, 81 82 /// How many bytes to keep resident between instantiations for the 83 /// pooling allocator in tables. 84 pub pooling_table_keep_resident: Option<usize>, 85 86 /// Enable memory protection keys for the pooling allocator; this can 87 /// optimize the size of memory slots. 88 pub pooling_memory_protection_keys: Option<bool>, 89 90 /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime 91 /// will use. (default: 16) 92 pub pooling_max_memory_protection_keys: Option<usize>, 93 94 /// Configure attempting to initialize linear memory via a 95 /// copy-on-write mapping (default: yes) 96 pub memory_init_cow: Option<bool>, 97 98 /// The maximum number of WebAssembly instances which can be created 99 /// with the pooling allocator. 100 pub pooling_total_core_instances: Option<u32>, 101 102 /// The maximum number of WebAssembly components which can be created 103 /// with the pooling allocator. 104 pub pooling_total_component_instances: Option<u32>, 105 106 /// The maximum number of WebAssembly memories which can be created with 107 /// the pooling allocator. 108 pub pooling_total_memories: Option<u32>, 109 110 /// The maximum number of WebAssembly tables which can be created with 111 /// the pooling allocator. 112 pub pooling_total_tables: Option<u32>, 113 114 /// The maximum number of WebAssembly stacks which can be created with 115 /// the pooling allocator. 116 pub pooling_total_stacks: Option<u32>, 117 118 /// The maximum runtime size of each linear memory in the pooling 119 /// allocator, in bytes. 120 pub pooling_max_memory_size: Option<usize>, 121 122 /// The maximum table elements for any table defined in a module when 123 /// using the pooling allocator. 124 pub pooling_table_elements: Option<usize>, 125 126 /// The maximum size, in bytes, allocated for a core instance's metadata 127 /// when using the pooling allocator. 128 pub pooling_max_core_instance_size: Option<usize>, 129 130 /// Configures the maximum number of "unused warm slots" to retain in the 131 /// pooling allocator. (default: 100) 132 pub pooling_max_unused_warm_slots: Option<u32>, 133 134 /// Configures whether or not stacks used for async futures are reset to 135 /// zero after usage. (default: false) 136 pub pooling_async_stack_zeroing: Option<bool>, 137 138 /// How much memory, in bytes, to keep resident for async stacks allocated 139 /// with the pooling allocator. (default: 0) 140 pub pooling_async_stack_keep_resident: Option<usize>, 141 142 /// The maximum size, in bytes, allocated for a component instance's 143 /// `VMComponentContext` metadata. (default: 1MiB) 144 pub pooling_max_component_instance_size: Option<usize>, 145 146 /// The maximum number of core instances a single component may contain 147 /// (default is unlimited). 148 pub pooling_max_core_instances_per_component: Option<u32>, 149 150 /// The maximum number of Wasm linear memories that a single component may 151 /// transitively contain (default is unlimited). 152 pub pooling_max_memories_per_component: Option<u32>, 153 154 /// The maximum number of tables that a single component may transitively 155 /// contain (default is unlimited). 156 pub pooling_max_tables_per_component: Option<u32>, 157 158 /// The maximum number of defined tables for a core module. (default: 1) 159 pub pooling_max_tables_per_module: Option<u32>, 160 161 /// The maximum number of defined linear memories for a module. (default: 1) 162 pub pooling_max_memories_per_module: Option<u32>, 163 164 /// The maximum number of concurrent GC heaps supported. (default: 1000) 165 pub pooling_total_gc_heaps: Option<u32>, 166 167 /// Enable or disable the use of host signal handlers for traps. 168 pub signals_based_traps: Option<bool>, 169 170 /// DEPRECATED: Use `-Cmemory-guard-size=N` instead. 171 pub dynamic_memory_guard_size: Option<u64>, 172 173 /// DEPRECATED: Use `-Cmemory-guard-size=N` instead. 174 pub static_memory_guard_size: Option<u64>, 175 176 /// DEPRECATED: Use `-Cmemory-may-move` instead. 177 pub static_memory_forced: Option<bool>, 178 179 /// DEPRECATED: Use `-Cmemory-reservation=N` instead. 180 pub static_memory_maximum_size: Option<u64>, 181 182 /// DEPRECATED: Use `-Cmemory-reservation-for-growth=N` instead. 183 pub dynamic_memory_reserved_for_growth: Option<u64>, 184 } 185 186 enum Optimize { 187 ... 188 } 189 } 190 191 wasmtime_option_group! { 192 #[derive(PartialEq, Clone)] 193 pub struct CodegenOptions { 194 /// Either `cranelift` or `winch`. 195 /// 196 /// Currently only `cranelift` and `winch` are supported, but not all 197 /// builds of Wasmtime have both built in. 198 pub compiler: Option<wasmtime::Strategy>, 199 /// Which garbage collector to use: `drc` or `null`. 200 /// 201 /// `drc` is the deferred reference-counting collector. 202 /// 203 /// `null` is the null garbage collector, which does not collect any 204 /// garbage. 205 /// 206 /// Note that not all builds of Wasmtime will have support for garbage 207 /// collection included. 208 pub collector: Option<wasmtime::Collector>, 209 /// Enable Cranelift's internal debug verifier (expensive) 210 pub cranelift_debug_verifier: Option<bool>, 211 /// Whether or not to enable caching of compiled modules. 212 pub cache: Option<bool>, 213 /// Configuration for compiled module caching. 214 pub cache_config: Option<String>, 215 /// Whether or not to enable parallel compilation of modules. 216 pub parallel_compilation: Option<bool>, 217 /// Whether to enable proof-carrying code (PCC)-based validation. 218 pub pcc: Option<bool>, 219 /// Controls whether native unwind information is present in compiled 220 /// object files. 221 pub native_unwind_info: Option<bool>, 222 223 #[prefixed = "cranelift"] 224 /// Set a cranelift-specific option. Use `wasmtime settings` to see 225 /// all. 226 pub cranelift: Vec<(String, Option<String>)>, 227 } 228 229 enum Codegen { 230 ... 231 } 232 } 233 234 wasmtime_option_group! { 235 #[derive(PartialEq, Clone)] 236 pub struct DebugOptions { 237 /// Enable generation of DWARF debug information in compiled code. 238 pub debug_info: Option<bool>, 239 /// Configure whether compiled code can map native addresses to wasm. 240 pub address_map: Option<bool>, 241 /// Configure whether logging is enabled. 242 pub logging: Option<bool>, 243 /// Configure whether logs are emitted to files 244 pub log_to_files: Option<bool>, 245 /// Enable coredump generation to this file after a WebAssembly trap. 246 pub coredump: Option<String>, 247 } 248 249 enum Debug { 250 ... 251 } 252 } 253 254 wasmtime_option_group! { 255 #[derive(PartialEq, Clone)] 256 pub struct WasmOptions { 257 /// Enable canonicalization of all NaN values. 258 pub nan_canonicalization: Option<bool>, 259 /// Enable execution fuel with N units fuel, trapping after running out 260 /// of fuel. 261 /// 262 /// Most WebAssembly instructions consume 1 unit of fuel. Some 263 /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0 264 /// units, as any execution cost associated with them involves other 265 /// instructions which do consume fuel. 266 pub fuel: Option<u64>, 267 /// Yield when a global epoch counter changes, allowing for async 268 /// operation without blocking the executor. 269 pub epoch_interruption: Option<bool>, 270 /// Maximum stack size, in bytes, that wasm is allowed to consume before a 271 /// stack overflow is reported. 272 pub max_wasm_stack: Option<usize>, 273 /// Stack size, in bytes, that will be allocated for async stacks. 274 /// 275 /// Note that this must be larger than `max-wasm-stack` and the 276 /// difference between the two is how much stack the host has to execute 277 /// on. 278 pub async_stack_size: Option<usize>, 279 /// Allow unknown exports when running commands. 280 pub unknown_exports_allow: Option<bool>, 281 /// Allow the main module to import unknown functions, using an 282 /// implementation that immediately traps, when running commands. 283 pub unknown_imports_trap: Option<bool>, 284 /// Allow the main module to import unknown functions, using an 285 /// implementation that returns default values, when running commands. 286 pub unknown_imports_default: Option<bool>, 287 /// Enables memory error checking. (see wmemcheck.md for more info) 288 pub wmemcheck: Option<bool>, 289 /// Maximum size, in bytes, that a linear memory is allowed to reach. 290 /// 291 /// Growth beyond this limit will cause `memory.grow` instructions in 292 /// WebAssembly modules to return -1 and fail. 293 pub max_memory_size: Option<usize>, 294 /// Maximum size, in table elements, that a table is allowed to reach. 295 pub max_table_elements: Option<usize>, 296 /// Maximum number of WebAssembly instances allowed to be created. 297 pub max_instances: Option<usize>, 298 /// Maximum number of WebAssembly tables allowed to be created. 299 pub max_tables: Option<usize>, 300 /// Maximum number of WebAssembly linear memories allowed to be created. 301 pub max_memories: Option<usize>, 302 /// Force a trap to be raised on `memory.grow` and `table.grow` failure 303 /// instead of returning -1 from these instructions. 304 /// 305 /// This is not necessarily a spec-compliant option to enable but can be 306 /// useful for tracking down a backtrace of what is requesting so much 307 /// memory, for example. 308 pub trap_on_grow_failure: Option<bool>, 309 /// Maximum execution time of wasm code before timing out (1, 2s, 100ms, etc) 310 pub timeout: Option<Duration>, 311 /// Configures support for all WebAssembly proposals implemented. 312 pub all_proposals: Option<bool>, 313 /// Configure support for the bulk memory proposal. 314 pub bulk_memory: Option<bool>, 315 /// Configure support for the multi-memory proposal. 316 pub multi_memory: Option<bool>, 317 /// Configure support for the multi-value proposal. 318 pub multi_value: Option<bool>, 319 /// Configure support for the reference-types proposal. 320 pub reference_types: Option<bool>, 321 /// Configure support for the simd proposal. 322 pub simd: Option<bool>, 323 /// Configure support for the relaxed-simd proposal. 324 pub relaxed_simd: Option<bool>, 325 /// Configure forcing deterministic and host-independent behavior of 326 /// the relaxed-simd instructions. 327 /// 328 /// By default these instructions may have architecture-specific behavior as 329 /// allowed by the specification, but this can be used to force the behavior 330 /// of these instructions to match the deterministic behavior classified in 331 /// the specification. Note that enabling this option may come at a 332 /// performance cost. 333 pub relaxed_simd_deterministic: Option<bool>, 334 /// Configure support for the tail-call proposal. 335 pub tail_call: Option<bool>, 336 /// Configure support for the threads proposal. 337 pub threads: Option<bool>, 338 /// Configure support for the memory64 proposal. 339 pub memory64: Option<bool>, 340 /// Configure support for the component-model proposal. 341 pub component_model: Option<bool>, 342 /// Configure support for 33+ flags in the component model. 343 pub component_model_more_flags: Option<bool>, 344 /// Component model support for more than one return value. 345 pub component_model_multiple_returns: Option<bool>, 346 /// Configure support for the function-references proposal. 347 pub function_references: Option<bool>, 348 /// Configure support for the GC proposal. 349 pub gc: Option<bool>, 350 /// Configure support for the custom-page-sizes proposal. 351 pub custom_page_sizes: Option<bool>, 352 /// Configure support for the wide-arithmetic proposal. 353 pub wide_arithmetic: Option<bool>, 354 /// Configure support for the extended-const proposal. 355 pub extended_const: Option<bool>, 356 } 357 358 enum Wasm { 359 ... 360 } 361 } 362 363 wasmtime_option_group! { 364 #[derive(PartialEq, Clone)] 365 pub struct WasiOptions { 366 /// Enable support for WASI CLI APIs, including filesystems, sockets, clocks, and random. 367 pub cli: Option<bool>, 368 /// Enable WASI APIs marked as: @unstable(feature = cli-exit-with-code) 369 pub cli_exit_with_code: Option<bool>, 370 /// Deprecated alias for `cli` 371 pub common: Option<bool>, 372 /// Enable support for WASI neural network imports (experimental) 373 pub nn: Option<bool>, 374 /// Enable support for WASI threading imports (experimental). Implies preview2=false. 375 pub threads: Option<bool>, 376 /// Enable support for WASI HTTP imports 377 pub http: Option<bool>, 378 /// Number of distinct write calls to the outgoing body's output-stream 379 /// that the implementation will buffer. 380 /// Default: 1. 381 pub http_outgoing_body_buffer_chunks: Option<usize>, 382 /// Maximum size allowed in a write call to the outgoing body's output-stream. 383 /// Default: 1024 * 1024. 384 pub http_outgoing_body_chunk_size: Option<usize>, 385 /// Enable support for WASI config imports (experimental) 386 pub config: Option<bool>, 387 /// Enable support for WASI key-value imports (experimental) 388 pub keyvalue: Option<bool>, 389 /// Inherit environment variables and file descriptors following the 390 /// systemd listen fd specification (UNIX only) 391 pub listenfd: Option<bool>, 392 /// Grant access to the given TCP listen socket 393 pub tcplisten: Vec<String>, 394 /// Implement WASI Preview1 using new Preview2 implementation (true, default) or legacy 395 /// implementation (false) 396 pub preview2: Option<bool>, 397 /// Pre-load machine learning graphs (i.e., models) for use by wasi-nn. 398 /// 399 /// Each use of the flag will preload a ML model from the host directory 400 /// using the given model encoding. The model will be mapped to the 401 /// directory name: e.g., `--wasi-nn-graph openvino:/foo/bar` will preload 402 /// an OpenVINO model named `bar`. Note that which model encodings are 403 /// available is dependent on the backends implemented in the 404 /// `wasmtime_wasi_nn` crate. 405 pub nn_graph: Vec<WasiNnGraph>, 406 /// Flag for WASI preview2 to inherit the host's network within the 407 /// guest so it has full access to all addresses/ports/etc. 408 pub inherit_network: Option<bool>, 409 /// Indicates whether `wasi:sockets/ip-name-lookup` is enabled or not. 410 pub allow_ip_name_lookup: Option<bool>, 411 /// Indicates whether `wasi:sockets` TCP support is enabled or not. 412 pub tcp: Option<bool>, 413 /// Indicates whether `wasi:sockets` UDP support is enabled or not. 414 pub udp: Option<bool>, 415 /// Enable WASI APIs marked as: @unstable(feature = network-error-code) 416 pub network_error_code: Option<bool>, 417 /// Allows imports from the `wasi_unstable` core wasm module. 418 pub preview0: Option<bool>, 419 /// Inherit all environment variables from the parent process. 420 /// 421 /// This option can be further overwritten with `--env` flags. 422 pub inherit_env: Option<bool>, 423 /// Pass a wasi config variable to the program. 424 pub config_var: Vec<KeyValuePair>, 425 /// Preset data for the In-Memory provider of WASI key-value API. 426 pub keyvalue_in_memory_data: Vec<KeyValuePair>, 427 } 428 429 enum Wasi { 430 ... 431 } 432 } 433 434 #[derive(Debug, Clone, PartialEq)] 435 pub struct WasiNnGraph { 436 pub format: String, 437 pub dir: String, 438 } 439 440 #[derive(Debug, Clone, PartialEq)] 441 pub struct KeyValuePair { 442 pub key: String, 443 pub value: String, 444 } 445 446 /// Common options for commands that translate WebAssembly modules 447 #[derive(Parser, Clone)] 448 pub struct CommonOptions { 449 // These options groups are used to parse `-O` and such options but aren't 450 // the raw form consumed by the CLI. Instead they're pushed into the `pub` 451 // fields below as part of the `configure` method. 452 // 453 // Ideally clap would support `pub opts: OptimizeOptions` and parse directly 454 // into that but it does not appear to do so for multiple `-O` flags for 455 // now. 456 /// Optimization and tuning related options for wasm performance, `-O help` to 457 /// see all. 458 #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")] 459 opts_raw: Vec<opt::CommaSeparated<Optimize>>, 460 461 /// Codegen-related configuration options, `-C help` to see all. 462 #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")] 463 codegen_raw: Vec<opt::CommaSeparated<Codegen>>, 464 465 /// Debug-related configuration options, `-D help` to see all. 466 #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")] 467 debug_raw: Vec<opt::CommaSeparated<Debug>>, 468 469 /// Options for configuring semantic execution of WebAssembly, `-W help` to see 470 /// all. 471 #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")] 472 wasm_raw: Vec<opt::CommaSeparated<Wasm>>, 473 474 /// Options for configuring WASI and its proposals, `-S help` to see all. 475 #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")] 476 wasi_raw: Vec<opt::CommaSeparated<Wasi>>, 477 478 // These fields are filled in by the `configure` method below via the 479 // options parsed from the CLI above. This is what the CLI should use. 480 #[arg(skip)] 481 configured: bool, 482 #[arg(skip)] 483 pub opts: OptimizeOptions, 484 #[arg(skip)] 485 pub codegen: CodegenOptions, 486 #[arg(skip)] 487 pub debug: DebugOptions, 488 #[arg(skip)] 489 pub wasm: WasmOptions, 490 #[arg(skip)] 491 pub wasi: WasiOptions, 492 493 /// The target triple; default is the host triple 494 #[arg(long, value_name = "TARGET")] 495 pub target: Option<String>, 496 } 497 498 macro_rules! match_feature { 499 ( 500 [$feat:tt : $config:expr] 501 $val:ident => $e:expr, 502 $p:pat => err, 503 ) => { 504 #[cfg(feature = $feat)] 505 { 506 if let Some($val) = $config { 507 $e; 508 } 509 } 510 #[cfg(not(feature = $feat))] 511 { 512 if let Some($p) = $config { 513 anyhow::bail!(concat!("support for ", $feat, " disabled at compile time")); 514 } 515 } 516 }; 517 } 518 519 impl CommonOptions { 520 fn configure(&mut self) { 521 if self.configured { 522 return; 523 } 524 self.configured = true; 525 self.opts.configure_with(&self.opts_raw); 526 self.codegen.configure_with(&self.codegen_raw); 527 self.debug.configure_with(&self.debug_raw); 528 self.wasm.configure_with(&self.wasm_raw); 529 self.wasi.configure_with(&self.wasi_raw); 530 } 531 532 pub fn init_logging(&mut self) -> Result<()> { 533 self.configure(); 534 if self.debug.logging == Some(false) { 535 return Ok(()); 536 } 537 #[cfg(feature = "logging")] 538 if self.debug.log_to_files == Some(true) { 539 let prefix = "wasmtime.dbg."; 540 init_file_per_thread_logger(prefix); 541 } else { 542 use std::io::IsTerminal; 543 use tracing_subscriber::{EnvFilter, FmtSubscriber}; 544 let builder = FmtSubscriber::builder() 545 .with_writer(std::io::stderr) 546 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG")) 547 .with_ansi(std::io::stderr().is_terminal()); 548 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) { 549 builder 550 .with_level(false) 551 .with_target(false) 552 .without_time() 553 .init() 554 } else { 555 builder.init(); 556 } 557 } 558 #[cfg(not(feature = "logging"))] 559 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) { 560 anyhow::bail!("support for logging disabled at compile time"); 561 } 562 Ok(()) 563 } 564 565 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> { 566 self.configure(); 567 let mut config = Config::new(); 568 569 match_feature! { 570 ["cranelift" : self.codegen.compiler] 571 strategy => config.strategy(strategy), 572 _ => err, 573 } 574 match_feature! { 575 ["gc" : self.codegen.collector] 576 collector => config.collector(collector), 577 _ => err, 578 } 579 if let Some(target) = &self.target { 580 config.target(target)?; 581 } 582 match_feature! { 583 ["cranelift" : self.codegen.cranelift_debug_verifier] 584 enable => config.cranelift_debug_verifier(enable), 585 true => err, 586 } 587 if let Some(enable) = self.debug.debug_info { 588 config.debug_info(enable); 589 } 590 if self.debug.coredump.is_some() { 591 #[cfg(feature = "coredump")] 592 config.coredump_on_trap(true); 593 #[cfg(not(feature = "coredump"))] 594 anyhow::bail!("support for coredumps disabled at compile time"); 595 } 596 match_feature! { 597 ["cranelift" : self.opts.opt_level] 598 level => config.cranelift_opt_level(level), 599 _ => err, 600 } 601 match_feature! { 602 ["cranelift": self.opts.regalloc_algorithm] 603 algo => config.cranelift_regalloc_algorithm(algo), 604 _ => err, 605 } 606 match_feature! { 607 ["cranelift" : self.wasm.nan_canonicalization] 608 enable => config.cranelift_nan_canonicalization(enable), 609 true => err, 610 } 611 match_feature! { 612 ["cranelift" : self.codegen.pcc] 613 enable => config.cranelift_pcc(enable), 614 true => err, 615 } 616 617 self.enable_wasm_features(&mut config)?; 618 619 #[cfg(feature = "cranelift")] 620 for (name, value) in self.codegen.cranelift.iter() { 621 let name = name.replace('-', "_"); 622 unsafe { 623 match value { 624 Some(val) => { 625 config.cranelift_flag_set(&name, val); 626 } 627 None => { 628 config.cranelift_flag_enable(&name); 629 } 630 } 631 } 632 } 633 #[cfg(not(feature = "cranelift"))] 634 if !self.codegen.cranelift.is_empty() { 635 anyhow::bail!("support for cranelift disabled at compile time"); 636 } 637 638 #[cfg(feature = "cache")] 639 if self.codegen.cache != Some(false) { 640 match &self.codegen.cache_config { 641 Some(path) => { 642 config.cache_config_load(path)?; 643 } 644 None => { 645 config.cache_config_load_default()?; 646 } 647 } 648 } 649 #[cfg(not(feature = "cache"))] 650 if self.codegen.cache == Some(true) { 651 anyhow::bail!("support for caching disabled at compile time"); 652 } 653 654 match_feature! { 655 ["parallel-compilation" : self.codegen.parallel_compilation] 656 enable => config.parallel_compilation(enable), 657 true => err, 658 } 659 660 let memory_reservation = self 661 .opts 662 .memory_reservation 663 .or(self.opts.static_memory_maximum_size); 664 match_feature! { 665 ["signals-based-traps" : memory_reservation] 666 size => config.memory_reservation(size), 667 _ => err, 668 } 669 670 match_feature! { 671 ["signals-based-traps" : self.opts.static_memory_forced] 672 enable => config.memory_may_move(!enable), 673 _ => err, 674 } 675 match_feature! { 676 ["signals-based-traps" : self.opts.memory_may_move] 677 enable => config.memory_may_move(enable), 678 _ => err, 679 } 680 681 let memory_guard_size = self 682 .opts 683 .static_memory_guard_size 684 .or(self.opts.dynamic_memory_guard_size) 685 .or(self.opts.memory_guard_size); 686 match_feature! { 687 ["signals-based-traps" : memory_guard_size] 688 size => config.memory_guard_size(size), 689 _ => err, 690 } 691 692 let mem_for_growth = self 693 .opts 694 .memory_reservation_for_growth 695 .or(self.opts.dynamic_memory_reserved_for_growth); 696 match_feature! { 697 ["signals-based-traps" : mem_for_growth] 698 size => config.memory_reservation_for_growth(size), 699 _ => err, 700 } 701 match_feature! { 702 ["signals-based-traps" : self.opts.guard_before_linear_memory] 703 enable => config.guard_before_linear_memory(enable), 704 _ => err, 705 } 706 if let Some(enable) = self.opts.table_lazy_init { 707 config.table_lazy_init(enable); 708 } 709 710 // If fuel has been configured, set the `consume fuel` flag on the config. 711 if self.wasm.fuel.is_some() { 712 config.consume_fuel(true); 713 } 714 715 if let Some(enable) = self.wasm.epoch_interruption { 716 config.epoch_interruption(enable); 717 } 718 if let Some(enable) = self.debug.address_map { 719 config.generate_address_map(enable); 720 } 721 match_feature! { 722 ["signals-based-traps" : self.opts.memory_init_cow] 723 enable => config.memory_init_cow(enable), 724 _ => err, 725 } 726 match_feature! { 727 ["signals-based-traps" : self.opts.signals_based_traps] 728 enable => config.signals_based_traps(enable), 729 _ => err, 730 } 731 if let Some(enable) = self.codegen.native_unwind_info { 732 config.native_unwind_info(enable); 733 } 734 735 match_feature! { 736 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)] 737 enable => { 738 if enable { 739 let mut cfg = wasmtime::PoolingAllocationConfig::default(); 740 if let Some(size) = self.opts.pooling_memory_keep_resident { 741 cfg.linear_memory_keep_resident(size); 742 } 743 if let Some(size) = self.opts.pooling_table_keep_resident { 744 cfg.table_keep_resident(size); 745 } 746 if let Some(limit) = self.opts.pooling_total_core_instances { 747 cfg.total_core_instances(limit); 748 } 749 if let Some(limit) = self.opts.pooling_total_component_instances { 750 cfg.total_component_instances(limit); 751 } 752 if let Some(limit) = self.opts.pooling_total_memories { 753 cfg.total_memories(limit); 754 } 755 if let Some(limit) = self.opts.pooling_total_tables { 756 cfg.total_tables(limit); 757 } 758 if let Some(limit) = self.opts.pooling_table_elements { 759 cfg.table_elements(limit); 760 } 761 if let Some(limit) = self.opts.pooling_max_core_instance_size { 762 cfg.max_core_instance_size(limit); 763 } 764 match_feature! { 765 ["async" : self.opts.pooling_total_stacks] 766 limit => cfg.total_stacks(limit), 767 _ => err, 768 } 769 if let Some(max) = self.opts.pooling_max_memory_size { 770 cfg.max_memory_size(max); 771 } 772 if let Some(size) = self.opts.pooling_decommit_batch_size { 773 cfg.decommit_batch_size(size); 774 } 775 if let Some(max) = self.opts.pooling_max_unused_warm_slots { 776 cfg.max_unused_warm_slots(max); 777 } 778 match_feature! { 779 ["async" : self.opts.pooling_async_stack_zeroing] 780 enable => cfg.async_stack_zeroing(enable), 781 _ => err, 782 } 783 match_feature! { 784 ["async" : self.opts.pooling_async_stack_keep_resident] 785 size => cfg.async_stack_keep_resident(size), 786 _ => err, 787 } 788 if let Some(max) = self.opts.pooling_max_component_instance_size { 789 cfg.max_component_instance_size(max); 790 } 791 if let Some(max) = self.opts.pooling_max_core_instances_per_component { 792 cfg.max_core_instances_per_component(max); 793 } 794 if let Some(max) = self.opts.pooling_max_memories_per_component { 795 cfg.max_memories_per_component(max); 796 } 797 if let Some(max) = self.opts.pooling_max_tables_per_component { 798 cfg.max_tables_per_component(max); 799 } 800 if let Some(max) = self.opts.pooling_max_tables_per_module { 801 cfg.max_tables_per_module(max); 802 } 803 if let Some(max) = self.opts.pooling_max_memories_per_module { 804 cfg.max_memories_per_module(max); 805 } 806 match_feature! { 807 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys] 808 enable => cfg.memory_protection_keys(if enable { 809 wasmtime::MpkEnabled::Enable 810 } else { 811 wasmtime::MpkEnabled::Disable 812 }), 813 _ => err, 814 } 815 match_feature! { 816 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys] 817 max => cfg.max_memory_protection_keys(max), 818 _ => err, 819 } 820 match_feature! { 821 ["gc" : self.opts.pooling_total_gc_heaps] 822 max => cfg.total_gc_heaps(max), 823 _ => err, 824 } 825 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg)); 826 } 827 }, 828 true => err, 829 } 830 831 if self.opts.pooling_memory_protection_keys.unwrap_or(false) 832 && !self.opts.pooling_allocator.unwrap_or(false) 833 { 834 anyhow::bail!("memory protection keys require the pooling allocator"); 835 } 836 837 if self.opts.pooling_max_memory_protection_keys.is_some() 838 && !self.opts.pooling_memory_protection_keys.unwrap_or(false) 839 { 840 anyhow::bail!( 841 "max memory protection keys requires memory protection keys to be enabled" 842 ); 843 } 844 845 match_feature! { 846 ["async" : self.wasm.async_stack_size] 847 size => config.async_stack_size(size), 848 _ => err, 849 } 850 851 if let Some(max) = self.wasm.max_wasm_stack { 852 config.max_wasm_stack(max); 853 854 // If `-Wasync-stack-size` isn't passed then automatically adjust it 855 // to the wasm stack size provided here too. That prevents the need 856 // to pass both when one can generally be inferred from the other. 857 #[cfg(feature = "async")] 858 if self.wasm.async_stack_size.is_none() { 859 const DEFAULT_HOST_STACK: usize = 512 << 10; 860 config.async_stack_size(max + DEFAULT_HOST_STACK); 861 } 862 } 863 864 if let Some(enable) = self.wasm.relaxed_simd_deterministic { 865 config.relaxed_simd_deterministic(enable); 866 } 867 match_feature! { 868 ["cranelift" : self.wasm.wmemcheck] 869 enable => config.wmemcheck(enable), 870 true => err, 871 } 872 873 Ok(config) 874 } 875 876 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> { 877 let all = self.wasm.all_proposals; 878 879 if let Some(enable) = self.wasm.simd.or(all) { 880 config.wasm_simd(enable); 881 } 882 if let Some(enable) = self.wasm.relaxed_simd.or(all) { 883 config.wasm_relaxed_simd(enable); 884 } 885 if let Some(enable) = self.wasm.bulk_memory.or(all) { 886 config.wasm_bulk_memory(enable); 887 } 888 if let Some(enable) = self.wasm.multi_value.or(all) { 889 config.wasm_multi_value(enable); 890 } 891 if let Some(enable) = self.wasm.tail_call.or(all) { 892 config.wasm_tail_call(enable); 893 } 894 if let Some(enable) = self.wasm.multi_memory.or(all) { 895 config.wasm_multi_memory(enable); 896 } 897 if let Some(enable) = self.wasm.memory64.or(all) { 898 config.wasm_memory64(enable); 899 } 900 if let Some(enable) = self.wasm.custom_page_sizes.or(all) { 901 config.wasm_custom_page_sizes(enable); 902 } 903 if let Some(enable) = self.wasm.wide_arithmetic.or(all) { 904 config.wasm_wide_arithmetic(enable); 905 } 906 if let Some(enable) = self.wasm.extended_const.or(all) { 907 config.wasm_extended_const(enable); 908 } 909 910 macro_rules! handle_conditionally_compiled { 911 ($(($feature:tt, $field:tt, $method:tt))*) => ($( 912 if let Some(enable) = self.wasm.$field.or(all) { 913 #[cfg(feature = $feature)] 914 config.$method(enable); 915 #[cfg(not(feature = $feature))] 916 if enable && all.is_none() { 917 anyhow::bail!("support for {} was disabled at compile-time", $feature); 918 } 919 } 920 )*) 921 } 922 923 handle_conditionally_compiled! { 924 ("component-model", component_model, wasm_component_model) 925 ("component-model", component_model_more_flags, wasm_component_model_more_flags) 926 ("component-model", component_model_multiple_returns, wasm_component_model_multiple_returns) 927 ("threads", threads, wasm_threads) 928 ("gc", gc, wasm_gc) 929 ("gc", reference_types, wasm_reference_types) 930 ("gc", function_references, wasm_function_references) 931 } 932 Ok(()) 933 } 934 } 935