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_wast_util::{limits, WastConfig, WastTest}; 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 104 /// Uses this configuration and the supplied source of data to generate 105 /// a wasm module. 106 /// 107 /// If a `default_fuel` is provided, the resulting module will be configured 108 /// to ensure termination; as doing so will add an additional global to the module, 109 /// the pooling allocator, if configured, will also have its globals limit updated. 110 pub fn generate( 111 &self, 112 input: &mut Unstructured<'_>, 113 default_fuel: Option<u32>, 114 ) -> arbitrary::Result<wasm_smith::Module> { 115 self.module_config.generate(input, default_fuel) 116 } 117 118 /// Updates this configuration to be able to run the `test` specified. 119 /// 120 /// This primarily updates `self.module_config` to ensure that it enables 121 /// all features and proposals necessary to execute the `test` specified. 122 /// This will additionally update limits in the pooling allocator to be able 123 /// to execute all tests. 124 pub fn make_wast_test_compliant(&mut self, test: &WastTest) -> WastConfig { 125 let wasmtime_wast_util::TestConfig { 126 memory64, 127 custom_page_sizes, 128 multi_memory, 129 threads, 130 gc, 131 function_references, 132 relaxed_simd, 133 reference_types, 134 tail_call, 135 extended_const, 136 wide_arithmetic, 137 component_model_more_flags, 138 simd, 139 140 hogs_memory: _, 141 nan_canonicalization: _, 142 gc_types: _, 143 } = test.config; 144 145 // Enable/disable some proposals that aren't configurable in wasm-smith 146 // but are configurable in Wasmtime. 147 self.module_config.function_references_enabled = 148 function_references.or(gc).unwrap_or(false); 149 self.module_config.component_model_more_flags = component_model_more_flags.unwrap_or(false); 150 151 // Enable/disable proposals that wasm-smith has knobs for which will be 152 // read when creating `wasmtime::Config`. 153 let config = &mut self.module_config.config; 154 config.bulk_memory_enabled = true; 155 config.multi_value_enabled = true; 156 config.wide_arithmetic_enabled = wide_arithmetic.unwrap_or(false); 157 config.memory64_enabled = memory64.unwrap_or(false); 158 config.relaxed_simd_enabled = relaxed_simd.unwrap_or(false); 159 config.simd_enabled = config.relaxed_simd_enabled || simd.unwrap_or(false); 160 config.tail_call_enabled = tail_call.unwrap_or(false); 161 config.custom_page_sizes_enabled = custom_page_sizes.unwrap_or(false); 162 config.threads_enabled = threads.unwrap_or(false); 163 config.gc_enabled = gc.unwrap_or(false); 164 config.reference_types_enabled = config.gc_enabled 165 || self.module_config.function_references_enabled 166 || reference_types.unwrap_or(false); 167 config.extended_const_enabled = extended_const.unwrap_or(false); 168 if multi_memory.unwrap_or(false) { 169 config.max_memories = limits::MEMORIES_PER_MODULE as usize; 170 } else { 171 config.max_memories = 1; 172 } 173 174 match &mut self.wasmtime.memory_config { 175 MemoryConfig::Normal(config) => { 176 if let Some(n) = &mut config.memory_reservation { 177 *n = (*n).max(limits::MEMORY_SIZE as u64); 178 } 179 } 180 MemoryConfig::CustomUnaligned => {} 181 } 182 183 // FIXME: it might be more ideal to avoid the need for this entirely 184 // and to just let the test fail. If a test fails due to a pooling 185 // allocator resource limit being met we could ideally detect that and 186 // let the fuzz test case pass. That would avoid the need to hardcode 187 // so much here and in theory wouldn't reduce the usefulness of fuzzers 188 // all that much. At this time though we can't easily test this configuration. 189 if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.wasmtime.strategy { 190 // Clamp protection keys between 1 & 2 to reduce the number of 191 // slots and then multiply the total memories by the number of keys 192 // we have since a single store has access to only one key. 193 pooling.max_memory_protection_keys = pooling.max_memory_protection_keys.max(1).min(2); 194 pooling.total_memories = pooling 195 .total_memories 196 .max(limits::MEMORIES * (pooling.max_memory_protection_keys as u32)); 197 198 // For other limits make sure they meet the minimum threshold 199 // required for our wast tests. 200 pooling.total_component_instances = pooling 201 .total_component_instances 202 .max(limits::COMPONENT_INSTANCES); 203 pooling.total_tables = pooling.total_tables.max(limits::TABLES); 204 pooling.max_tables_per_module = 205 pooling.max_tables_per_module.max(limits::TABLES_PER_MODULE); 206 pooling.max_memories_per_module = pooling 207 .max_memories_per_module 208 .max(limits::MEMORIES_PER_MODULE); 209 pooling.max_memories_per_component = pooling 210 .max_memories_per_component 211 .max(limits::MEMORIES_PER_MODULE); 212 pooling.total_core_instances = pooling.total_core_instances.max(limits::CORE_INSTANCES); 213 pooling.max_memory_size = pooling.max_memory_size.max(limits::MEMORY_SIZE); 214 pooling.table_elements = pooling.table_elements.max(limits::TABLE_ELEMENTS); 215 pooling.core_instance_size = pooling.core_instance_size.max(limits::CORE_INSTANCE_SIZE); 216 pooling.component_instance_size = pooling 217 .component_instance_size 218 .max(limits::CORE_INSTANCE_SIZE); 219 } 220 221 // Return the test configuration that this fuzz configuration represents 222 // which is used afterwards to test if the `test` here is expected to 223 // fail or not. 224 WastConfig { 225 collector: match self.wasmtime.collector { 226 Collector::Null => wasmtime_wast_util::Collector::Null, 227 Collector::DeferredReferenceCounting => { 228 wasmtime_wast_util::Collector::DeferredReferenceCounting 229 } 230 }, 231 pooling: matches!( 232 self.wasmtime.strategy, 233 InstanceAllocationStrategy::Pooling(_) 234 ), 235 compiler: match self.wasmtime.compiler_strategy { 236 CompilerStrategy::Cranelift => wasmtime_wast_util::Compiler::Cranelift, 237 CompilerStrategy::Winch => wasmtime_wast_util::Compiler::Winch, 238 }, 239 } 240 } 241 242 /// Converts this to a `wasmtime::Config` object 243 pub fn to_wasmtime(&self) -> wasmtime::Config { 244 crate::init_fuzzing(); 245 log::debug!("creating wasmtime config with {:#?}", self.wasmtime); 246 247 let mut cfg = wasmtime::Config::new(); 248 cfg.wasm_bulk_memory(true) 249 .wasm_reference_types(self.module_config.config.reference_types_enabled) 250 .wasm_multi_value(self.module_config.config.multi_value_enabled) 251 .wasm_multi_memory(self.module_config.config.max_memories > 1) 252 .wasm_simd(self.module_config.config.simd_enabled) 253 .wasm_memory64(self.module_config.config.memory64_enabled) 254 .wasm_tail_call(self.module_config.config.tail_call_enabled) 255 .wasm_custom_page_sizes(self.module_config.config.custom_page_sizes_enabled) 256 .wasm_threads(self.module_config.config.threads_enabled) 257 .wasm_function_references(self.module_config.function_references_enabled) 258 .wasm_gc(self.module_config.config.gc_enabled) 259 .wasm_custom_page_sizes(self.module_config.config.custom_page_sizes_enabled) 260 .wasm_wide_arithmetic(self.module_config.config.wide_arithmetic_enabled) 261 .wasm_extended_const(self.module_config.config.extended_const_enabled) 262 .wasm_component_model_more_flags(self.module_config.component_model_more_flags) 263 .native_unwind_info(cfg!(target_os = "windows") || self.wasmtime.native_unwind_info) 264 .cranelift_nan_canonicalization(self.wasmtime.canonicalize_nans) 265 .cranelift_opt_level(self.wasmtime.opt_level.to_wasmtime()) 266 .cranelift_regalloc_algorithm(self.wasmtime.regalloc_algorithm.to_wasmtime()) 267 .consume_fuel(self.wasmtime.consume_fuel) 268 .epoch_interruption(self.wasmtime.epoch_interruption) 269 .memory_guaranteed_dense_image_size(std::cmp::min( 270 // Clamp this at 16MiB so we don't get huge in-memory 271 // images during fuzzing. 272 16 << 20, 273 self.wasmtime.memory_guaranteed_dense_image_size, 274 )) 275 .allocation_strategy(self.wasmtime.strategy.to_wasmtime()) 276 .generate_address_map(self.wasmtime.generate_address_map) 277 .signals_based_traps(self.wasmtime.signals_based_traps); 278 279 if !self.module_config.config.simd_enabled { 280 cfg.wasm_relaxed_simd(false); 281 } 282 283 let compiler_strategy = &self.wasmtime.compiler_strategy; 284 let cranelift_strategy = *compiler_strategy == CompilerStrategy::Cranelift; 285 cfg.strategy(self.wasmtime.compiler_strategy.to_wasmtime()); 286 cfg.collector(self.wasmtime.collector.to_wasmtime()); 287 288 self.wasmtime.codegen.configure(&mut cfg); 289 290 // Determine whether we will actually enable PCC -- this is 291 // disabled if the module requires memory64, which is not yet 292 // compatible (due to the need for dynamic checks). 293 let pcc = cfg!(feature = "fuzz-pcc") 294 && self.wasmtime.pcc 295 && !self.module_config.config.memory64_enabled; 296 297 // Only set cranelift specific flags when the Cranelift strategy is 298 // chosen. 299 if cranelift_strategy { 300 // If the wasm-smith-generated module use nan canonicalization then we 301 // don't need to enable it, but if it doesn't enable it already then we 302 // enable this codegen option. 303 cfg.cranelift_nan_canonicalization(!self.module_config.config.canonicalize_nans); 304 305 // Enabling the verifier will at-least-double compilation time, which 306 // with a 20-30x slowdown in fuzzing can cause issues related to 307 // timeouts. If generated modules can have more than a small handful of 308 // functions then disable the verifier when fuzzing to try to lessen the 309 // impact of timeouts. 310 if self.module_config.config.max_funcs > 10 { 311 cfg.cranelift_debug_verifier(false); 312 } 313 314 if self.wasmtime.force_jump_veneers { 315 unsafe { 316 cfg.cranelift_flag_set("wasmtime_linkopt_force_jump_veneer", "true"); 317 } 318 } 319 320 if let Some(pad) = self.wasmtime.padding_between_functions { 321 unsafe { 322 cfg.cranelift_flag_set( 323 "wasmtime_linkopt_padding_between_functions", 324 &pad.to_string(), 325 ); 326 } 327 } 328 329 cfg.cranelift_pcc(pcc); 330 331 // Eager init is currently only supported on Cranelift, not Winch. 332 cfg.table_lazy_init(self.wasmtime.table_lazy_init); 333 } 334 335 self.wasmtime.async_config.configure(&mut cfg); 336 337 // Vary the memory configuration, but only if threads are not enabled. 338 // When the threads proposal is enabled we might generate shared memory, 339 // which is less amenable to different memory configurations: 340 // - shared memories are required to be "static" so fuzzing the various 341 // memory configurations will mostly result in uninteresting errors. 342 // The interesting part about shared memories is the runtime so we 343 // don't fuzz non-default settings. 344 // - shared memories are required to be aligned which means that the 345 // `CustomUnaligned` variant isn't actually safe to use with a shared 346 // memory. 347 if !self.module_config.config.threads_enabled { 348 // If PCC is enabled, force other options to be compatible: PCC is currently only 349 // supported when bounds checks are elided. 350 let memory_config = if pcc { 351 MemoryConfig::Normal(NormalMemoryConfig { 352 memory_reservation: Some(4 << 30), // 4 GiB 353 memory_guard_size: Some(2 << 30), // 2 GiB 354 memory_reservation_for_growth: Some(0), 355 guard_before_linear_memory: false, 356 memory_init_cow: true, 357 // Doesn't matter, only using virtual memory. 358 cranelift_enable_heap_access_spectre_mitigations: None, 359 }) 360 } else { 361 self.wasmtime.memory_config.clone() 362 }; 363 364 match &memory_config { 365 MemoryConfig::Normal(memory_config) => { 366 memory_config.apply_to(&mut cfg); 367 } 368 MemoryConfig::CustomUnaligned => { 369 cfg.with_host_memory(Arc::new(UnalignedMemoryCreator)) 370 .memory_reservation(0) 371 .memory_guard_size(0) 372 .memory_reservation_for_growth(0) 373 .guard_before_linear_memory(false) 374 .memory_init_cow(false); 375 } 376 } 377 } 378 379 return cfg; 380 } 381 382 /// Convenience function for generating a `Store<T>` using this 383 /// configuration. 384 pub fn to_store(&self) -> Store<StoreLimits> { 385 let engine = Engine::new(&self.to_wasmtime()).unwrap(); 386 let mut store = Store::new(&engine, StoreLimits::new()); 387 self.configure_store(&mut store); 388 store 389 } 390 391 /// Configures a store based on this configuration. 392 pub fn configure_store(&self, store: &mut Store<StoreLimits>) { 393 store.limiter(|s| s as &mut dyn wasmtime::ResourceLimiter); 394 match self.wasmtime.async_config { 395 AsyncConfig::Disabled => { 396 if self.wasmtime.consume_fuel { 397 store.set_fuel(u64::MAX).unwrap(); 398 } 399 if self.wasmtime.epoch_interruption { 400 store.epoch_deadline_trap(); 401 store.set_epoch_deadline(1); 402 } 403 } 404 AsyncConfig::YieldWithFuel(amt) => { 405 assert!(self.wasmtime.consume_fuel); 406 store.fuel_async_yield_interval(Some(amt)).unwrap(); 407 store.set_fuel(amt).unwrap(); 408 } 409 AsyncConfig::YieldWithEpochs { ticks, .. } => { 410 assert!(self.wasmtime.epoch_interruption); 411 store.set_epoch_deadline(ticks); 412 store.epoch_deadline_async_yield_and_update(ticks); 413 } 414 } 415 } 416 417 /// Generates an arbitrary method of timing out an instance, ensuring that 418 /// this configuration supports the returned timeout. 419 pub fn generate_timeout(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<Timeout> { 420 let time_duration = Duration::from_millis(100); 421 let timeout = u 422 .choose(&[Timeout::Fuel(100_000), Timeout::Epoch(time_duration)])? 423 .clone(); 424 match &timeout { 425 Timeout::Fuel(..) => { 426 self.wasmtime.consume_fuel = true; 427 } 428 Timeout::Epoch(..) => { 429 self.wasmtime.epoch_interruption = true; 430 } 431 Timeout::None => unreachable!("Not an option given to choose()"), 432 } 433 Ok(timeout) 434 } 435 436 /// Compiles the `wasm` within the `engine` provided. 437 /// 438 /// This notably will use `Module::{serialize,deserialize_file}` to 439 /// round-trip if configured in the fuzzer. 440 pub fn compile(&self, engine: &Engine, wasm: &[u8]) -> Result<Module> { 441 // Propagate this error in case the caller wants to handle 442 // valid-vs-invalid wasm. 443 let module = Module::new(engine, wasm)?; 444 if !self.wasmtime.use_precompiled_cwasm { 445 return Ok(module); 446 } 447 448 // Don't propagate these errors to prevent them from accidentally being 449 // interpreted as invalid wasm, these should never fail on a 450 // well-behaved host system. 451 let dir = tempfile::TempDir::new().unwrap(); 452 let file = dir.path().join("module.wasm"); 453 std::fs::write(&file, module.serialize().unwrap()).unwrap(); 454 unsafe { Ok(Module::deserialize_file(engine, &file).unwrap()) } 455 } 456 457 /// Updates this configuration to forcibly enable async support. Only useful 458 /// in fuzzers which do async calls. 459 pub fn enable_async(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<()> { 460 if self.wasmtime.consume_fuel || u.arbitrary()? { 461 self.wasmtime.async_config = 462 AsyncConfig::YieldWithFuel(u.int_in_range(1000..=100_000)?); 463 self.wasmtime.consume_fuel = true; 464 } else { 465 self.wasmtime.async_config = AsyncConfig::YieldWithEpochs { 466 dur: Duration::from_millis(u.int_in_range(1..=10)?), 467 ticks: u.int_in_range(1..=10)?, 468 }; 469 self.wasmtime.epoch_interruption = true; 470 } 471 Ok(()) 472 } 473 } 474 475 impl<'a> Arbitrary<'a> for Config { 476 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 477 let mut config = Self { 478 wasmtime: u.arbitrary()?, 479 module_config: u.arbitrary()?, 480 }; 481 482 config 483 .wasmtime 484 .update_module_config(&mut config.module_config.config, u)?; 485 486 Ok(config) 487 } 488 } 489 490 /// Configuration related to `wasmtime::Config` and the various settings which 491 /// can be tweaked from within. 492 #[derive(Arbitrary, Clone, Debug, Eq, Hash, PartialEq)] 493 pub struct WasmtimeConfig { 494 opt_level: OptLevel, 495 regalloc_algorithm: RegallocAlgorithm, 496 debug_info: bool, 497 canonicalize_nans: bool, 498 interruptable: bool, 499 pub(crate) consume_fuel: bool, 500 pub(crate) epoch_interruption: bool, 501 /// The Wasmtime memory configuration to use. 502 pub memory_config: MemoryConfig, 503 force_jump_veneers: bool, 504 memory_init_cow: bool, 505 memory_guaranteed_dense_image_size: u64, 506 use_precompiled_cwasm: bool, 507 /// Configuration for the instance allocation strategy to use. 508 pub strategy: InstanceAllocationStrategy, 509 codegen: CodegenSettings, 510 padding_between_functions: Option<u16>, 511 generate_address_map: bool, 512 native_unwind_info: bool, 513 /// Configuration for the compiler to use. 514 pub compiler_strategy: CompilerStrategy, 515 collector: Collector, 516 table_lazy_init: bool, 517 518 /// Whether or not fuzzing should enable PCC. 519 pcc: bool, 520 521 /// Configuration for whether wasm is invoked in an async fashion and how 522 /// it's cooperatively time-sliced. 523 pub async_config: AsyncConfig, 524 525 /// Whether or not host signal handlers are enabled for this configuration, 526 /// aka whether signal handlers are supported. 527 signals_based_traps: bool, 528 } 529 530 impl WasmtimeConfig { 531 /// Force `self` to be a configuration compatible with `other`. This is 532 /// useful for differential execution to avoid unhelpful fuzz crashes when 533 /// one engine has a feature enabled and the other does not. 534 pub fn make_compatible_with(&mut self, other: &Self) { 535 // Use the same allocation strategy between the two configs. 536 // 537 // Ideally this wouldn't be necessary, but, during differential 538 // evaluation, if the `lhs` is using ondemand and the `rhs` is using the 539 // pooling allocator (or vice versa), then the module may have been 540 // generated in such a way that is incompatible with the other 541 // allocation strategy. 542 // 543 // We can remove this in the future when it's possible to access the 544 // fields of `wasm_smith::Module` to constrain the pooling allocator 545 // based on what was actually generated. 546 self.strategy = other.strategy.clone(); 547 if let InstanceAllocationStrategy::Pooling { .. } = &other.strategy { 548 // Also use the same memory configuration when using the pooling 549 // allocator. 550 self.memory_config = other.memory_config.clone(); 551 } 552 553 self.make_internally_consistent(); 554 } 555 556 /// Updates `config` to be compatible with `self` and the other way around 557 /// too. 558 pub fn update_module_config( 559 &mut self, 560 config: &mut wasm_smith::Config, 561 u: &mut Unstructured<'_>, 562 ) -> arbitrary::Result<()> { 563 // Winch doesn't support the same set of wasm proposal as Cranelift at 564 // this time, so if winch is selected be sure to disable wasm proposals 565 // in `Config` to ensure that Winch can compile the module that 566 // wasm-smith generates. 567 if let CompilerStrategy::Winch = self.compiler_strategy { 568 config.simd_enabled = false; 569 config.relaxed_simd_enabled = false; 570 config.gc_enabled = false; 571 config.threads_enabled = false; 572 config.tail_call_enabled = false; 573 config.reference_types_enabled = false; 574 575 // Tuning the following engine options is currently not supported 576 // by Winch. 577 self.signals_based_traps = true; 578 self.table_lazy_init = true; 579 self.epoch_interruption = false; 580 self.debug_info = false; 581 } 582 583 // Forcibly don't use the `CustomUnaligned` memory configuration when 584 // wasm threads are enabled or when the pooling allocator is used. For 585 // the pooling allocator it doesn't use custom memory creators anyway 586 // and for wasm threads that will require some refactoring of the 587 // `LinearMemory` trait to bubble up the request that the linear memory 588 // not move. Otherwise that just generates a panic right now. 589 if config.threads_enabled || matches!(self.strategy, InstanceAllocationStrategy::Pooling(_)) 590 { 591 self.avoid_custom_unaligned_memory(u)?; 592 } 593 594 // If using the pooling allocator, constrain the memory and module configurations 595 // to the module limits. 596 if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.strategy { 597 // If the pooling allocator is used, do not allow shared memory to 598 // be created. FIXME: see 599 // https://github.com/bytecodealliance/wasmtime/issues/4244. 600 config.threads_enabled = false; 601 602 // Ensure the pooling allocator can support the maximal size of 603 // memory, picking the smaller of the two to win. 604 let min_bytes = config 605 .max_memory32_bytes 606 // memory64_bytes is a u128, but since we are taking the min 607 // we can truncate it down to a u64. 608 .min(config.max_memory64_bytes.try_into().unwrap_or(u64::MAX)); 609 let mut min = min_bytes.min(pooling.max_memory_size as u64); 610 if let MemoryConfig::Normal(cfg) = &self.memory_config { 611 min = min.min(cfg.memory_reservation.unwrap_or(0)); 612 } 613 pooling.max_memory_size = min as usize; 614 config.max_memory32_bytes = min; 615 config.max_memory64_bytes = min as u128; 616 617 // If traps are disallowed then memories must have at least one page 618 // of memory so if we still are only allowing 0 pages of memory then 619 // increase that to one here. 620 if config.disallow_traps { 621 if pooling.max_memory_size < (1 << 16) { 622 pooling.max_memory_size = 1 << 16; 623 config.max_memory32_bytes = 1 << 16; 624 config.max_memory64_bytes = 1 << 16; 625 if let MemoryConfig::Normal(cfg) = &mut self.memory_config { 626 match &mut cfg.memory_reservation { 627 Some(size) => *size = (*size).max(pooling.max_memory_size as u64), 628 size @ None => *size = Some(pooling.max_memory_size as u64), 629 } 630 } 631 } 632 // .. additionally update tables 633 if pooling.table_elements == 0 { 634 pooling.table_elements = 1; 635 } 636 } 637 638 // Don't allow too many linear memories per instance since massive 639 // virtual mappings can fail to get allocated. 640 config.min_memories = config.min_memories.min(10); 641 config.max_memories = config.max_memories.min(10); 642 643 // Force this pooling allocator to always be able to accommodate the 644 // module that may be generated. 645 pooling.total_memories = config.max_memories as u32; 646 pooling.total_tables = config.max_tables as u32; 647 } 648 649 if !self.signals_based_traps { 650 // At this time shared memories require a "static" memory 651 // configuration but when signals-based traps are disabled all 652 // memories are forced to the "dynamic" configuration. This is 653 // fixable with some more work on the bounds-checks side of things 654 // to do a full bounds check even on static memories, but that's 655 // left for a future PR. 656 config.threads_enabled = false; 657 658 // Spectre-based heap mitigations require signal handlers so this 659 // must always be disabled if signals-based traps are disabled. 660 if let MemoryConfig::Normal(cfg) = &mut self.memory_config { 661 cfg.cranelift_enable_heap_access_spectre_mitigations = None; 662 } 663 } 664 665 self.make_internally_consistent(); 666 667 Ok(()) 668 } 669 670 /// Helper to switch `MemoryConfig::CustomUnaligned` to 671 /// `MemoryConfig::Normal` 672 fn avoid_custom_unaligned_memory(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<()> { 673 if let MemoryConfig::CustomUnaligned = self.memory_config { 674 self.memory_config = MemoryConfig::Normal(u.arbitrary()?); 675 } 676 Ok(()) 677 } 678 679 /// Helper method to handle some dependencies between various configuration 680 /// options. This is intended to be called whenever a `Config` is created or 681 /// modified to ensure that the final result is an instantiable `Config`. 682 /// 683 /// Note that in general this probably shouldn't exist and anything here can 684 /// be considered a "TODO" to go implement more stuff in Wasmtime to accept 685 /// these sorts of configurations. For now though it's intended to reflect 686 /// the current state of the engine's development. 687 fn make_internally_consistent(&mut self) { 688 if !self.signals_based_traps { 689 // Spectre-based heap mitigations require signal handlers so this 690 // must always be disabled if signals-based traps are disabled. 691 if let MemoryConfig::Normal(cfg) = &mut self.memory_config { 692 cfg.cranelift_enable_heap_access_spectre_mitigations = None; 693 } 694 } 695 } 696 } 697 698 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 699 enum OptLevel { 700 None, 701 Speed, 702 SpeedAndSize, 703 } 704 705 impl OptLevel { 706 fn to_wasmtime(&self) -> wasmtime::OptLevel { 707 match self { 708 OptLevel::None => wasmtime::OptLevel::None, 709 OptLevel::Speed => wasmtime::OptLevel::Speed, 710 OptLevel::SpeedAndSize => wasmtime::OptLevel::SpeedAndSize, 711 } 712 } 713 } 714 715 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 716 enum RegallocAlgorithm { 717 Backtracking, 718 SinglePass, 719 } 720 721 impl RegallocAlgorithm { 722 fn to_wasmtime(&self) -> wasmtime::RegallocAlgorithm { 723 match self { 724 RegallocAlgorithm::Backtracking => wasmtime::RegallocAlgorithm::Backtracking, 725 RegallocAlgorithm::SinglePass => wasmtime::RegallocAlgorithm::SinglePass, 726 } 727 } 728 } 729 730 #[derive(Clone, Debug, PartialEq, Eq, Hash)] 731 /// Compiler to use. 732 pub enum CompilerStrategy { 733 /// Cranelift compiler. 734 Cranelift, 735 /// Winch compiler. 736 Winch, 737 } 738 739 impl CompilerStrategy { 740 fn to_wasmtime(&self) -> wasmtime::Strategy { 741 match self { 742 CompilerStrategy::Cranelift => wasmtime::Strategy::Cranelift, 743 CompilerStrategy::Winch => wasmtime::Strategy::Winch, 744 } 745 } 746 } 747 748 impl Arbitrary<'_> for CompilerStrategy { 749 fn arbitrary(_: &mut Unstructured<'_>) -> arbitrary::Result<Self> { 750 // NB: Winch isn't selected here yet as it doesn't yet implement all the 751 // compiler features for things such as trampolines, so it's only used 752 // on fuzz targets that don't need those trampolines. 753 Ok(Self::Cranelift) 754 } 755 } 756 757 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 758 pub enum Collector { 759 DeferredReferenceCounting, 760 Null, 761 } 762 763 impl Collector { 764 fn to_wasmtime(&self) -> wasmtime::Collector { 765 match self { 766 Collector::DeferredReferenceCounting => wasmtime::Collector::DeferredReferenceCounting, 767 Collector::Null => wasmtime::Collector::Null, 768 } 769 } 770 } 771