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