1 //! Generate a configuration for both Wasmtime and the Wasm module to execute. 2 3 use super::{ 4 AsyncConfig, CodegenSettings, InstanceAllocationStrategy, MemoryConfig, ModuleConfig, 5 NormalMemoryConfig, UnalignedMemoryCreator, 6 }; 7 use crate::oracles::{StoreLimits, Timeout}; 8 use anyhow::Result; 9 use arbitrary::{Arbitrary, Unstructured}; 10 use std::sync::Arc; 11 use std::time::Duration; 12 use wasmtime::{Engine, Module, MpkEnabled, Store}; 13 use wasmtime_test_util::wast::{WastConfig, WastTest, limits}; 14 15 /// Configuration for `wasmtime::Config` and generated modules for a session of 16 /// fuzzing. 17 /// 18 /// This configuration guides what modules are generated, how wasmtime 19 /// configuration is generated, and is typically itself generated through a call 20 /// to `Arbitrary` which allows for a form of "swarm testing". 21 #[derive(Debug, Clone)] 22 pub struct Config { 23 /// Configuration related to the `wasmtime::Config`. 24 pub wasmtime: WasmtimeConfig, 25 /// Configuration related to generated modules. 26 pub module_config: ModuleConfig, 27 } 28 29 impl Config { 30 /// Indicates that this configuration is being used for differential 31 /// execution. 32 /// 33 /// The purpose of this function is to update the configuration which was 34 /// generated to be compatible with execution in multiple engines. The goal 35 /// is to produce the exact same result in all engines so we need to paper 36 /// over things like nan differences and memory/table behavior differences. 37 pub fn set_differential_config(&mut self) { 38 let config = &mut self.module_config.config; 39 40 // Make it more likely that there are types available to generate a 41 // function with. 42 config.min_types = config.min_types.max(1); 43 config.max_types = config.max_types.max(1); 44 45 // Generate at least one function 46 config.min_funcs = config.min_funcs.max(1); 47 config.max_funcs = config.max_funcs.max(1); 48 49 // Allow a memory to be generated, but don't let it get too large. 50 // Additionally require the maximum size to guarantee that the growth 51 // behavior is consistent across engines. 52 config.max_memory32_bytes = 10 << 16; 53 config.max_memory64_bytes = 10 << 16; 54 config.memory_max_size_required = true; 55 56 // If tables are generated make sure they don't get too large to avoid 57 // hitting any engine-specific limit. Additionally ensure that the 58 // maximum size is required to guarantee consistent growth across 59 // engines. 60 // 61 // Note that while reference types are disabled below, only allow one 62 // table. 63 config.max_table_elements = 1_000; 64 config.table_max_size_required = true; 65 66 // Don't allow any imports 67 config.max_imports = 0; 68 69 // Try to get the function and the memory exported 70 config.export_everything = true; 71 72 // NaN is canonicalized at the wasm level for differential fuzzing so we 73 // can paper over NaN differences between engines. 74 config.canonicalize_nans = true; 75 76 // If using the pooling allocator, update the instance limits too 77 if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.wasmtime.strategy { 78 // One single-page memory 79 pooling.total_memories = config.max_memories as u32; 80 pooling.max_memory_size = 10 << 16; 81 pooling.max_memories_per_module = config.max_memories as u32; 82 if pooling.memory_protection_keys == MpkEnabled::Auto 83 && pooling.max_memory_protection_keys > 1 84 { 85 pooling.total_memories = 86 pooling.total_memories * (pooling.max_memory_protection_keys as u32); 87 } 88 89 pooling.total_tables = config.max_tables as u32; 90 pooling.table_elements = 1_000; 91 pooling.max_tables_per_module = config.max_tables as u32; 92 93 pooling.core_instance_size = 1_000_000; 94 95 if let MemoryConfig::Normal(cfg) = &mut self.wasmtime.memory_config { 96 match &mut cfg.memory_reservation { 97 Some(size) => *size = (*size).max(pooling.max_memory_size as u64), 98 other @ None => *other = Some(pooling.max_memory_size as u64), 99 } 100 } 101 } 102 103 // These instructions are explicitly not expected to be exactly the same 104 // across engines. Don't fuzz them. 105 config.relaxed_simd_enabled = false; 106 } 107 108 /// Uses this configuration and the supplied source of data to generate 109 /// a wasm module. 110 /// 111 /// If a `default_fuel` is provided, the resulting module will be configured 112 /// to ensure termination; as doing so will add an additional global to the module, 113 /// the pooling allocator, if configured, will also have its globals limit updated. 114 pub fn generate( 115 &self, 116 input: &mut Unstructured<'_>, 117 default_fuel: Option<u32>, 118 ) -> arbitrary::Result<wasm_smith::Module> { 119 self.module_config.generate(input, default_fuel) 120 } 121 122 /// Updates this configuration to be able to run the `test` specified. 123 /// 124 /// This primarily updates `self.module_config` to ensure that it enables 125 /// all features and proposals necessary to execute the `test` specified. 126 /// This will additionally update limits in the pooling allocator to be able 127 /// to execute all tests. 128 pub fn make_wast_test_compliant(&mut self, test: &WastTest) -> WastConfig { 129 let wasmtime_test_util::wast::TestConfig { 130 memory64, 131 custom_page_sizes, 132 multi_memory, 133 threads, 134 shared_everything_threads, 135 gc, 136 function_references, 137 relaxed_simd, 138 reference_types, 139 tail_call, 140 extended_const, 141 wide_arithmetic, 142 component_model_async, 143 component_model_async_builtins, 144 component_model_async_stackful, 145 simd, 146 exceptions, 147 legacy_exceptions, 148 149 hogs_memory: _, 150 nan_canonicalization: _, 151 gc_types: _, 152 } = test.config; 153 154 // Enable/disable some proposals that aren't configurable in wasm-smith 155 // but are configurable in Wasmtime. 156 self.module_config.function_references_enabled = 157 function_references.or(gc).unwrap_or(false); 158 self.module_config.component_model_async = component_model_async.unwrap_or(false); 159 self.module_config.component_model_async_builtins = 160 component_model_async_builtins.unwrap_or(false); 161 self.module_config.component_model_async_stackful = 162 component_model_async_stackful.unwrap_or(false); 163 self.module_config.legacy_exceptions = legacy_exceptions.unwrap_or(false); 164 165 // Enable/disable proposals that wasm-smith has knobs for which will be 166 // read when creating `wasmtime::Config`. 167 let config = &mut self.module_config.config; 168 config.bulk_memory_enabled = true; 169 config.multi_value_enabled = true; 170 config.wide_arithmetic_enabled = wide_arithmetic.unwrap_or(false); 171 config.memory64_enabled = memory64.unwrap_or(false); 172 config.relaxed_simd_enabled = relaxed_simd.unwrap_or(false); 173 config.simd_enabled = config.relaxed_simd_enabled || simd.unwrap_or(false); 174 config.tail_call_enabled = tail_call.unwrap_or(false); 175 config.custom_page_sizes_enabled = custom_page_sizes.unwrap_or(false); 176 config.threads_enabled = threads.unwrap_or(false); 177 config.shared_everything_threads_enabled = shared_everything_threads.unwrap_or(false); 178 config.gc_enabled = gc.unwrap_or(false); 179 config.reference_types_enabled = config.gc_enabled 180 || self.module_config.function_references_enabled 181 || reference_types.unwrap_or(false); 182 config.extended_const_enabled = extended_const.unwrap_or(false); 183 config.exceptions_enabled = exceptions.unwrap_or(false); 184 if multi_memory.unwrap_or(false) { 185 config.max_memories = limits::MEMORIES_PER_MODULE as usize; 186 } else { 187 config.max_memories = 1; 188 } 189 190 match &mut self.wasmtime.memory_config { 191 MemoryConfig::Normal(config) => { 192 if let Some(n) = &mut config.memory_reservation { 193 *n = (*n).max(limits::MEMORY_SIZE as u64); 194 } 195 } 196 MemoryConfig::CustomUnaligned => {} 197 } 198 199 // FIXME: it might be more ideal to avoid the need for this entirely 200 // and to just let the test fail. If a test fails due to a pooling 201 // allocator resource limit being met we could ideally detect that and 202 // let the fuzz test case pass. That would avoid the need to hardcode 203 // so much here and in theory wouldn't reduce the usefulness of fuzzers 204 // all that much. At this time though we can't easily test this configuration. 205 if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.wasmtime.strategy { 206 // Clamp protection keys between 1 & 2 to reduce the number of 207 // slots and then multiply the total memories by the number of keys 208 // we have since a single store has access to only one key. 209 pooling.max_memory_protection_keys = pooling.max_memory_protection_keys.max(1).min(2); 210 pooling.total_memories = pooling 211 .total_memories 212 .max(limits::MEMORIES * (pooling.max_memory_protection_keys as u32)); 213 214 // For other limits make sure they meet the minimum threshold 215 // required for our wast tests. 216 pooling.total_component_instances = pooling 217 .total_component_instances 218 .max(limits::COMPONENT_INSTANCES); 219 pooling.total_tables = pooling.total_tables.max(limits::TABLES); 220 pooling.max_tables_per_module = 221 pooling.max_tables_per_module.max(limits::TABLES_PER_MODULE); 222 pooling.max_memories_per_module = pooling 223 .max_memories_per_module 224 .max(limits::MEMORIES_PER_MODULE); 225 pooling.max_memories_per_component = pooling 226 .max_memories_per_component 227 .max(limits::MEMORIES_PER_MODULE); 228 pooling.total_core_instances = pooling.total_core_instances.max(limits::CORE_INSTANCES); 229 pooling.max_memory_size = pooling.max_memory_size.max(limits::MEMORY_SIZE); 230 pooling.table_elements = pooling.table_elements.max(limits::TABLE_ELEMENTS); 231 pooling.core_instance_size = pooling.core_instance_size.max(limits::CORE_INSTANCE_SIZE); 232 pooling.component_instance_size = pooling 233 .component_instance_size 234 .max(limits::CORE_INSTANCE_SIZE); 235 } 236 237 // Return the test configuration that this fuzz configuration represents 238 // which is used afterwards to test if the `test` here is expected to 239 // fail or not. 240 WastConfig { 241 collector: match self.wasmtime.collector { 242 Collector::Null => wasmtime_test_util::wast::Collector::Null, 243 Collector::DeferredReferenceCounting => { 244 wasmtime_test_util::wast::Collector::DeferredReferenceCounting 245 } 246 }, 247 pooling: matches!( 248 self.wasmtime.strategy, 249 InstanceAllocationStrategy::Pooling(_) 250 ), 251 compiler: match self.wasmtime.compiler_strategy { 252 CompilerStrategy::CraneliftNative => { 253 wasmtime_test_util::wast::Compiler::CraneliftNative 254 } 255 CompilerStrategy::CraneliftPulley => { 256 wasmtime_test_util::wast::Compiler::CraneliftPulley 257 } 258 CompilerStrategy::Winch => wasmtime_test_util::wast::Compiler::Winch, 259 }, 260 } 261 } 262 263 /// Converts this to a `wasmtime::Config` object 264 pub fn to_wasmtime(&self) -> wasmtime::Config { 265 crate::init_fuzzing(); 266 267 let mut cfg = wasmtime_cli_flags::CommonOptions::default(); 268 cfg.codegen.native_unwind_info = 269 Some(cfg!(target_os = "windows") || self.wasmtime.native_unwind_info); 270 cfg.codegen.parallel_compilation = Some(false); 271 cfg.debug.address_map = Some(self.wasmtime.generate_address_map); 272 cfg.opts.opt_level = Some(self.wasmtime.opt_level.to_wasmtime()); 273 cfg.opts.regalloc_algorithm = Some(self.wasmtime.regalloc_algorithm.to_wasmtime()); 274 cfg.opts.signals_based_traps = Some(self.wasmtime.signals_based_traps); 275 cfg.opts.memory_guaranteed_dense_image_size = Some(std::cmp::min( 276 // Clamp this at 16MiB so we don't get huge in-memory 277 // images during fuzzing. 278 16 << 20, 279 self.wasmtime.memory_guaranteed_dense_image_size, 280 )); 281 cfg.wasm.async_stack_zeroing = Some(self.wasmtime.async_stack_zeroing); 282 cfg.wasm.bulk_memory = Some(true); 283 cfg.wasm.component_model_async = Some(self.module_config.component_model_async); 284 cfg.wasm.component_model_async_builtins = 285 Some(self.module_config.component_model_async_builtins); 286 cfg.wasm.component_model_async_stackful = 287 Some(self.module_config.component_model_async_stackful); 288 cfg.wasm.custom_page_sizes = Some(self.module_config.config.custom_page_sizes_enabled); 289 cfg.wasm.epoch_interruption = Some(self.wasmtime.epoch_interruption); 290 cfg.wasm.extended_const = Some(self.module_config.config.extended_const_enabled); 291 cfg.wasm.fuel = self.wasmtime.consume_fuel.then(|| u64::MAX); 292 cfg.wasm.function_references = Some(self.module_config.function_references_enabled); 293 cfg.wasm.gc = Some(self.module_config.config.gc_enabled); 294 cfg.wasm.memory64 = Some(self.module_config.config.memory64_enabled); 295 cfg.wasm.multi_memory = Some(self.module_config.config.max_memories > 1); 296 cfg.wasm.multi_value = Some(self.module_config.config.multi_value_enabled); 297 cfg.wasm.nan_canonicalization = Some(self.wasmtime.canonicalize_nans); 298 cfg.wasm.reference_types = Some(self.module_config.config.reference_types_enabled); 299 cfg.wasm.simd = Some(self.module_config.config.simd_enabled); 300 cfg.wasm.tail_call = Some(self.module_config.config.tail_call_enabled); 301 cfg.wasm.threads = Some(self.module_config.config.threads_enabled); 302 cfg.wasm.shared_everything_threads = 303 Some(self.module_config.config.shared_everything_threads_enabled); 304 cfg.wasm.wide_arithmetic = Some(self.module_config.config.wide_arithmetic_enabled); 305 cfg.wasm.exceptions = Some(self.module_config.config.exceptions_enabled); 306 cfg.wasm.legacy_exceptions = Some(self.module_config.legacy_exceptions); 307 if !self.module_config.config.simd_enabled { 308 cfg.wasm.relaxed_simd = Some(false); 309 } 310 cfg.codegen.collector = Some(self.wasmtime.collector.to_wasmtime()); 311 312 let compiler_strategy = &self.wasmtime.compiler_strategy; 313 let cranelift_strategy = match compiler_strategy { 314 CompilerStrategy::CraneliftNative | CompilerStrategy::CraneliftPulley => true, 315 CompilerStrategy::Winch => false, 316 }; 317 self.wasmtime.compiler_strategy.configure(&mut cfg); 318 319 self.wasmtime.codegen.configure(&mut cfg); 320 321 // Determine whether we will actually enable PCC -- this is 322 // disabled if the module requires memory64, which is not yet 323 // compatible (due to the need for dynamic checks). 324 let pcc = cfg!(feature = "fuzz-pcc") 325 && self.wasmtime.pcc 326 && !self.module_config.config.memory64_enabled; 327 328 // Only set cranelift specific flags when the Cranelift strategy is 329 // chosen. 330 if cranelift_strategy { 331 // If the wasm-smith-generated module use nan canonicalization then we 332 // don't need to enable it, but if it doesn't enable it already then we 333 // enable this codegen option. 334 cfg.wasm.nan_canonicalization = Some(!self.module_config.config.canonicalize_nans); 335 336 // Enabling the verifier will at-least-double compilation time, which 337 // with a 20-30x slowdown in fuzzing can cause issues related to 338 // timeouts. If generated modules can have more than a small handful of 339 // functions then disable the verifier when fuzzing to try to lessen the 340 // impact of timeouts. 341 if self.module_config.config.max_funcs > 10 { 342 cfg.codegen.cranelift_debug_verifier = Some(false); 343 } 344 345 if self.wasmtime.force_jump_veneers { 346 cfg.codegen.cranelift.push(( 347 "wasmtime_linkopt_force_jump_veneer".to_string(), 348 Some("true".to_string()), 349 )); 350 } 351 352 if let Some(pad) = self.wasmtime.padding_between_functions { 353 cfg.codegen.cranelift.push(( 354 "wasmtime_linkopt_padding_between_functions".to_string(), 355 Some(pad.to_string()), 356 )); 357 } 358 359 cfg.codegen.pcc = Some(pcc); 360 361 // Eager init is currently only supported on Cranelift, not Winch. 362 cfg.opts.table_lazy_init = Some(self.wasmtime.table_lazy_init); 363 } 364 365 self.wasmtime.strategy.configure(&mut cfg); 366 367 // Vary the memory configuration, but only if threads are not enabled. 368 // When the threads proposal is enabled we might generate shared memory, 369 // which is less amenable to different memory configurations: 370 // - shared memories are required to be "static" so fuzzing the various 371 // memory configurations will mostly result in uninteresting errors. 372 // The interesting part about shared memories is the runtime so we 373 // don't fuzz non-default settings. 374 // - shared memories are required to be aligned which means that the 375 // `CustomUnaligned` variant isn't actually safe to use with a shared 376 // memory. 377 let host_memory = if !self.module_config.config.threads_enabled { 378 // If PCC is enabled, force other options to be compatible: PCC is currently only 379 // supported when bounds checks are elided. 380 let memory_config = if pcc { 381 MemoryConfig::Normal(NormalMemoryConfig { 382 memory_reservation: Some(4 << 30), // 4 GiB 383 memory_guard_size: Some(2 << 30), // 2 GiB 384 memory_reservation_for_growth: Some(0), 385 guard_before_linear_memory: false, 386 memory_init_cow: true, 387 // Doesn't matter, only using virtual memory. 388 cranelift_enable_heap_access_spectre_mitigations: None, 389 }) 390 } else { 391 self.wasmtime.memory_config.clone() 392 }; 393 394 match &memory_config { 395 MemoryConfig::Normal(memory_config) => { 396 memory_config.configure(&mut cfg); 397 None 398 } 399 MemoryConfig::CustomUnaligned => { 400 cfg.opts.memory_reservation = Some(0); 401 cfg.opts.memory_guard_size = Some(0); 402 cfg.opts.memory_reservation_for_growth = Some(0); 403 cfg.opts.guard_before_linear_memory = Some(false); 404 cfg.opts.memory_init_cow = Some(false); 405 log::debug!("a custom unaligned host memory will be in use"); 406 Some(Arc::new(UnalignedMemoryCreator)) 407 } 408 } 409 } else { 410 None 411 }; 412 413 // If malloc-based memory is going to be used, which requires these four 414 // options set to specific values (and Pulley auto-sets two of them) 415 // then be sure to cap `memory_reservation_for_growth` at a smaller 416 // value than the default. For malloc-based memory reservation beyond 417 // the end of memory isn't captured by `StoreLimiter` so we need to be 418 // sure it's small enough to not blow OOM limits while fuzzing. 419 if ((cfg.opts.signals_based_traps == Some(true) && cfg.opts.memory_guard_size == Some(0)) 420 || self.wasmtime.compiler_strategy == CompilerStrategy::CraneliftPulley) 421 && cfg.opts.memory_reservation == Some(0) 422 && cfg.opts.memory_init_cow == Some(false) 423 { 424 let growth = &mut cfg.opts.memory_reservation_for_growth; 425 let max = 1 << 20; 426 *growth = match *growth { 427 Some(n) => Some(n.min(max)), 428 None => Some(max), 429 }; 430 } 431 432 log::debug!("creating wasmtime config with CLI options:\n{cfg}"); 433 let mut cfg = cfg.config(None).expect("failed to create wasmtime::Config"); 434 435 if let Some(host_memory) = host_memory { 436 cfg.with_host_memory(host_memory); 437 } 438 439 if self.wasmtime.async_config != AsyncConfig::Disabled { 440 log::debug!("async config in use {:?}", self.wasmtime.async_config); 441 self.wasmtime.async_config.configure(&mut cfg); 442 } 443 444 return cfg; 445 } 446 447 /// Convenience function for generating a `Store<T>` using this 448 /// configuration. 449 pub fn to_store(&self) -> Store<StoreLimits> { 450 let engine = Engine::new(&self.to_wasmtime()).unwrap(); 451 let mut store = Store::new(&engine, StoreLimits::new()); 452 self.configure_store(&mut store); 453 store 454 } 455 456 /// Configures a store based on this configuration. 457 pub fn configure_store(&self, store: &mut Store<StoreLimits>) { 458 store.limiter(|s| s as &mut dyn wasmtime::ResourceLimiter); 459 460 // Configure the store to never abort by default, that is it'll have 461 // max fuel or otherwise trap on an epoch change but the epoch won't 462 // ever change. 463 // 464 // Afterwards though see what `AsyncConfig` is being used an further 465 // refine the store's configuration based on that. 466 if self.wasmtime.consume_fuel { 467 store.set_fuel(u64::MAX).unwrap(); 468 } 469 if self.wasmtime.epoch_interruption { 470 store.epoch_deadline_trap(); 471 store.set_epoch_deadline(1); 472 } 473 match self.wasmtime.async_config { 474 AsyncConfig::Disabled => {} 475 AsyncConfig::YieldWithFuel(amt) => { 476 assert!(self.wasmtime.consume_fuel); 477 store.fuel_async_yield_interval(Some(amt)).unwrap(); 478 } 479 AsyncConfig::YieldWithEpochs { ticks, .. } => { 480 assert!(self.wasmtime.epoch_interruption); 481 store.set_epoch_deadline(ticks); 482 store.epoch_deadline_async_yield_and_update(ticks); 483 } 484 } 485 } 486 487 /// Generates an arbitrary method of timing out an instance, ensuring that 488 /// this configuration supports the returned timeout. 489 pub fn generate_timeout(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<Timeout> { 490 let time_duration = Duration::from_millis(100); 491 let timeout = u 492 .choose(&[Timeout::Fuel(100_000), Timeout::Epoch(time_duration)])? 493 .clone(); 494 match &timeout { 495 Timeout::Fuel(..) => { 496 self.wasmtime.consume_fuel = true; 497 } 498 Timeout::Epoch(..) => { 499 self.wasmtime.epoch_interruption = true; 500 } 501 Timeout::None => unreachable!("Not an option given to choose()"), 502 } 503 Ok(timeout) 504 } 505 506 /// Compiles the `wasm` within the `engine` provided. 507 /// 508 /// This notably will use `Module::{serialize,deserialize_file}` to 509 /// round-trip if configured in the fuzzer. 510 pub fn compile(&self, engine: &Engine, wasm: &[u8]) -> Result<Module> { 511 // Propagate this error in case the caller wants to handle 512 // valid-vs-invalid wasm. 513 let module = Module::new(engine, wasm)?; 514 if !self.wasmtime.use_precompiled_cwasm { 515 return Ok(module); 516 } 517 518 // Don't propagate these errors to prevent them from accidentally being 519 // interpreted as invalid wasm, these should never fail on a 520 // well-behaved host system. 521 let dir = tempfile::TempDir::new().unwrap(); 522 let file = dir.path().join("module.wasm"); 523 std::fs::write(&file, module.serialize().unwrap()).unwrap(); 524 unsafe { Ok(Module::deserialize_file(engine, &file).unwrap()) } 525 } 526 527 /// Updates this configuration to forcibly enable async support. Only useful 528 /// in fuzzers which do async calls. 529 pub fn enable_async(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<()> { 530 if self.wasmtime.consume_fuel || u.arbitrary()? { 531 self.wasmtime.async_config = 532 AsyncConfig::YieldWithFuel(u.int_in_range(1000..=100_000)?); 533 self.wasmtime.consume_fuel = true; 534 } else { 535 self.wasmtime.async_config = AsyncConfig::YieldWithEpochs { 536 dur: Duration::from_millis(u.int_in_range(1..=10)?), 537 ticks: u.int_in_range(1..=10)?, 538 }; 539 self.wasmtime.epoch_interruption = true; 540 } 541 Ok(()) 542 } 543 } 544 545 impl<'a> Arbitrary<'a> for Config { 546 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 547 let mut config = Self { 548 wasmtime: u.arbitrary()?, 549 module_config: u.arbitrary()?, 550 }; 551 552 config 553 .wasmtime 554 .update_module_config(&mut config.module_config, u)?; 555 556 Ok(config) 557 } 558 } 559 560 /// Configuration related to `wasmtime::Config` and the various settings which 561 /// can be tweaked from within. 562 #[derive(Arbitrary, Clone, Debug, Eq, Hash, PartialEq)] 563 pub struct WasmtimeConfig { 564 opt_level: OptLevel, 565 regalloc_algorithm: RegallocAlgorithm, 566 debug_info: bool, 567 canonicalize_nans: bool, 568 interruptable: bool, 569 pub(crate) consume_fuel: bool, 570 pub(crate) epoch_interruption: bool, 571 /// The Wasmtime memory configuration to use. 572 pub memory_config: MemoryConfig, 573 force_jump_veneers: bool, 574 memory_init_cow: bool, 575 memory_guaranteed_dense_image_size: u64, 576 use_precompiled_cwasm: bool, 577 async_stack_zeroing: bool, 578 /// Configuration for the instance allocation strategy to use. 579 pub strategy: InstanceAllocationStrategy, 580 codegen: CodegenSettings, 581 padding_between_functions: Option<u16>, 582 generate_address_map: bool, 583 native_unwind_info: bool, 584 /// Configuration for the compiler to use. 585 pub compiler_strategy: CompilerStrategy, 586 collector: Collector, 587 table_lazy_init: bool, 588 589 /// Whether or not fuzzing should enable PCC. 590 pcc: bool, 591 592 /// Configuration for whether wasm is invoked in an async fashion and how 593 /// it's cooperatively time-sliced. 594 pub async_config: AsyncConfig, 595 596 /// Whether or not host signal handlers are enabled for this configuration, 597 /// aka whether signal handlers are supported. 598 signals_based_traps: bool, 599 } 600 601 impl WasmtimeConfig { 602 /// Force `self` to be a configuration compatible with `other`. This is 603 /// useful for differential execution to avoid unhelpful fuzz crashes when 604 /// one engine has a feature enabled and the other does not. 605 pub fn make_compatible_with(&mut self, other: &Self) { 606 // Use the same allocation strategy between the two configs. 607 // 608 // Ideally this wouldn't be necessary, but, during differential 609 // evaluation, if the `lhs` is using ondemand and the `rhs` is using the 610 // pooling allocator (or vice versa), then the module may have been 611 // generated in such a way that is incompatible with the other 612 // allocation strategy. 613 // 614 // We can remove this in the future when it's possible to access the 615 // fields of `wasm_smith::Module` to constrain the pooling allocator 616 // based on what was actually generated. 617 self.strategy = other.strategy.clone(); 618 if let InstanceAllocationStrategy::Pooling { .. } = &other.strategy { 619 // Also use the same memory configuration when using the pooling 620 // allocator. 621 self.memory_config = other.memory_config.clone(); 622 } 623 624 self.make_internally_consistent(); 625 } 626 627 /// Updates `config` to be compatible with `self` and the other way around 628 /// too. 629 pub fn update_module_config( 630 &mut self, 631 config: &mut ModuleConfig, 632 u: &mut Unstructured<'_>, 633 ) -> arbitrary::Result<()> { 634 match self.compiler_strategy { 635 CompilerStrategy::CraneliftNative => {} 636 637 CompilerStrategy::Winch => { 638 // Winch is not complete on non-x64 targets, so just abandon this test 639 // case. We don't want to force Cranelift because we change what module 640 // config features are enabled based on the compiler strategy, and we 641 // don't want to make the same fuzz input DNA generate different test 642 // cases on different targets. 643 if cfg!(not(target_arch = "x86_64")) { 644 log::warn!( 645 "want to compile with Winch but host architecture does not support it" 646 ); 647 return Err(arbitrary::Error::IncorrectFormat); 648 } 649 650 // Winch doesn't support the same set of wasm proposal as Cranelift 651 // at this time, so if winch is selected be sure to disable wasm 652 // proposals in `Config` to ensure that Winch can compile the 653 // module that wasm-smith generates. 654 config.config.relaxed_simd_enabled = false; 655 config.config.gc_enabled = false; 656 config.config.tail_call_enabled = false; 657 config.config.reference_types_enabled = false; 658 config.function_references_enabled = false; 659 660 // Winch's SIMD implementations require AVX and AVX2. 661 if self 662 .codegen_flag("has_avx") 663 .is_some_and(|value| value == "false") 664 || self 665 .codegen_flag("has_avx2") 666 .is_some_and(|value| value == "false") 667 { 668 config.config.simd_enabled = false; 669 } 670 671 // Tuning the following engine options is currently not supported 672 // by Winch. 673 self.signals_based_traps = true; 674 self.table_lazy_init = true; 675 self.debug_info = false; 676 } 677 678 CompilerStrategy::CraneliftPulley => { 679 config.config.threads_enabled = false; 680 } 681 } 682 683 // Forcibly don't use the `CustomUnaligned` memory configuration when 684 // wasm threads are enabled or when the pooling allocator is used. For 685 // the pooling allocator it doesn't use custom memory creators anyway 686 // and for wasm threads that will require some refactoring of the 687 // `LinearMemory` trait to bubble up the request that the linear memory 688 // not move. Otherwise that just generates a panic right now. 689 if config.config.threads_enabled 690 || matches!(self.strategy, InstanceAllocationStrategy::Pooling(_)) 691 { 692 self.avoid_custom_unaligned_memory(u)?; 693 } 694 695 // If using the pooling allocator, constrain the memory and module configurations 696 // to the module limits. 697 if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.strategy { 698 // If the pooling allocator is used, do not allow shared memory to 699 // be created. FIXME: see 700 // https://github.com/bytecodealliance/wasmtime/issues/4244. 701 config.config.threads_enabled = false; 702 703 // Ensure the pooling allocator can support the maximal size of 704 // memory, picking the smaller of the two to win. 705 let min_bytes = config 706 .config 707 .max_memory32_bytes 708 // memory64_bytes is a u128, but since we are taking the min 709 // we can truncate it down to a u64. 710 .min( 711 config 712 .config 713 .max_memory64_bytes 714 .try_into() 715 .unwrap_or(u64::MAX), 716 ); 717 let mut min = min_bytes.min(pooling.max_memory_size as u64); 718 if let MemoryConfig::Normal(cfg) = &self.memory_config { 719 min = min.min(cfg.memory_reservation.unwrap_or(0)); 720 } 721 pooling.max_memory_size = min as usize; 722 config.config.max_memory32_bytes = min; 723 config.config.max_memory64_bytes = min as u128; 724 725 // If traps are disallowed then memories must have at least one page 726 // of memory so if we still are only allowing 0 pages of memory then 727 // increase that to one here. 728 if config.config.disallow_traps { 729 if pooling.max_memory_size < (1 << 16) { 730 pooling.max_memory_size = 1 << 16; 731 config.config.max_memory32_bytes = 1 << 16; 732 config.config.max_memory64_bytes = 1 << 16; 733 if let MemoryConfig::Normal(cfg) = &mut self.memory_config { 734 match &mut cfg.memory_reservation { 735 Some(size) => *size = (*size).max(pooling.max_memory_size as u64), 736 size @ None => *size = Some(pooling.max_memory_size as u64), 737 } 738 } 739 } 740 // .. additionally update tables 741 if pooling.table_elements == 0 { 742 pooling.table_elements = 1; 743 } 744 } 745 746 // Don't allow too many linear memories per instance since massive 747 // virtual mappings can fail to get allocated. 748 config.config.min_memories = config.config.min_memories.min(10); 749 config.config.max_memories = config.config.max_memories.min(10); 750 751 // Force this pooling allocator to always be able to accommodate the 752 // module that may be generated. 753 pooling.total_memories = config.config.max_memories as u32; 754 pooling.total_tables = config.config.max_tables as u32; 755 } 756 757 if !self.signals_based_traps { 758 // At this time shared memories require a "static" memory 759 // configuration but when signals-based traps are disabled all 760 // memories are forced to the "dynamic" configuration. This is 761 // fixable with some more work on the bounds-checks side of things 762 // to do a full bounds check even on static memories, but that's 763 // left for a future PR. 764 config.config.threads_enabled = false; 765 766 // Spectre-based heap mitigations require signal handlers so this 767 // must always be disabled if signals-based traps are disabled. 768 if let MemoryConfig::Normal(cfg) = &mut self.memory_config { 769 cfg.cranelift_enable_heap_access_spectre_mitigations = None; 770 } 771 } 772 773 self.make_internally_consistent(); 774 775 Ok(()) 776 } 777 778 /// Returns the codegen flag value, if any, for `name`. 779 pub(crate) fn codegen_flag(&self, name: &str) -> Option<&str> { 780 self.codegen.flags().iter().find_map(|(n, value)| { 781 if n == name { 782 Some(value.as_str()) 783 } else { 784 None 785 } 786 }) 787 } 788 789 /// Helper to switch `MemoryConfig::CustomUnaligned` to 790 /// `MemoryConfig::Normal` 791 fn avoid_custom_unaligned_memory(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<()> { 792 if let MemoryConfig::CustomUnaligned = self.memory_config { 793 self.memory_config = MemoryConfig::Normal(u.arbitrary()?); 794 } 795 Ok(()) 796 } 797 798 /// Helper method to handle some dependencies between various configuration 799 /// options. This is intended to be called whenever a `Config` is created or 800 /// modified to ensure that the final result is an instantiable `Config`. 801 /// 802 /// Note that in general this probably shouldn't exist and anything here can 803 /// be considered a "TODO" to go implement more stuff in Wasmtime to accept 804 /// these sorts of configurations. For now though it's intended to reflect 805 /// the current state of the engine's development. 806 fn make_internally_consistent(&mut self) { 807 if !self.signals_based_traps { 808 if let MemoryConfig::Normal(cfg) = &mut self.memory_config { 809 // Spectre-based heap mitigations require signal handlers so 810 // this must always be disabled if signals-based traps are 811 // disabled. 812 cfg.cranelift_enable_heap_access_spectre_mitigations = None; 813 814 // With configuration settings that match the use of malloc for 815 // linear memories cap the `memory_reservation_for_growth` value 816 // to something reasonable to avoid OOM in fuzzing. 817 if !cfg.memory_init_cow 818 && cfg.memory_guard_size == Some(0) 819 && cfg.memory_reservation == Some(0) 820 { 821 let min = 10 << 20; // 10 MiB 822 if let Some(val) = &mut cfg.memory_reservation_for_growth { 823 *val = (*val).min(min); 824 } else { 825 cfg.memory_reservation_for_growth = Some(min); 826 } 827 } 828 } 829 } 830 } 831 } 832 833 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 834 enum OptLevel { 835 None, 836 Speed, 837 SpeedAndSize, 838 } 839 840 impl OptLevel { 841 fn to_wasmtime(&self) -> wasmtime::OptLevel { 842 match self { 843 OptLevel::None => wasmtime::OptLevel::None, 844 OptLevel::Speed => wasmtime::OptLevel::Speed, 845 OptLevel::SpeedAndSize => wasmtime::OptLevel::SpeedAndSize, 846 } 847 } 848 } 849 850 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 851 enum RegallocAlgorithm { 852 Backtracking, 853 SinglePass, 854 } 855 856 impl RegallocAlgorithm { 857 fn to_wasmtime(&self) -> wasmtime::RegallocAlgorithm { 858 match self { 859 RegallocAlgorithm::Backtracking => wasmtime::RegallocAlgorithm::Backtracking, 860 // Note: we have disabled `single_pass` for now because of 861 // its limitations w.r.t. exception handling 862 // (https://github.com/bytecodealliance/regalloc2/issues/217). To 863 // avoid breaking all existing fuzzbugs by changing the 864 // `arbitrary` mappings, we keep the `RegallocAlgorithm` 865 // enum as it is and remap here to `Backtracking`. 866 RegallocAlgorithm::SinglePass => wasmtime::RegallocAlgorithm::Backtracking, 867 } 868 } 869 } 870 871 #[derive(Clone, Debug, PartialEq, Eq, Hash)] 872 /// Compiler to use. 873 pub enum CompilerStrategy { 874 /// Cranelift compiler for the native architecture. 875 CraneliftNative, 876 /// Winch compiler. 877 Winch, 878 /// Cranelift compiler for the native architecture. 879 CraneliftPulley, 880 } 881 882 impl CompilerStrategy { 883 /// Configures `config` to use this compilation strategy 884 pub fn configure(&self, config: &mut wasmtime_cli_flags::CommonOptions) { 885 match self { 886 CompilerStrategy::CraneliftNative => { 887 config.codegen.compiler = Some(wasmtime::Strategy::Cranelift); 888 } 889 CompilerStrategy::Winch => { 890 config.codegen.compiler = Some(wasmtime::Strategy::Winch); 891 } 892 CompilerStrategy::CraneliftPulley => { 893 config.codegen.compiler = Some(wasmtime::Strategy::Cranelift); 894 config.target = Some("pulley64".to_string()); 895 } 896 } 897 } 898 } 899 900 impl Arbitrary<'_> for CompilerStrategy { 901 fn arbitrary(u: &mut Unstructured<'_>) -> arbitrary::Result<Self> { 902 // Favor fuzzing native cranelift, but if allowed also enable 903 // winch/pulley. 904 match u.int_in_range(0..=19)? { 905 1 => Ok(Self::CraneliftPulley), 906 2 => Ok(Self::Winch), 907 _ => Ok(Self::CraneliftNative), 908 } 909 } 910 } 911 912 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 913 pub enum Collector { 914 DeferredReferenceCounting, 915 Null, 916 } 917 918 impl Collector { 919 fn to_wasmtime(&self) -> wasmtime::Collector { 920 match self { 921 Collector::DeferredReferenceCounting => wasmtime::Collector::DeferredReferenceCounting, 922 Collector::Null => wasmtime::Collector::Null, 923 } 924 } 925 } 926