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