| 1 |
//! Generating arbitary core Wasm modules. |
| 2 |
|
| 3 |
mod code_builder; |
| 4 |
pub(crate) mod encode; |
| 5 |
mod terminate; |
| 6 |
|
| 7 |
use crate::{arbitrary_loop, limited_string, unique_string, Config}; |
| 8 |
use arbitrary::{Arbitrary, Result, Unstructured}; |
| 9 |
use code_builder::CodeBuilderAllocations; |
| 10 |
use flagset::{flags, FlagSet}; |
| 11 |
use std::collections::{HashMap, HashSet}; |
| 12 |
use std::fmt; |
| 13 |
use std::mem; |
| 14 |
use std::ops::Range; |
| 15 |
use std::rc::Rc; |
| 16 |
use std::str::{self, FromStr}; |
| 17 |
use wasm_encoder::{ |
| 18 |
AbstractHeapType, ArrayType, BlockType, ConstExpr, ExportKind, FieldType, HeapType, RefType, |
| 19 |
StorageType, StructType, ValType, |
| 20 |
}; |
| 21 |
pub(crate) use wasm_encoder::{GlobalType, MemoryType, TableType}; |
| 22 |
|
| 23 |
// NB: these constants are used to control the rate at which various events |
| 24 |
// occur. For more information see where these constants are used. Their values |
| 25 |
// are somewhat random in the sense that they're not scientifically determined |
| 26 |
// or anything like that, I just threw a bunch of random data at wasm-smith and |
| 27 |
// measured various rates of ooms/traps/etc and adjusted these so abnormal |
| 28 |
// events were ~1% of the time. |
| 29 |
const CHANCE_OFFSET_INBOUNDS: usize = 10; // bigger = less traps |
| 30 |
const CHANCE_SEGMENT_ON_EMPTY: usize = 10; // bigger = less traps |
| 31 |
const PCT_INBOUNDS: f64 = 0.995; // bigger = less traps |
| 32 |
|
| 33 |
type Instruction = wasm_encoder::Instruction<'static>; |
| 34 |
|
| 35 |
/// A pseudo-random WebAssembly module. |
| 36 |
/// |
| 37 |
/// Construct instances of this type (with default configuration) with [the |
| 38 |
/// `Arbitrary` |
| 39 |
/// trait](https://docs.rs/arbitrary/*/arbitrary/trait.Arbitrary.html). |
| 40 |
/// |
| 41 |
/// ## Configuring Generated Modules |
| 42 |
/// |
| 43 |
/// To configure the shape of generated module, create a |
| 44 |
/// [`Config`][crate::Config] and then call [`Module::new`][crate::Module::new] |
| 45 |
/// with it. |
| 46 |
pub struct Module { |
| 47 |
config: Config, |
| 48 |
duplicate_imports_behavior: DuplicateImportsBehavior, |
| 49 |
valtypes: Vec<ValType>, |
| 50 |
|
| 51 |
/// All types locally defined in this module (available in the type index |
| 52 |
/// space). |
| 53 |
types: Vec<SubType>, |
| 54 |
|
| 55 |
/// Non-overlapping ranges within `types` that belong to the same rec |
| 56 |
/// group. All of `types` is covered by these ranges. When GC is not |
| 57 |
/// enabled, these are all single-element ranges. |
| 58 |
rec_groups: Vec<Range<usize>>, |
| 59 |
|
| 60 |
/// A map from a super type to all of its sub types. |
| 61 |
super_to_sub_types: HashMap<u32, Vec<u32>>, |
| 62 |
|
| 63 |
/// Indices within `types` that are not final types. |
| 64 |
can_subtype: Vec<u32>, |
| 65 |
|
| 66 |
/// Whether we should encode a types section, even if `self.types` is empty. |
| 67 |
should_encode_types: bool, |
| 68 |
|
| 69 |
/// All of this module's imports. These don't have their own index space, |
| 70 |
/// but instead introduce entries to each imported entity's associated index |
| 71 |
/// space. |
| 72 |
imports: Vec<Import>, |
| 73 |
|
| 74 |
/// Whether we should encode an imports section, even if `self.imports` is |
| 75 |
/// empty. |
| 76 |
should_encode_imports: bool, |
| 77 |
|
| 78 |
/// Indices within `types` that are array types. |
| 79 |
array_types: Vec<u32>, |
| 80 |
|
| 81 |
/// Indices within `types` that are function types. |
| 82 |
func_types: Vec<u32>, |
| 83 |
|
| 84 |
/// Indices within `types that are struct types. |
| 85 |
struct_types: Vec<u32>, |
| 86 |
|
| 87 |
/// Number of imported items into this module. |
| 88 |
num_imports: usize, |
| 89 |
|
| 90 |
/// The number of tags defined in this module (not imported or |
| 91 |
/// aliased). |
| 92 |
num_defined_tags: usize, |
| 93 |
|
| 94 |
/// The number of functions defined in this module (not imported or |
| 95 |
/// aliased). |
| 96 |
num_defined_funcs: usize, |
| 97 |
|
| 98 |
/// Initialization expressions for all defined tables in this module. |
| 99 |
defined_tables: Vec<Option<ConstExpr>>, |
| 100 |
|
| 101 |
/// The number of memories defined in this module (not imported or |
| 102 |
/// aliased). |
| 103 |
num_defined_memories: usize, |
| 104 |
|
| 105 |
/// The indexes and initialization expressions of globals defined in this |
| 106 |
/// module. |
| 107 |
defined_globals: Vec<(u32, ConstExpr)>, |
| 108 |
|
| 109 |
/// All tags available to this module, sorted by their index. The list |
| 110 |
/// entry is the type of each tag. |
| 111 |
tags: Vec<TagType>, |
| 112 |
|
| 113 |
/// All functions available to this module, sorted by their index. The list |
| 114 |
/// entry points to the index in this module where the function type is |
| 115 |
/// defined (if available) and provides the type of the function. |
| 116 |
funcs: Vec<(u32, Rc<FuncType>)>, |
| 117 |
|
| 118 |
/// All tables available to this module, sorted by their index. The list |
| 119 |
/// entry is the type of each table. |
| 120 |
tables: Vec<TableType>, |
| 121 |
|
| 122 |
/// All globals available to this module, sorted by their index. The list |
| 123 |
/// entry is the type of each global. |
| 124 |
globals: Vec<GlobalType>, |
| 125 |
|
| 126 |
/// All memories available to this module, sorted by their index. The list |
| 127 |
/// entry is the type of each memory. |
| 128 |
memories: Vec<MemoryType>, |
| 129 |
|
| 130 |
exports: Vec<(String, ExportKind, u32)>, |
| 131 |
start: Option<u32>, |
| 132 |
elems: Vec<ElementSegment>, |
| 133 |
code: Vec<Code>, |
| 134 |
data: Vec<DataSegment>, |
| 135 |
|
| 136 |
/// The predicted size of the effective type of this module, based on this |
| 137 |
/// module's size of the types of imports/exports. |
| 138 |
type_size: u32, |
| 139 |
|
| 140 |
/// Names currently exported from this module. |
| 141 |
export_names: HashSet<String>, |
| 142 |
|
| 143 |
/// Reusable buffer in `self.arbitrary_const_expr` to amortize the cost of |
| 144 |
/// allocation. |
| 145 |
const_expr_choices: Vec<Box<dyn Fn(&mut Unstructured, ValType) -> Result<ConstExpr>>>, |
| 146 |
|
| 147 |
/// What the maximum type index that can be referenced is. |
| 148 |
max_type_limit: MaxTypeLimit, |
| 149 |
|
| 150 |
/// Some known-interesting values, such as powers of two, values just before |
| 151 |
/// or just after a memory size, etc... |
| 152 |
interesting_values32: Vec<u32>, |
| 153 |
interesting_values64: Vec<u64>, |
| 154 |
} |
| 155 |
|
| 156 |
impl<'a> Arbitrary<'a> for Module { |
| 157 |
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> { |
| 158 |
Module::new(Config::default(), u) |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
impl fmt::Debug for Module { |
| 163 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 164 |
f.debug_struct("Module") |
| 165 |
.field("config", &self.config) |
| 166 |
.field(&"...", &"...") |
| 167 |
.finish() |
| 168 |
} |
| 169 |
} |
| 170 |
|
| 171 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 172 |
pub(crate) enum DuplicateImportsBehavior { |
| 173 |
Allowed, |
| 174 |
Disallowed, |
| 175 |
} |
| 176 |
|
| 177 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 178 |
enum AllowEmptyRecGroup { |
| 179 |
Yes, |
| 180 |
No, |
| 181 |
} |
| 182 |
|
| 183 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 184 |
enum MaxTypeLimit { |
| 185 |
ModuleTypes, |
| 186 |
Num(u32), |
| 187 |
} |
| 188 |
|
| 189 |
impl Module { |
| 190 |
/// Returns a reference to the internal configuration. |
| 191 |
pub fn config(&self) -> &Config { |
| 192 |
&self.config |
| 193 |
} |
| 194 |
|
| 195 |
/// Creates a new `Module` with the specified `config` for |
| 196 |
/// configuration and `Unstructured` for the DNA of this module. |
| 197 |
pub fn new(config: Config, u: &mut Unstructured<'_>) -> Result<Self> { |
| 198 |
Self::new_internal(config, u, DuplicateImportsBehavior::Allowed) |
| 199 |
} |
| 200 |
|
| 201 |
pub(crate) fn new_internal( |
| 202 |
config: Config, |
| 203 |
u: &mut Unstructured<'_>, |
| 204 |
duplicate_imports_behavior: DuplicateImportsBehavior, |
| 205 |
) -> Result<Self> { |
| 206 |
let mut module = Module::empty(config, duplicate_imports_behavior); |
| 207 |
module.build(u)?; |
| 208 |
Ok(module) |
| 209 |
} |
| 210 |
|
| 211 |
fn empty(mut config: Config, duplicate_imports_behavior: DuplicateImportsBehavior) -> Self { |
| 212 |
config.sanitize(); |
| 213 |
Module { |
| 214 |
config, |
| 215 |
duplicate_imports_behavior, |
| 216 |
valtypes: Vec::new(), |
| 217 |
types: Vec::new(), |
| 218 |
rec_groups: Vec::new(), |
| 219 |
can_subtype: Vec::new(), |
| 220 |
super_to_sub_types: HashMap::new(), |
| 221 |
should_encode_types: false, |
| 222 |
imports: Vec::new(), |
| 223 |
should_encode_imports: false, |
| 224 |
array_types: Vec::new(), |
| 225 |
func_types: Vec::new(), |
| 226 |
struct_types: Vec::new(), |
| 227 |
num_imports: 0, |
| 228 |
num_defined_tags: 0, |
| 229 |
num_defined_funcs: 0, |
| 230 |
defined_tables: Vec::new(), |
| 231 |
num_defined_memories: 0, |
| 232 |
defined_globals: Vec::new(), |
| 233 |
tags: Vec::new(), |
| 234 |
funcs: Vec::new(), |
| 235 |
tables: Vec::new(), |
| 236 |
globals: Vec::new(), |
| 237 |
memories: Vec::new(), |
| 238 |
exports: Vec::new(), |
| 239 |
start: None, |
| 240 |
elems: Vec::new(), |
| 241 |
code: Vec::new(), |
| 242 |
data: Vec::new(), |
| 243 |
type_size: 0, |
| 244 |
export_names: HashSet::new(), |
| 245 |
const_expr_choices: Vec::new(), |
| 246 |
max_type_limit: MaxTypeLimit::ModuleTypes, |
| 247 |
interesting_values32: Vec::new(), |
| 248 |
interesting_values64: Vec::new(), |
| 249 |
} |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
#[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 254 |
pub(crate) struct SubType { |
| 255 |
pub(crate) is_final: bool, |
| 256 |
pub(crate) supertype: Option<u32>, |
| 257 |
pub(crate) composite_type: CompositeType, |
| 258 |
} |
| 259 |
|
| 260 |
impl SubType { |
| 261 |
fn unwrap_struct(&self) -> &StructType { |
| 262 |
self.composite_type.unwrap_struct() |
| 263 |
} |
| 264 |
|
| 265 |
fn unwrap_func(&self) -> &Rc<FuncType> { |
| 266 |
self.composite_type.unwrap_func() |
| 267 |
} |
| 268 |
|
| 269 |
fn unwrap_array(&self) -> &ArrayType { |
| 270 |
self.composite_type.unwrap_array() |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
#[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 275 |
pub(crate) struct CompositeType { |
| 276 |
pub inner: CompositeInnerType, |
| 277 |
pub shared: bool, |
| 278 |
} |
| 279 |
|
| 280 |
impl CompositeType { |
| 281 |
#[cfg(any(feature = "component-model", feature = "wasmparser"))] |
| 282 |
pub(crate) fn new_func(func: Rc<FuncType>, shared: bool) -> Self { |
| 283 |
Self { |
| 284 |
inner: CompositeInnerType::Func(func), |
| 285 |
shared, |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
fn unwrap_func(&self) -> &Rc<FuncType> { |
| 290 |
match &self.inner { |
| 291 |
CompositeInnerType::Func(f) => f, |
| 292 |
_ => panic!("not a func"), |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
fn unwrap_array(&self) -> &ArrayType { |
| 297 |
match &self.inner { |
| 298 |
CompositeInnerType::Array(a) => a, |
| 299 |
_ => panic!("not an array"), |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
fn unwrap_struct(&self) -> &StructType { |
| 304 |
match &self.inner { |
| 305 |
CompositeInnerType::Struct(s) => s, |
| 306 |
_ => panic!("not a struct"), |
| 307 |
} |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
impl From<&CompositeType> for wasm_encoder::CompositeType { |
| 312 |
fn from(ty: &CompositeType) -> Self { |
| 313 |
let inner = match &ty.inner { |
| 314 |
CompositeInnerType::Array(a) => wasm_encoder::CompositeInnerType::Array(*a), |
| 315 |
CompositeInnerType::Func(f) => wasm_encoder::CompositeInnerType::Func( |
| 316 |
wasm_encoder::FuncType::new(f.params.iter().cloned(), f.results.iter().cloned()), |
| 317 |
), |
| 318 |
CompositeInnerType::Struct(s) => wasm_encoder::CompositeInnerType::Struct(s.clone()), |
| 319 |
}; |
| 320 |
wasm_encoder::CompositeType { |
| 321 |
shared: ty.shared, |
| 322 |
inner, |
| 323 |
} |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
#[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 328 |
pub(crate) enum CompositeInnerType { |
| 329 |
Array(ArrayType), |
| 330 |
Func(Rc<FuncType>), |
| 331 |
Struct(StructType), |
| 332 |
} |
| 333 |
|
| 334 |
/// A function signature. |
| 335 |
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 336 |
pub(crate) struct FuncType { |
| 337 |
/// Types of the parameter values. |
| 338 |
pub(crate) params: Vec<ValType>, |
| 339 |
/// Types of the result values. |
| 340 |
pub(crate) results: Vec<ValType>, |
| 341 |
} |
| 342 |
|
| 343 |
/// An import of an entity provided externally or by a component. |
| 344 |
#[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 345 |
pub(crate) struct Import { |
| 346 |
/// The name of the module providing this entity. |
| 347 |
pub(crate) module: String, |
| 348 |
/// The name of the entity. |
| 349 |
pub(crate) field: String, |
| 350 |
/// The type of this entity. |
| 351 |
pub(crate) entity_type: EntityType, |
| 352 |
} |
| 353 |
|
| 354 |
/// Type of an entity. |
| 355 |
#[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 356 |
pub(crate) enum EntityType { |
| 357 |
/// A global entity. |
| 358 |
Global(GlobalType), |
| 359 |
/// A table entity. |
| 360 |
Table(TableType), |
| 361 |
/// A memory entity. |
| 362 |
Memory(MemoryType), |
| 363 |
/// A tag entity. |
| 364 |
Tag(TagType), |
| 365 |
/// A function entity. |
| 366 |
Func(u32, Rc<FuncType>), |
| 367 |
} |
| 368 |
|
| 369 |
/// Type of a tag. |
| 370 |
#[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 371 |
pub(crate) struct TagType { |
| 372 |
/// Index of the function type. |
| 373 |
func_type_idx: u32, |
| 374 |
/// Type of the function. |
| 375 |
func_type: Rc<FuncType>, |
| 376 |
} |
| 377 |
|
| 378 |
#[derive(Debug)] |
| 379 |
struct ElementSegment { |
| 380 |
kind: ElementKind, |
| 381 |
ty: RefType, |
| 382 |
items: Elements, |
| 383 |
} |
| 384 |
|
| 385 |
#[derive(Debug)] |
| 386 |
enum ElementKind { |
| 387 |
Passive, |
| 388 |
Declared, |
| 389 |
Active { |
| 390 |
table: Option<u32>, // None == table 0 implicitly |
| 391 |
offset: Offset, |
| 392 |
}, |
| 393 |
} |
| 394 |
|
| 395 |
#[derive(Debug)] |
| 396 |
enum Elements { |
| 397 |
Functions(Vec<u32>), |
| 398 |
Expressions(Vec<ConstExpr>), |
| 399 |
} |
| 400 |
|
| 401 |
#[derive(Debug)] |
| 402 |
struct Code { |
| 403 |
locals: Vec<ValType>, |
| 404 |
instructions: Instructions, |
| 405 |
} |
| 406 |
|
| 407 |
#[derive(Debug)] |
| 408 |
enum Instructions { |
| 409 |
Generated(Vec<Instruction>), |
| 410 |
Arbitrary(Vec<u8>), |
| 411 |
} |
| 412 |
|
| 413 |
#[derive(Debug)] |
| 414 |
struct DataSegment { |
| 415 |
kind: DataSegmentKind, |
| 416 |
init: Vec<u8>, |
| 417 |
} |
| 418 |
|
| 419 |
#[derive(Debug)] |
| 420 |
enum DataSegmentKind { |
| 421 |
Passive, |
| 422 |
Active { memory_index: u32, offset: Offset }, |
| 423 |
} |
| 424 |
|
| 425 |
#[derive(Debug)] |
| 426 |
pub(crate) enum Offset { |
| 427 |
Const32(i32), |
| 428 |
Const64(i64), |
| 429 |
Global(u32), |
| 430 |
} |
| 431 |
|
| 432 |
impl Module { |
| 433 |
fn build(&mut self, u: &mut Unstructured) -> Result<()> { |
| 434 |
self.valtypes = configured_valtypes(&self.config); |
| 435 |
|
| 436 |
// We attempt to figure out our available imports *before* creating the types section here, |
| 437 |
// because the types for the imports are already well-known (specified by the user) and we |
| 438 |
// must have those populated for all function/etc. imports, no matter what. |
| 439 |
// |
| 440 |
// This can affect the available capacity for types and such. |
| 441 |
if self.arbitrary_imports_from_available(u)? { |
| 442 |
self.arbitrary_types(u)?; |
| 443 |
} else { |
| 444 |
self.arbitrary_types(u)?; |
| 445 |
self.arbitrary_imports(u)?; |
| 446 |
} |
| 447 |
|
| 448 |
self.should_encode_imports = !self.imports.is_empty() || u.arbitrary()?; |
| 449 |
|
| 450 |
self.arbitrary_tags(u)?; |
| 451 |
self.arbitrary_funcs(u)?; |
| 452 |
self.arbitrary_tables(u)?; |
| 453 |
self.arbitrary_memories(u)?; |
| 454 |
self.arbitrary_globals(u)?; |
| 455 |
if !self.required_exports(u)? { |
| 456 |
self.arbitrary_exports(u)?; |
| 457 |
}; |
| 458 |
self.should_encode_types = !self.types.is_empty() || u.arbitrary()?; |
| 459 |
self.arbitrary_start(u)?; |
| 460 |
self.arbitrary_elems(u)?; |
| 461 |
self.arbitrary_data(u)?; |
| 462 |
self.arbitrary_code(u)?; |
| 463 |
Ok(()) |
| 464 |
} |
| 465 |
|
| 466 |
#[inline] |
| 467 |
fn val_type_is_sub_type(&self, a: ValType, b: ValType) -> bool { |
| 468 |
match (a, b) { |
| 469 |
(a, b) if a == b => true, |
| 470 |
(ValType::Ref(a), ValType::Ref(b)) => self.ref_type_is_sub_type(a, b), |
| 471 |
_ => false, |
| 472 |
} |
| 473 |
} |
| 474 |
|
| 475 |
/// Is `a` a subtype of `b`? |
| 476 |
fn ref_type_is_sub_type(&self, a: RefType, b: RefType) -> bool { |
| 477 |
if a == b { |
| 478 |
return true; |
| 479 |
} |
| 480 |
|
| 481 |
if a.nullable && !b.nullable { |
| 482 |
return false; |
| 483 |
} |
| 484 |
|
| 485 |
self.heap_type_is_sub_type(a.heap_type, b.heap_type) |
| 486 |
} |
| 487 |
|
| 488 |
fn heap_type_is_sub_type(&self, a: HeapType, b: HeapType) -> bool { |
| 489 |
use AbstractHeapType::*; |
| 490 |
use CompositeInnerType as CT; |
| 491 |
use HeapType as HT; |
| 492 |
match (a, b) { |
| 493 |
(a, b) if a == b => true, |
| 494 |
|
| 495 |
( |
| 496 |
HT::Abstract { |
| 497 |
shared: a_shared, |
| 498 |
ty: a_ty, |
| 499 |
}, |
| 500 |
HT::Abstract { |
| 501 |
shared: b_shared, |
| 502 |
ty: b_ty, |
| 503 |
}, |
| 504 |
) => { |
| 505 |
a_shared == b_shared |
| 506 |
&& match (a_ty, b_ty) { |
| 507 |
(Eq | I31 | Struct | Array | None, Any) => true, |
| 508 |
(I31 | Struct | Array | None, Eq) => true, |
| 509 |
(NoExtern, Extern) => true, |
| 510 |
(NoFunc, Func) => true, |
| 511 |
(None, I31 | Array | Struct) => true, |
| 512 |
(NoExn, Exn) => true, |
| 513 |
_ => false, |
| 514 |
} |
| 515 |
} |
| 516 |
|
| 517 |
(HT::Concrete(a), HT::Abstract { shared, ty }) => { |
| 518 |
let a_ty = &self.ty(a).composite_type; |
| 519 |
if a_ty.shared == shared { |
| 520 |
return false; |
| 521 |
} |
| 522 |
match ty { |
| 523 |
Eq | Any => matches!(a_ty.inner, CT::Array(_) | CT::Struct(_)), |
| 524 |
Struct => matches!(a_ty.inner, CT::Struct(_)), |
| 525 |
Array => matches!(a_ty.inner, CT::Array(_)), |
| 526 |
Func => matches!(a_ty.inner, CT::Func(_)), |
| 527 |
_ => false, |
| 528 |
} |
| 529 |
} |
| 530 |
|
| 531 |
(HT::Abstract { shared, ty }, HT::Concrete(b)) => { |
| 532 |
let b_ty = &self.ty(b).composite_type; |
| 533 |
if shared == b_ty.shared { |
| 534 |
return false; |
| 535 |
} |
| 536 |
match ty { |
| 537 |
None => matches!(b_ty.inner, CT::Array(_) | CT::Struct(_)), |
| 538 |
NoFunc => matches!(b_ty.inner, CT::Func(_)), |
| 539 |
_ => false, |
| 540 |
} |
| 541 |
} |
| 542 |
|
| 543 |
(HT::Concrete(mut a), HT::Concrete(b)) => loop { |
| 544 |
if a == b { |
| 545 |
return true; |
| 546 |
} |
| 547 |
if let Some(supertype) = self.ty(a).supertype { |
| 548 |
a = supertype; |
| 549 |
} else { |
| 550 |
return false; |
| 551 |
} |
| 552 |
}, |
| 553 |
} |
| 554 |
} |
| 555 |
|
| 556 |
fn arbitrary_types(&mut self, u: &mut Unstructured) -> Result<()> { |
| 557 |
assert!(self.config.min_types <= self.config.max_types); |
| 558 |
while self.types.len() < self.config.min_types { |
| 559 |
self.arbitrary_rec_group(u, AllowEmptyRecGroup::No)?; |
| 560 |
} |
| 561 |
while self.types.len() < self.config.max_types { |
| 562 |
let keep_going = u.arbitrary().unwrap_or(false); |
| 563 |
if !keep_going { |
| 564 |
break; |
| 565 |
} |
| 566 |
self.arbitrary_rec_group(u, AllowEmptyRecGroup::Yes)?; |
| 567 |
} |
| 568 |
Ok(()) |
| 569 |
} |
| 570 |
|
| 571 |
fn add_type(&mut self, ty: SubType) -> u32 { |
| 572 |
let index = u32::try_from(self.types.len()).unwrap(); |
| 573 |
|
| 574 |
if let Some(supertype) = ty.supertype { |
| 575 |
self.super_to_sub_types |
| 576 |
.entry(supertype) |
| 577 |
.or_default() |
| 578 |
.push(index); |
| 579 |
} |
| 580 |
|
| 581 |
let list = match &ty.composite_type.inner { |
| 582 |
CompositeInnerType::Array(_) => &mut self.array_types, |
| 583 |
CompositeInnerType::Func(_) => &mut self.func_types, |
| 584 |
CompositeInnerType::Struct(_) => &mut self.struct_types, |
| 585 |
}; |
| 586 |
list.push(index); |
| 587 |
|
| 588 |
if !ty.is_final { |
| 589 |
self.can_subtype.push(index); |
| 590 |
} |
| 591 |
|
| 592 |
self.types.push(ty); |
| 593 |
index |
| 594 |
} |
| 595 |
|
| 596 |
fn arbitrary_rec_group( |
| 597 |
&mut self, |
| 598 |
u: &mut Unstructured, |
| 599 |
kind: AllowEmptyRecGroup, |
| 600 |
) -> Result<()> { |
| 601 |
let rec_group_start = self.types.len(); |
| 602 |
|
| 603 |
assert!(matches!(self.max_type_limit, MaxTypeLimit::ModuleTypes)); |
| 604 |
|
| 605 |
if self.config.gc_enabled { |
| 606 |
// With small probability, clone an existing rec group. |
| 607 |
if self.clonable_rec_groups(kind).next().is_some() && u.ratio(1, u8::MAX)? { |
| 608 |
return self.clone_rec_group(u, kind); |
| 609 |
} |
| 610 |
|
| 611 |
// Otherwise, create a new rec group with multiple types inside. |
| 612 |
let max_rec_group_size = self.config.max_types - self.types.len(); |
| 613 |
let min_rec_group_size = match kind { |
| 614 |
AllowEmptyRecGroup::Yes => 0, |
| 615 |
AllowEmptyRecGroup::No => 1, |
| 616 |
}; |
| 617 |
let rec_group_size = u.int_in_range(min_rec_group_size..=max_rec_group_size)?; |
| 618 |
let type_ref_limit = u32::try_from(self.types.len() + rec_group_size).unwrap(); |
| 619 |
self.max_type_limit = MaxTypeLimit::Num(type_ref_limit); |
| 620 |
for _ in 0..rec_group_size { |
| 621 |
let ty = self.arbitrary_sub_type(u)?; |
| 622 |
self.add_type(ty); |
| 623 |
} |
| 624 |
} else { |
| 625 |
let type_ref_limit = u32::try_from(self.types.len()).unwrap(); |
| 626 |
self.max_type_limit = MaxTypeLimit::Num(type_ref_limit); |
| 627 |
let ty = self.arbitrary_sub_type(u)?; |
| 628 |
self.add_type(ty); |
| 629 |
} |
| 630 |
|
| 631 |
self.max_type_limit = MaxTypeLimit::ModuleTypes; |
| 632 |
|
| 633 |
self.rec_groups.push(rec_group_start..self.types.len()); |
| 634 |
Ok(()) |
| 635 |
} |
| 636 |
|
| 637 |
/// Returns an iterator of rec groups that we could currently clone while |
| 638 |
/// still staying within the max types limit. |
| 639 |
fn clonable_rec_groups( |
| 640 |
&self, |
| 641 |
kind: AllowEmptyRecGroup, |
| 642 |
) -> impl Iterator<Item = Range<usize>> + '_ { |
| 643 |
self.rec_groups |
| 644 |
.iter() |
| 645 |
.filter(move |r| { |
| 646 |
match kind { |
| 647 |
AllowEmptyRecGroup::Yes => {} |
| 648 |
AllowEmptyRecGroup::No => { |
| 649 |
if r.is_empty() { |
| 650 |
return false; |
| 651 |
} |
| 652 |
} |
| 653 |
} |
| 654 |
r.end - r.start <= self.config.max_types.saturating_sub(self.types.len()) |
| 655 |
}) |
| 656 |
.cloned() |
| 657 |
} |
| 658 |
|
| 659 |
fn clone_rec_group(&mut self, u: &mut Unstructured, kind: AllowEmptyRecGroup) -> Result<()> { |
| 660 |
// NB: this does *not* guarantee that the cloned rec group will |
| 661 |
// canonicalize the same as the original rec group and be |
| 662 |
// deduplicated. That would reqiure a second pass over the cloned types |
| 663 |
// to rewrite references within the original rec group to be references |
| 664 |
// into the new rec group. That might make sense to do one day, but for |
| 665 |
// now we don't do it. That also means that we can't mark the new types |
| 666 |
// as "subtypes" of the old types and vice versa. |
| 667 |
let candidates: Vec<_> = self.clonable_rec_groups(kind).collect(); |
| 668 |
let group = u.choose(&candidates)?.clone(); |
| 669 |
let new_rec_group_start = self.types.len(); |
| 670 |
for index in group { |
| 671 |
let orig_ty_index = u32::try_from(index).unwrap(); |
| 672 |
let ty = self.ty(orig_ty_index).clone(); |
| 673 |
self.add_type(ty); |
| 674 |
} |
| 675 |
self.rec_groups.push(new_rec_group_start..self.types.len()); |
| 676 |
Ok(()) |
| 677 |
} |
| 678 |
|
| 679 |
fn arbitrary_sub_type(&mut self, u: &mut Unstructured) -> Result<SubType> { |
| 680 |
if !self.config.gc_enabled { |
| 681 |
let composite_type = CompositeType { |
| 682 |
inner: CompositeInnerType::Func(self.arbitrary_func_type(u)?), |
| 683 |
shared: false, |
| 684 |
}; |
| 685 |
return Ok(SubType { |
| 686 |
is_final: true, |
| 687 |
supertype: None, |
| 688 |
composite_type, |
| 689 |
}); |
| 690 |
} |
| 691 |
|
| 692 |
if !self.can_subtype.is_empty() && u.ratio(1, 32_u8)? { |
| 693 |
self.arbitrary_sub_type_of_super_type(u) |
| 694 |
} else { |
| 695 |
Ok(SubType { |
| 696 |
is_final: u.arbitrary()?, |
| 697 |
supertype: None, |
| 698 |
composite_type: self.arbitrary_composite_type(u)?, |
| 699 |
}) |
| 700 |
} |
| 701 |
} |
| 702 |
|
| 703 |
fn arbitrary_sub_type_of_super_type(&mut self, u: &mut Unstructured) -> Result<SubType> { |
| 704 |
let supertype = *u.choose(&self.can_subtype)?; |
| 705 |
let mut composite_type = self.types[usize::try_from(supertype).unwrap()] |
| 706 |
.composite_type |
| 707 |
.clone(); |
| 708 |
match &mut composite_type.inner { |
| 709 |
CompositeInnerType::Array(a) => { |
| 710 |
a.0 = self.arbitrary_matching_field_type(u, a.0)?; |
| 711 |
} |
| 712 |
CompositeInnerType::Func(f) => { |
| 713 |
*f = self.arbitrary_matching_func_type(u, f)?; |
| 714 |
} |
| 715 |
CompositeInnerType::Struct(s) => { |
| 716 |
*s = self.arbitrary_matching_struct_type(u, s)?; |
| 717 |
} |
| 718 |
} |
| 719 |
Ok(SubType { |
| 720 |
is_final: u.arbitrary()?, |
| 721 |
supertype: Some(supertype), |
| 722 |
composite_type, |
| 723 |
}) |
| 724 |
} |
| 725 |
|
| 726 |
fn arbitrary_matching_struct_type( |
| 727 |
&mut self, |
| 728 |
u: &mut Unstructured, |
| 729 |
ty: &StructType, |
| 730 |
) -> Result<StructType> { |
| 731 |
let len_extra_fields = u.int_in_range(0..=5)?; |
| 732 |
let mut fields = Vec::with_capacity(ty.fields.len() + len_extra_fields); |
| 733 |
for field in ty.fields.iter() { |
| 734 |
fields.push(self.arbitrary_matching_field_type(u, *field)?); |
| 735 |
} |
| 736 |
for _ in 0..len_extra_fields { |
| 737 |
fields.push(self.arbitrary_field_type(u)?); |
| 738 |
} |
| 739 |
Ok(StructType { |
| 740 |
fields: fields.into_boxed_slice(), |
| 741 |
}) |
| 742 |
} |
| 743 |
|
| 744 |
fn arbitrary_matching_field_type( |
| 745 |
&mut self, |
| 746 |
u: &mut Unstructured, |
| 747 |
ty: FieldType, |
| 748 |
) -> Result<FieldType> { |
| 749 |
Ok(FieldType { |
| 750 |
element_type: self.arbitrary_matching_storage_type(u, ty.element_type)?, |
| 751 |
mutable: if ty.mutable { u.arbitrary()? } else { false }, |
| 752 |
}) |
| 753 |
} |
| 754 |
|
| 755 |
fn arbitrary_matching_storage_type( |
| 756 |
&mut self, |
| 757 |
u: &mut Unstructured, |
| 758 |
ty: StorageType, |
| 759 |
) -> Result<StorageType> { |
| 760 |
match ty { |
| 761 |
StorageType::I8 => Ok(StorageType::I8), |
| 762 |
StorageType::I16 => Ok(StorageType::I16), |
| 763 |
StorageType::Val(ty) => Ok(StorageType::Val(self.arbitrary_matching_val_type(u, ty)?)), |
| 764 |
} |
| 765 |
} |
| 766 |
|
| 767 |
fn arbitrary_matching_val_type( |
| 768 |
&mut self, |
| 769 |
u: &mut Unstructured, |
| 770 |
ty: ValType, |
| 771 |
) -> Result<ValType> { |
| 772 |
match ty { |
| 773 |
ValType::I32 => Ok(ValType::I32), |
| 774 |
ValType::I64 => Ok(ValType::I64), |
| 775 |
ValType::F32 => Ok(ValType::F32), |
| 776 |
ValType::F64 => Ok(ValType::F64), |
| 777 |
ValType::V128 => Ok(ValType::V128), |
| 778 |
ValType::Ref(ty) => Ok(ValType::Ref(self.arbitrary_matching_ref_type(u, ty)?)), |
| 779 |
} |
| 780 |
} |
| 781 |
|
| 782 |
fn arbitrary_matching_ref_type(&self, u: &mut Unstructured, ty: RefType) -> Result<RefType> { |
| 783 |
Ok(RefType { |
| 784 |
nullable: ty.nullable, |
| 785 |
heap_type: self.arbitrary_matching_heap_type(u, ty.heap_type)?, |
| 786 |
}) |
| 787 |
} |
| 788 |
|
| 789 |
fn arbitrary_matching_heap_type(&self, u: &mut Unstructured, ty: HeapType) -> Result<HeapType> { |
| 790 |
if !self.config.gc_enabled { |
| 791 |
return Ok(ty); |
| 792 |
} |
| 793 |
use CompositeInnerType as CT; |
| 794 |
use HeapType as HT; |
| 795 |
let mut choices = vec![ty]; |
| 796 |
match ty { |
| 797 |
HT::Abstract { shared, ty } => { |
| 798 |
use AbstractHeapType::*; |
| 799 |
let ht = |ty| HT::Abstract { shared, ty }; |
| 800 |
match ty { |
| 801 |
Any => { |
| 802 |
choices.extend([ht(Eq), ht(Struct), ht(Array), ht(I31), ht(None)]); |
| 803 |
choices.extend(self.array_types.iter().copied().map(HT::Concrete)); |
| 804 |
choices.extend(self.struct_types.iter().copied().map(HT::Concrete)); |
| 805 |
} |
| 806 |
Eq => { |
| 807 |
choices.extend([ht(Struct), ht(Array), ht(I31), ht(None)]); |
| 808 |
choices.extend(self.array_types.iter().copied().map(HT::Concrete)); |
| 809 |
choices.extend(self.struct_types.iter().copied().map(HT::Concrete)); |
| 810 |
} |
| 811 |
Struct => { |
| 812 |
choices.extend([ht(Struct), ht(None)]); |
| 813 |
choices.extend(self.struct_types.iter().copied().map(HT::Concrete)); |
| 814 |
} |
| 815 |
Array => { |
| 816 |
choices.extend([ht(Array), ht(None)]); |
| 817 |
choices.extend(self.array_types.iter().copied().map(HT::Concrete)); |
| 818 |
} |
| 819 |
I31 => { |
| 820 |
choices.push(ht(None)); |
| 821 |
} |
| 822 |
Func => { |
| 823 |
choices.extend(self.func_types.iter().copied().map(HT::Concrete)); |
| 824 |
choices.push(ht(NoFunc)); |
| 825 |
} |
| 826 |
Extern => { |
| 827 |
choices.push(ht(NoExtern)); |
| 828 |
} |
| 829 |
Exn | NoExn | None | NoExtern | NoFunc | Cont | NoCont => {} |
| 830 |
} |
| 831 |
} |
| 832 |
HT::Concrete(idx) => { |
| 833 |
if let Some(subs) = self.super_to_sub_types.get(&idx) { |
| 834 |
choices.extend(subs.iter().copied().map(HT::Concrete)); |
| 835 |
} |
| 836 |
match self |
| 837 |
.types |
| 838 |
.get(usize::try_from(idx).unwrap()) |
| 839 |
.map(|ty| (ty.composite_type.shared, &ty.composite_type.inner)) |
| 840 |
{ |
| 841 |
Some((shared, CT::Array(_) | CT::Struct(_))) => choices.push(HT::Abstract { |
| 842 |
shared, |
| 843 |
ty: AbstractHeapType::None, |
| 844 |
}), |
| 845 |
Some((shared, CT::Func(_))) => choices.push(HT::Abstract { |
| 846 |
shared, |
| 847 |
ty: AbstractHeapType::NoFunc, |
| 848 |
}), |
| 849 |
None => { |
| 850 |
// The referenced type might be part of this same rec |
| 851 |
// group we are currently generating, but not generated |
| 852 |
// yet. In this case, leave `choices` as it is, and we |
| 853 |
// will just end up choosing the original type again |
| 854 |
// down below, which is fine. |
| 855 |
} |
| 856 |
} |
| 857 |
} |
| 858 |
} |
| 859 |
Ok(*u.choose(&choices)?) |
| 860 |
} |
| 861 |
|
| 862 |
fn arbitrary_matching_func_type( |
| 863 |
&mut self, |
| 864 |
u: &mut Unstructured, |
| 865 |
ty: &FuncType, |
| 866 |
) -> Result<Rc<FuncType>> { |
| 867 |
// Note: parameters are contravariant, results are covariant. See |
| 868 |
// https://github.com/bytecodealliance/wasm-tools/blob/0616ef196a183cf137ee06b4a5993b7d590088bf/crates/wasmparser/src/readers/core/types/matches.rs#L137-L174 |
| 869 |
// for details. |
| 870 |
let mut params = Vec::with_capacity(ty.params.len()); |
| 871 |
for param in &ty.params { |
| 872 |
params.push(self.arbitrary_super_type_of_val_type(u, *param)?); |
| 873 |
} |
| 874 |
let mut results = Vec::with_capacity(ty.results.len()); |
| 875 |
for result in &ty.results { |
| 876 |
results.push(self.arbitrary_matching_val_type(u, *result)?); |
| 877 |
} |
| 878 |
Ok(Rc::new(FuncType { params, results })) |
| 879 |
} |
| 880 |
|
| 881 |
fn arbitrary_super_type_of_val_type( |
| 882 |
&mut self, |
| 883 |
u: &mut Unstructured, |
| 884 |
ty: ValType, |
| 885 |
) -> Result<ValType> { |
| 886 |
match ty { |
| 887 |
ValType::I32 => Ok(ValType::I32), |
| 888 |
ValType::I64 => Ok(ValType::I64), |
| 889 |
ValType::F32 => Ok(ValType::F32), |
| 890 |
ValType::F64 => Ok(ValType::F64), |
| 891 |
ValType::V128 => Ok(ValType::V128), |
| 892 |
ValType::Ref(ty) => Ok(ValType::Ref(self.arbitrary_super_type_of_ref_type(u, ty)?)), |
| 893 |
} |
| 894 |
} |
| 895 |
|
| 896 |
fn arbitrary_super_type_of_ref_type( |
| 897 |
&self, |
| 898 |
u: &mut Unstructured, |
| 899 |
ty: RefType, |
| 900 |
) -> Result<RefType> { |
| 901 |
Ok(RefType { |
| 902 |
// TODO: For now, only create allow nullable reference |
| 903 |
// types. Eventually we should support non-nullable reference types, |
| 904 |
// but this means that we will also need to recognize when it is |
| 905 |
// impossible to create an instance of the reference (eg `(ref |
| 906 |
// nofunc)` has no instances, and self-referential types that |
| 907 |
// contain a non-null self-reference are also impossible to create). |
| 908 |
nullable: true, |
| 909 |
heap_type: self.arbitrary_super_type_of_heap_type(u, ty.heap_type)?, |
| 910 |
}) |
| 911 |
} |
| 912 |
|
| 913 |
fn arbitrary_super_type_of_heap_type( |
| 914 |
&self, |
| 915 |
u: &mut Unstructured, |
| 916 |
ty: HeapType, |
| 917 |
) -> Result<HeapType> { |
| 918 |
if !self.config.gc_enabled { |
| 919 |
return Ok(ty); |
| 920 |
} |
| 921 |
use CompositeInnerType as CT; |
| 922 |
use HeapType as HT; |
| 923 |
let mut choices = vec![ty]; |
| 924 |
match ty { |
| 925 |
HT::Abstract { shared, ty } => { |
| 926 |
use AbstractHeapType::*; |
| 927 |
let ht = |ty| HT::Abstract { shared, ty }; |
| 928 |
match ty { |
| 929 |
None => { |
| 930 |
choices.extend([ht(Any), ht(Eq), ht(Struct), ht(Array), ht(I31)]); |
| 931 |
choices.extend(self.array_types.iter().copied().map(HT::Concrete)); |
| 932 |
choices.extend(self.struct_types.iter().copied().map(HT::Concrete)); |
| 933 |
} |
| 934 |
NoExtern => { |
| 935 |
choices.push(ht(Extern)); |
| 936 |
} |
| 937 |
NoFunc => { |
| 938 |
choices.extend(self.func_types.iter().copied().map(HT::Concrete)); |
| 939 |
choices.push(ht(Func)); |
| 940 |
} |
| 941 |
NoExn => { |
| 942 |
choices.push(ht(Exn)); |
| 943 |
} |
| 944 |
Struct | Array | I31 => { |
| 945 |
choices.extend([ht(Any), ht(Eq)]); |
| 946 |
} |
| 947 |
Eq => { |
| 948 |
choices.push(ht(Any)); |
| 949 |
} |
| 950 |
NoCont => { |
| 951 |
choices.push(ht(Cont)); |
| 952 |
} |
| 953 |
Exn | Any | Func | Extern | Cont => {} |
| 954 |
} |
| 955 |
} |
| 956 |
HT::Concrete(mut idx) => { |
| 957 |
if let Some(sub_ty) = &self.types.get(usize::try_from(idx).unwrap()) { |
| 958 |
let ht = |ty| HT::Abstract { |
| 959 |
shared: sub_ty.composite_type.shared, |
| 960 |
ty, |
| 961 |
}; |
| 962 |
match &sub_ty.composite_type.inner { |
| 963 |
CT::Array(_) => { |
| 964 |
choices.extend([ |
| 965 |
ht(AbstractHeapType::Any), |
| 966 |
ht(AbstractHeapType::Eq), |
| 967 |
ht(AbstractHeapType::Array), |
| 968 |
]); |
| 969 |
} |
| 970 |
CT::Func(_) => { |
| 971 |
choices.push(ht(AbstractHeapType::Func)); |
| 972 |
} |
| 973 |
CT::Struct(_) => { |
| 974 |
choices.extend([ |
| 975 |
ht(AbstractHeapType::Any), |
| 976 |
ht(AbstractHeapType::Eq), |
| 977 |
ht(AbstractHeapType::Struct), |
| 978 |
]); |
| 979 |
} |
| 980 |
} |
| 981 |
} else { |
| 982 |
// Same as in `arbitrary_matching_heap_type`: this was a |
| 983 |
// forward reference to a concrete type that is part of |
| 984 |
// this same rec group we are generating right now, and |
| 985 |
// therefore we haven't generated that type yet. Just |
| 986 |
// leave `choices` as it is and we will choose the |
| 987 |
// original type again down below. |
| 988 |
} |
| 989 |
while let Some(supertype) = self |
| 990 |
.types |
| 991 |
.get(usize::try_from(idx).unwrap()) |
| 992 |
.and_then(|ty| ty.supertype) |
| 993 |
{ |
| 994 |
choices.push(HT::Concrete(supertype)); |
| 995 |
idx = supertype; |
| 996 |
} |
| 997 |
} |
| 998 |
} |
| 999 |
Ok(*u.choose(&choices)?) |
| 1000 |
} |
| 1001 |
|
| 1002 |
fn arbitrary_composite_type(&mut self, u: &mut Unstructured) -> Result<CompositeType> { |
| 1003 |
use CompositeInnerType as CT; |
| 1004 |
let shared = false; // TODO: handle shared |
| 1005 |
if !self.config.gc_enabled { |
| 1006 |
return Ok(CompositeType { |
| 1007 |
shared, |
| 1008 |
inner: CT::Func(self.arbitrary_func_type(u)?), |
| 1009 |
}); |
| 1010 |
} |
| 1011 |
|
| 1012 |
match u.int_in_range(0..=2)? { |
| 1013 |
0 => Ok(CompositeType { |
| 1014 |
shared, |
| 1015 |
inner: CT::Array(ArrayType(self.arbitrary_field_type(u)?)), |
| 1016 |
}), |
| 1017 |
1 => Ok(CompositeType { |
| 1018 |
shared, |
| 1019 |
inner: CT::Func(self.arbitrary_func_type(u)?), |
| 1020 |
}), |
| 1021 |
2 => Ok(CompositeType { |
| 1022 |
shared, |
| 1023 |
inner: CT::Struct(self.arbitrary_struct_type(u)?), |
| 1024 |
}), |
| 1025 |
_ => unreachable!(), |
| 1026 |
} |
| 1027 |
} |
| 1028 |
|
| 1029 |
fn arbitrary_struct_type(&mut self, u: &mut Unstructured) -> Result<StructType> { |
| 1030 |
let len = u.int_in_range(0..=20)?; |
| 1031 |
let mut fields = Vec::with_capacity(len); |
| 1032 |
for _ in 0..len { |
| 1033 |
fields.push(self.arbitrary_field_type(u)?); |
| 1034 |
} |
| 1035 |
Ok(StructType { |
| 1036 |
fields: fields.into_boxed_slice(), |
| 1037 |
}) |
| 1038 |
} |
| 1039 |
|
| 1040 |
fn arbitrary_field_type(&mut self, u: &mut Unstructured) -> Result<FieldType> { |
| 1041 |
Ok(FieldType { |
| 1042 |
element_type: self.arbitrary_storage_type(u)?, |
| 1043 |
mutable: u.arbitrary()?, |
| 1044 |
}) |
| 1045 |
} |
| 1046 |
|
| 1047 |
fn arbitrary_storage_type(&mut self, u: &mut Unstructured) -> Result<StorageType> { |
| 1048 |
match u.int_in_range(0..=2)? { |
| 1049 |
0 => Ok(StorageType::I8), |
| 1050 |
1 => Ok(StorageType::I16), |
| 1051 |
2 => Ok(StorageType::Val(self.arbitrary_valtype(u)?)), |
| 1052 |
_ => unreachable!(), |
| 1053 |
} |
| 1054 |
} |
| 1055 |
|
| 1056 |
fn arbitrary_ref_type(&self, u: &mut Unstructured) -> Result<RefType> { |
| 1057 |
if !self.config.reference_types_enabled { |
| 1058 |
return Ok(RefType::FUNCREF); |
| 1059 |
} |
| 1060 |
Ok(RefType { |
| 1061 |
nullable: true, |
| 1062 |
heap_type: self.arbitrary_heap_type(u)?, |
| 1063 |
}) |
| 1064 |
} |
| 1065 |
|
| 1066 |
fn arbitrary_heap_type(&self, u: &mut Unstructured) -> Result<HeapType> { |
| 1067 |
assert!(self.config.reference_types_enabled); |
| 1068 |
|
| 1069 |
let concrete_type_limit = match self.max_type_limit { |
| 1070 |
MaxTypeLimit::Num(n) => n, |
| 1071 |
MaxTypeLimit::ModuleTypes => u32::try_from(self.types.len()).unwrap(), |
| 1072 |
}; |
| 1073 |
|
| 1074 |
if self.config.gc_enabled && concrete_type_limit > 0 && u.arbitrary()? { |
| 1075 |
let idx = u.int_in_range(0..=concrete_type_limit - 1)?; |
| 1076 |
return Ok(HeapType::Concrete(idx)); |
| 1077 |
} |
| 1078 |
|
| 1079 |
use AbstractHeapType::*; |
| 1080 |
let mut choices = vec![Func, Extern]; |
| 1081 |
if self.config.exceptions_enabled { |
| 1082 |
choices.push(Exn); |
| 1083 |
} |
| 1084 |
if self.config.gc_enabled { |
| 1085 |
choices.extend( |
| 1086 |
[Any, None, NoExtern, NoFunc, Eq, Struct, Array, I31] |
| 1087 |
.iter() |
| 1088 |
.copied(), |
| 1089 |
); |
| 1090 |
} |
| 1091 |
|
| 1092 |
Ok(HeapType::Abstract { |
| 1093 |
shared: false, // TODO: turn on shared attribute with shared-everything-threads. |
| 1094 |
ty: *u.choose(&choices)?, |
| 1095 |
}) |
| 1096 |
} |
| 1097 |
|
| 1098 |
fn arbitrary_func_type(&mut self, u: &mut Unstructured) -> Result<Rc<FuncType>> { |
| 1099 |
let mut params = vec![]; |
| 1100 |
let mut results = vec![]; |
| 1101 |
let max_params = 20; |
| 1102 |
arbitrary_loop(u, 0, max_params, |u| { |
| 1103 |
params.push(self.arbitrary_valtype(u)?); |
| 1104 |
Ok(true) |
| 1105 |
})?; |
| 1106 |
let max_results = if self.config.multi_value_enabled { |
| 1107 |
max_params |
| 1108 |
} else { |
| 1109 |
1 |
| 1110 |
}; |
| 1111 |
arbitrary_loop(u, 0, max_results, |u| { |
| 1112 |
results.push(self.arbitrary_valtype(u)?); |
| 1113 |
Ok(true) |
| 1114 |
})?; |
| 1115 |
Ok(Rc::new(FuncType { params, results })) |
| 1116 |
} |
| 1117 |
|
| 1118 |
fn can_add_local_or_import_tag(&self) -> bool { |
| 1119 |
self.config.exceptions_enabled |
| 1120 |
&& self.has_tag_func_types() |
| 1121 |
&& self.tags.len() < self.config.max_tags |
| 1122 |
} |
| 1123 |
|
| 1124 |
fn can_add_local_or_import_func(&self) -> bool { |
| 1125 |
!self.func_types.is_empty() && self.funcs.len() < self.config.max_funcs |
| 1126 |
} |
| 1127 |
|
| 1128 |
fn can_add_local_or_import_table(&self) -> bool { |
| 1129 |
self.tables.len() < self.config.max_tables |
| 1130 |
} |
| 1131 |
|
| 1132 |
fn can_add_local_or_import_global(&self) -> bool { |
| 1133 |
self.globals.len() < self.config.max_globals |
| 1134 |
} |
| 1135 |
|
| 1136 |
fn can_add_local_or_import_memory(&self) -> bool { |
| 1137 |
self.memories.len() < self.config.max_memories |
| 1138 |
} |
| 1139 |
|
| 1140 |
fn arbitrary_imports(&mut self, u: &mut Unstructured) -> Result<()> { |
| 1141 |
if self.config.max_type_size < self.type_size { |
| 1142 |
return Ok(()); |
| 1143 |
} |
| 1144 |
|
| 1145 |
let mut import_strings = HashSet::new(); |
| 1146 |
let mut choices: Vec<fn(&mut Unstructured, &mut Module) -> Result<EntityType>> = |
| 1147 |
Vec::with_capacity(5); |
| 1148 |
let min = self.config.min_imports.saturating_sub(self.num_imports); |
| 1149 |
let max = self.config.max_imports.saturating_sub(self.num_imports); |
| 1150 |
arbitrary_loop(u, min, max, |u| { |
| 1151 |
choices.clear(); |
| 1152 |
if self.can_add_local_or_import_tag() { |
| 1153 |
choices.push(|u, m| { |
| 1154 |
let ty = m.arbitrary_tag_type(u)?; |
| 1155 |
Ok(EntityType::Tag(ty)) |
| 1156 |
}); |
| 1157 |
} |
| 1158 |
if self.can_add_local_or_import_func() { |
| 1159 |
choices.push(|u, m| { |
| 1160 |
let idx = *u.choose(&m.func_types)?; |
| 1161 |
let ty = m.func_type(idx).clone(); |
| 1162 |
Ok(EntityType::Func(idx, ty)) |
| 1163 |
}); |
| 1164 |
} |
| 1165 |
if self.can_add_local_or_import_global() { |
| 1166 |
choices.push(|u, m| { |
| 1167 |
let ty = m.arbitrary_global_type(u)?; |
| 1168 |
Ok(EntityType::Global(ty)) |
| 1169 |
}); |
| 1170 |
} |
| 1171 |
if self.can_add_local_or_import_memory() { |
| 1172 |
choices.push(|u, m| { |
| 1173 |
let ty = arbitrary_memtype(u, m.config())?; |
| 1174 |
Ok(EntityType::Memory(ty)) |
| 1175 |
}); |
| 1176 |
} |
| 1177 |
if self.can_add_local_or_import_table() { |
| 1178 |
choices.push(|u, m| { |
| 1179 |
let ty = arbitrary_table_type(u, m.config(), Some(m))?; |
| 1180 |
Ok(EntityType::Table(ty)) |
| 1181 |
}); |
| 1182 |
} |
| 1183 |
|
| 1184 |
if choices.is_empty() { |
| 1185 |
// We are out of choices. If we have not have reached the |
| 1186 |
// minimum yet, then we have no way to satisfy the constraint, |
| 1187 |
// but we follow max-constraints before the min-import |
| 1188 |
// constraint. |
| 1189 |
return Ok(false); |
| 1190 |
} |
| 1191 |
|
| 1192 |
// Generate a type to import, but only actually add the item if the |
| 1193 |
// type size budget allows us to. |
| 1194 |
let f = u.choose(&choices)?; |
| 1195 |
let entity_type = f(u, self)?; |
| 1196 |
let budget = self.config.max_type_size - self.type_size; |
| 1197 |
if entity_type.size() + 1 > budget { |
| 1198 |
return Ok(false); |
| 1199 |
} |
| 1200 |
self.type_size += entity_type.size() + 1; |
| 1201 |
|
| 1202 |
// Generate an arbitrary module/name pair to name this import. |
| 1203 |
let mut import_pair = unique_import_strings(1_000, u)?; |
| 1204 |
if self.duplicate_imports_behavior == DuplicateImportsBehavior::Disallowed { |
| 1205 |
while import_strings.contains(&import_pair) { |
| 1206 |
use std::fmt::Write; |
| 1207 |
write!(&mut import_pair.1, "{}", import_strings.len()).unwrap(); |
| 1208 |
} |
| 1209 |
import_strings.insert(import_pair.clone()); |
| 1210 |
} |
| 1211 |
let (module, field) = import_pair; |
| 1212 |
|
| 1213 |
// Once our name is determined, then we push the typed item into the |
| 1214 |
// appropriate namespace. |
| 1215 |
match &entity_type { |
| 1216 |
EntityType::Tag(ty) => self.tags.push(ty.clone()), |
| 1217 |
EntityType::Func(idx, ty) => self.funcs.push((*idx, ty.clone())), |
| 1218 |
EntityType::Global(ty) => self.globals.push(*ty), |
| 1219 |
EntityType::Table(ty) => self.tables.push(*ty), |
| 1220 |
EntityType::Memory(ty) => self.memories.push(*ty), |
| 1221 |
} |
| 1222 |
|
| 1223 |
self.num_imports += 1; |
| 1224 |
self.imports.push(Import { |
| 1225 |
module, |
| 1226 |
field, |
| 1227 |
entity_type, |
| 1228 |
}); |
| 1229 |
Ok(true) |
| 1230 |
})?; |
| 1231 |
|
| 1232 |
Ok(()) |
| 1233 |
} |
| 1234 |
|
| 1235 |
/// Generate some arbitrary imports from the list of available imports. |
| 1236 |
/// |
| 1237 |
/// Returns `true` if there was a list of available imports |
| 1238 |
/// configured. Otherwise `false` and the caller should generate arbitrary |
| 1239 |
/// imports. |
| 1240 |
fn arbitrary_imports_from_available(&mut self, u: &mut Unstructured) -> Result<bool> { |
| 1241 |
let example_module = if let Some(wasm) = self.config.available_imports.take() { |
| 1242 |
wasm |
| 1243 |
} else { |
| 1244 |
return Ok(false); |
| 1245 |
}; |
| 1246 |
|
| 1247 |
#[cfg(feature = "wasmparser")] |
| 1248 |
{ |
| 1249 |
self._arbitrary_imports_from_available(u, &example_module)?; |
| 1250 |
Ok(true) |
| 1251 |
} |
| 1252 |
#[cfg(not(feature = "wasmparser"))] |
| 1253 |
{ |
| 1254 |
let _ = (example_module, u); |
| 1255 |
panic!("support for `available_imports` was disabled at compile time"); |
| 1256 |
} |
| 1257 |
} |
| 1258 |
|
| 1259 |
#[cfg(feature = "wasmparser")] |
| 1260 |
fn _arbitrary_imports_from_available( |
| 1261 |
&mut self, |
| 1262 |
u: &mut Unstructured, |
| 1263 |
example_module: &[u8], |
| 1264 |
) -> Result<()> { |
| 1265 |
// First, parse the module-by-example to collect the types and imports. |
| 1266 |
// |
| 1267 |
// `available_types` will map from a signature index (which is the same as the index into |
| 1268 |
// this vector) as it appears in the parsed code, to the type itself as well as to the |
| 1269 |
// index in our newly generated module. Initially the option is `None` and will become a |
| 1270 |
// `Some` when we encounter an import that uses this signature in the next portion of this |
| 1271 |
// function. See also the `make_func_type` closure below. |
| 1272 |
let mut available_types = Vec::new(); |
| 1273 |
let mut available_imports = Vec::<wasmparser::Import>::new(); |
| 1274 |
for payload in wasmparser::Parser::new(0).parse_all(&example_module) { |
| 1275 |
match payload.expect("could not parse the available import payload") { |
| 1276 |
wasmparser::Payload::TypeSection(type_reader) => { |
| 1277 |
for ty in type_reader.into_iter_err_on_gc_types() { |
| 1278 |
let ty = ty.expect("could not parse type section"); |
| 1279 |
available_types.push((ty, None)); |
| 1280 |
} |
| 1281 |
} |
| 1282 |
wasmparser::Payload::ImportSection(import_reader) => { |
| 1283 |
for im in import_reader { |
| 1284 |
let im = im.expect("could not read import"); |
| 1285 |
// We can immediately filter whether this is an import we want to |
| 1286 |
// use. |
| 1287 |
let use_import = u.arbitrary().unwrap_or(false); |
| 1288 |
if !use_import { |
| 1289 |
continue; |
| 1290 |
} |
| 1291 |
available_imports.push(im); |
| 1292 |
} |
| 1293 |
} |
| 1294 |
_ => {} |
| 1295 |
} |
| 1296 |
} |
| 1297 |
|
| 1298 |
// In this function we need to place imported function/tag types in the types section and |
| 1299 |
// generate import entries (which refer to said types) at the same time. |
| 1300 |
let max_types = self.config.max_types; |
| 1301 |
let multi_value_enabled = self.config.multi_value_enabled; |
| 1302 |
let mut new_imports = Vec::with_capacity(available_imports.len()); |
| 1303 |
let first_type_index = self.types.len(); |
| 1304 |
let mut new_types = Vec::<SubType>::new(); |
| 1305 |
|
| 1306 |
// Returns the index to the translated type in the to-be type section, and the reference to |
| 1307 |
// the type itself. |
| 1308 |
let mut make_func_type = |parsed_sig_idx: u32| { |
| 1309 |
let serialized_sig_idx = match available_types.get_mut(parsed_sig_idx as usize) { |
| 1310 |
None => panic!("signature index refers to a type out of bounds"), |
| 1311 |
Some((_, Some(idx))) => *idx as usize, |
| 1312 |
Some((func_type, index_store)) => { |
| 1313 |
let multi_value_required = func_type.results().len() > 1; |
| 1314 |
let new_index = first_type_index + new_types.len(); |
| 1315 |
if new_index >= max_types || (multi_value_required && !multi_value_enabled) { |
| 1316 |
return None; |
| 1317 |
} |
| 1318 |
let func_type = Rc::new(FuncType { |
| 1319 |
params: func_type |
| 1320 |
.params() |
| 1321 |
.iter() |
| 1322 |
.map(|t| (*t).try_into().unwrap()) |
| 1323 |
.collect(), |
| 1324 |
results: func_type |
| 1325 |
.results() |
| 1326 |
.iter() |
| 1327 |
.map(|t| (*t).try_into().unwrap()) |
| 1328 |
.collect(), |
| 1329 |
}); |
| 1330 |
index_store.replace(new_index as u32); |
| 1331 |
new_types.push(SubType { |
| 1332 |
is_final: true, |
| 1333 |
supertype: None, |
| 1334 |
composite_type: CompositeType::new_func(Rc::clone(&func_type), false), // TODO: handle shared |
| 1335 |
}); |
| 1336 |
new_index |
| 1337 |
} |
| 1338 |
}; |
| 1339 |
match &new_types[serialized_sig_idx - first_type_index] |
| 1340 |
.composite_type |
| 1341 |
.inner |
| 1342 |
{ |
| 1343 |
CompositeInnerType::Func(f) => Some((serialized_sig_idx as u32, Rc::clone(f))), |
| 1344 |
_ => unimplemented!(), |
| 1345 |
} |
| 1346 |
}; |
| 1347 |
|
| 1348 |
for import in available_imports { |
| 1349 |
let type_size_budget = self.config.max_type_size - self.type_size; |
| 1350 |
let entity_type = match &import.ty { |
| 1351 |
wasmparser::TypeRef::Func(sig_idx) => { |
| 1352 |
if self.funcs.len() >= self.config.max_funcs { |
| 1353 |
continue; |
| 1354 |
} else if let Some((sig_idx, func_type)) = make_func_type(*sig_idx) { |
| 1355 |
let entity = EntityType::Func(sig_idx as u32, Rc::clone(&func_type)); |
| 1356 |
if type_size_budget < entity.size() { |
| 1357 |
continue; |
| 1358 |
} |
| 1359 |
self.funcs.push((sig_idx, func_type)); |
| 1360 |
entity |
| 1361 |
} else { |
| 1362 |
continue; |
| 1363 |
} |
| 1364 |
} |
| 1365 |
|
| 1366 |
wasmparser::TypeRef::Tag(wasmparser::TagType { func_type_idx, .. }) => { |
| 1367 |
let can_add_tag = self.tags.len() < self.config.max_tags; |
| 1368 |
if !self.config.exceptions_enabled || !can_add_tag { |
| 1369 |
continue; |
| 1370 |
} else if let Some((sig_idx, func_type)) = make_func_type(*func_type_idx) { |
| 1371 |
let tag_type = TagType { |
| 1372 |
func_type_idx: sig_idx, |
| 1373 |
func_type, |
| 1374 |
}; |
| 1375 |
let entity = EntityType::Tag(tag_type.clone()); |
| 1376 |
if type_size_budget < entity.size() { |
| 1377 |
continue; |
| 1378 |
} |
| 1379 |
self.tags.push(tag_type); |
| 1380 |
entity |
| 1381 |
} else { |
| 1382 |
continue; |
| 1383 |
} |
| 1384 |
} |
| 1385 |
|
| 1386 |
wasmparser::TypeRef::Table(table_ty) => { |
| 1387 |
let table_ty = TableType::try_from(*table_ty).unwrap(); |
| 1388 |
let entity = EntityType::Table(table_ty); |
| 1389 |
let type_size = entity.size(); |
| 1390 |
if type_size_budget < type_size || !self.can_add_local_or_import_table() { |
| 1391 |
continue; |
| 1392 |
} |
| 1393 |
self.type_size += type_size; |
| 1394 |
self.tables.push(table_ty); |
| 1395 |
entity |
| 1396 |
} |
| 1397 |
|
| 1398 |
wasmparser::TypeRef::Memory(memory_ty) => { |
| 1399 |
let memory_ty = MemoryType::try_from(*memory_ty).unwrap(); |
| 1400 |
let entity = EntityType::Memory(memory_ty); |
| 1401 |
let type_size = entity.size(); |
| 1402 |
if type_size_budget < type_size || !self.can_add_local_or_import_memory() { |
| 1403 |
continue; |
| 1404 |
} |
| 1405 |
self.type_size += type_size; |
| 1406 |
self.memories.push(memory_ty); |
| 1407 |
entity |
| 1408 |
} |
| 1409 |
|
| 1410 |
wasmparser::TypeRef::Global(global_ty) => { |
| 1411 |
let global_ty = (*global_ty).try_into().unwrap(); |
| 1412 |
let entity = EntityType::Global(global_ty); |
| 1413 |
let type_size = entity.size(); |
| 1414 |
if type_size_budget < type_size || !self.can_add_local_or_import_global() { |
| 1415 |
continue; |
| 1416 |
} |
| 1417 |
self.type_size += type_size; |
| 1418 |
self.globals.push(global_ty); |
| 1419 |
entity |
| 1420 |
} |
| 1421 |
}; |
| 1422 |
new_imports.push(Import { |
| 1423 |
module: import.module.to_string(), |
| 1424 |
field: import.name.to_string(), |
| 1425 |
entity_type, |
| 1426 |
}); |
| 1427 |
self.num_imports += 1; |
| 1428 |
} |
| 1429 |
|
| 1430 |
// Finally, add the entities we just generated. |
| 1431 |
for ty in new_types { |
| 1432 |
self.rec_groups.push(self.types.len()..self.types.len() + 1); |
| 1433 |
self.add_type(ty); |
| 1434 |
} |
| 1435 |
self.imports.extend(new_imports); |
| 1436 |
|
| 1437 |
Ok(()) |
| 1438 |
} |
| 1439 |
|
| 1440 |
fn type_of(&self, kind: ExportKind, index: u32) -> EntityType { |
| 1441 |
match kind { |
| 1442 |
ExportKind::Global => EntityType::Global(self.globals[index as usize]), |
| 1443 |
ExportKind::Memory => EntityType::Memory(self.memories[index as usize]), |
| 1444 |
ExportKind::Table => EntityType::Table(self.tables[index as usize]), |
| 1445 |
ExportKind::Func => { |
| 1446 |
let (_idx, ty) = &self.funcs[index as usize]; |
| 1447 |
EntityType::Func(u32::max_value(), ty.clone()) |
| 1448 |
} |
| 1449 |
ExportKind::Tag => EntityType::Tag(self.tags[index as usize].clone()), |
| 1450 |
} |
| 1451 |
} |
| 1452 |
|
| 1453 |
fn ty(&self, idx: u32) -> &SubType { |
| 1454 |
&self.types[idx as usize] |
| 1455 |
} |
| 1456 |
|
| 1457 |
fn func_types(&self) -> impl Iterator<Item = (u32, &FuncType)> + '_ { |
| 1458 |
self.func_types |
| 1459 |
.iter() |
| 1460 |
.copied() |
| 1461 |
.map(move |type_i| (type_i, &**self.func_type(type_i))) |
| 1462 |
} |
| 1463 |
|
| 1464 |
fn func_type(&self, idx: u32) -> &Rc<FuncType> { |
| 1465 |
match &self.ty(idx).composite_type.inner { |
| 1466 |
CompositeInnerType::Func(f) => f, |
| 1467 |
_ => panic!("types[{idx}] is not a func type"), |
| 1468 |
} |
| 1469 |
} |
| 1470 |
|
| 1471 |
fn tags(&self) -> impl Iterator<Item = (u32, &TagType)> + '_ { |
| 1472 |
self.tags |
| 1473 |
.iter() |
| 1474 |
.enumerate() |
| 1475 |
.map(move |(i, ty)| (i as u32, ty)) |
| 1476 |
} |
| 1477 |
|
| 1478 |
fn funcs(&self) -> impl Iterator<Item = (u32, &Rc<FuncType>)> + '_ { |
| 1479 |
self.funcs |
| 1480 |
.iter() |
| 1481 |
.enumerate() |
| 1482 |
.map(move |(i, (_, ty))| (i as u32, ty)) |
| 1483 |
} |
| 1484 |
|
| 1485 |
fn has_tag_func_types(&self) -> bool { |
| 1486 |
self.tag_func_types().next().is_some() |
| 1487 |
} |
| 1488 |
|
| 1489 |
fn tag_func_types(&self) -> impl Iterator<Item = u32> + '_ { |
| 1490 |
self.func_types |
| 1491 |
.iter() |
| 1492 |
.copied() |
| 1493 |
.filter(move |i| self.func_type(*i).results.is_empty()) |
| 1494 |
} |
| 1495 |
|
| 1496 |
fn arbitrary_valtype(&self, u: &mut Unstructured) -> Result<ValType> { |
| 1497 |
#[derive(PartialEq, Eq, PartialOrd, Ord)] |
| 1498 |
enum ValTypeClass { |
| 1499 |
I32, |
| 1500 |
I64, |
| 1501 |
F32, |
| 1502 |
F64, |
| 1503 |
V128, |
| 1504 |
Ref, |
| 1505 |
} |
| 1506 |
|
| 1507 |
let mut val_classes: Vec<_> = self |
| 1508 |
.valtypes |
| 1509 |
.iter() |
| 1510 |
.map(|vt| match vt { |
| 1511 |
ValType::I32 => ValTypeClass::I32, |
| 1512 |
ValType::I64 => ValTypeClass::I64, |
| 1513 |
ValType::F32 => ValTypeClass::F32, |
| 1514 |
ValType::F64 => ValTypeClass::F64, |
| 1515 |
ValType::V128 => ValTypeClass::V128, |
| 1516 |
ValType::Ref(_) => ValTypeClass::Ref, |
| 1517 |
}) |
| 1518 |
.collect(); |
| 1519 |
val_classes.sort_unstable(); |
| 1520 |
val_classes.dedup(); |
| 1521 |
|
| 1522 |
match u.choose(&val_classes)? { |
| 1523 |
ValTypeClass::I32 => Ok(ValType::I32), |
| 1524 |
ValTypeClass::I64 => Ok(ValType::I64), |
| 1525 |
ValTypeClass::F32 => Ok(ValType::F32), |
| 1526 |
ValTypeClass::F64 => Ok(ValType::F64), |
| 1527 |
ValTypeClass::V128 => Ok(ValType::V128), |
| 1528 |
ValTypeClass::Ref => Ok(ValType::Ref(self.arbitrary_ref_type(u)?)), |
| 1529 |
} |
| 1530 |
} |
| 1531 |
|
| 1532 |
fn arbitrary_global_type(&self, u: &mut Unstructured) -> Result<GlobalType> { |
| 1533 |
Ok(GlobalType { |
| 1534 |
val_type: self.arbitrary_valtype(u)?, |
| 1535 |
mutable: u.arbitrary()?, |
| 1536 |
shared: false, |
| 1537 |
}) |
| 1538 |
} |
| 1539 |
|
| 1540 |
fn arbitrary_tag_type(&self, u: &mut Unstructured) -> Result<TagType> { |
| 1541 |
let candidate_func_types: Vec<_> = self.tag_func_types().collect(); |
| 1542 |
arbitrary_tag_type(u, &candidate_func_types, |ty_idx| { |
| 1543 |
self.func_type(ty_idx).clone() |
| 1544 |
}) |
| 1545 |
} |
| 1546 |
|
| 1547 |
fn arbitrary_tags(&mut self, u: &mut Unstructured) -> Result<()> { |
| 1548 |
if !self.config.exceptions_enabled || !self.has_tag_func_types() { |
| 1549 |
return Ok(()); |
| 1550 |
} |
| 1551 |
|
| 1552 |
arbitrary_loop(u, self.config.min_tags, self.config.max_tags, |u| { |
| 1553 |
if !self.can_add_local_or_import_tag() { |
| 1554 |
return Ok(false); |
| 1555 |
} |
| 1556 |
self.tags.push(self.arbitrary_tag_type(u)?); |
| 1557 |
self.num_defined_tags += 1; |
| 1558 |
Ok(true) |
| 1559 |
}) |
| 1560 |
} |
| 1561 |
|
| 1562 |
fn arbitrary_funcs(&mut self, u: &mut Unstructured) -> Result<()> { |
| 1563 |
if self.func_types.is_empty() { |
| 1564 |
return Ok(()); |
| 1565 |
} |
| 1566 |
|
| 1567 |
arbitrary_loop(u, self.config.min_funcs, self.config.max_funcs, |u| { |
| 1568 |
if !self.can_add_local_or_import_func() { |
| 1569 |
return Ok(false); |
| 1570 |
} |
| 1571 |
let max = self.func_types.len() - 1; |
| 1572 |
let ty = self.func_types[u.int_in_range(0..=max)?]; |
| 1573 |
self.funcs.push((ty, self.func_type(ty).clone())); |
| 1574 |
self.num_defined_funcs += 1; |
| 1575 |
Ok(true) |
| 1576 |
}) |
| 1577 |
} |
| 1578 |
|
| 1579 |
fn arbitrary_tables(&mut self, u: &mut Unstructured) -> Result<()> { |
| 1580 |
arbitrary_loop( |
| 1581 |
u, |
| 1582 |
self.config.min_tables as usize, |
| 1583 |
self.config.max_tables as usize, |
| 1584 |
|u| { |
| 1585 |
if !self.can_add_local_or_import_table() { |
| 1586 |
return Ok(false); |
| 1587 |
} |
| 1588 |
let ty = arbitrary_table_type(u, self.config(), Some(self))?; |
| 1589 |
let init = self.arbitrary_table_init(u, ty.element_type)?; |
| 1590 |
self.defined_tables.push(init); |
| 1591 |
self.tables.push(ty); |
| 1592 |
Ok(true) |
| 1593 |
}, |
| 1594 |
) |
| 1595 |
} |
| 1596 |
|
| 1597 |
/// Generates an arbitrary table initialization expression for a table whose |
| 1598 |
/// element type is `ty`. |
| 1599 |
/// |
| 1600 |
/// Table initialization expressions were added by the GC proposal to |
| 1601 |
/// initialize non-nullable tables. |
| 1602 |
fn arbitrary_table_init( |
| 1603 |
&mut self, |
| 1604 |
u: &mut Unstructured, |
| 1605 |
ty: RefType, |
| 1606 |
) -> Result<Option<ConstExpr>> { |
| 1607 |
if !self.config.gc_enabled { |
| 1608 |
assert!(ty.nullable); |
| 1609 |
return Ok(None); |
| 1610 |
} |
| 1611 |
// Even with the GC proposal an initialization expression is not |
| 1612 |
// required if the element type is nullable. |
| 1613 |
if ty.nullable && u.arbitrary()? { |
| 1614 |
return Ok(None); |
| 1615 |
} |
| 1616 |
let expr = self.arbitrary_const_expr(ValType::Ref(ty), u)?; |
| 1617 |
Ok(Some(expr)) |
| 1618 |
} |
| 1619 |
|
| 1620 |
fn arbitrary_memories(&mut self, u: &mut Unstructured) -> Result<()> { |
| 1621 |
arbitrary_loop( |
| 1622 |
u, |
| 1623 |
self.config.min_memories as usize, |
| 1624 |
self.config.max_memories as usize, |
| 1625 |
|u| { |
| 1626 |
if !self.can_add_local_or_import_memory() { |
| 1627 |
return Ok(false); |
| 1628 |
} |
| 1629 |
self.num_defined_memories += 1; |
| 1630 |
self.memories.push(arbitrary_memtype(u, self.config())?); |
| 1631 |
Ok(true) |
| 1632 |
}, |
| 1633 |
) |
| 1634 |
} |
| 1635 |
|
| 1636 |
/// Add a new global of the given type and return its global index. |
| 1637 |
fn add_arbitrary_global_of_type( |
| 1638 |
&mut self, |
| 1639 |
ty: GlobalType, |
| 1640 |
u: &mut Unstructured, |
| 1641 |
) -> Result<u32> { |
| 1642 |
let expr = self.arbitrary_const_expr(ty.val_type, u)?; |
| 1643 |
let global_idx = self.globals.len() as u32; |
| 1644 |
self.globals.push(ty); |
| 1645 |
self.defined_globals.push((global_idx, expr)); |
| 1646 |
Ok(global_idx) |
| 1647 |
} |
| 1648 |
|
| 1649 |
/// Generates an arbitrary constant expression of the type `ty`. |
| 1650 |
fn arbitrary_const_expr(&mut self, ty: ValType, u: &mut Unstructured) -> Result<ConstExpr> { |
| 1651 |
let mut choices = mem::take(&mut self.const_expr_choices); |
| 1652 |
choices.clear(); |
| 1653 |
let num_funcs = self.funcs.len() as u32; |
| 1654 |
|
| 1655 |
// MVP wasm can `global.get` any immutable imported global in a |
| 1656 |
// constant expression, and the GC proposal enables this for all |
| 1657 |
// globals, so make all matching globals a candidate. |
| 1658 |
for i in self.globals_for_const_expr(ty) { |
| 1659 |
choices.push(Box::new(move |_, _| Ok(ConstExpr::global_get(i)))); |
| 1660 |
} |
| 1661 |
|
| 1662 |
// Another option for all types is to have an actual value of each type. |
| 1663 |
// Change `ty` to any valid subtype of `ty` and then generate a matching |
| 1664 |
// type of that value. |
| 1665 |
let ty = self.arbitrary_matching_val_type(u, ty)?; |
| 1666 |
match ty { |
| 1667 |
ValType::I32 => choices.push(Box::new(|u, _| Ok(ConstExpr::i32_const(u.arbitrary()?)))), |
| 1668 |
ValType::I64 => choices.push(Box::new(|u, _| Ok(ConstExpr::i64_const(u.arbitrary()?)))), |
| 1669 |
ValType::F32 => choices.push(Box::new(|u, _| Ok(ConstExpr::f32_const(u.arbitrary()?)))), |
| 1670 |
ValType::F64 => choices.push(Box::new(|u, _| Ok(ConstExpr::f64_const(u.arbitrary()?)))), |
| 1671 |
ValType::V128 => { |
| 1672 |
choices.push(Box::new(|u, _| Ok(ConstExpr::v128_const(u.arbitrary()?)))) |
| 1673 |
} |
| 1674 |
|
| 1675 |
ValType::Ref(ty) => { |
| 1676 |
if ty.nullable { |
| 1677 |
choices.push(Box::new(move |_, _| Ok(ConstExpr::ref_null(ty.heap_type)))); |
| 1678 |
} |
| 1679 |
|
| 1680 |
match ty.heap_type { |
| 1681 |
HeapType::Abstract { |
| 1682 |
ty: AbstractHeapType::Func, |
| 1683 |
.. |
| 1684 |
} if num_funcs > 0 => { |
| 1685 |
choices.push(Box::new(move |u, _| { |
| 1686 |
let func = u.int_in_range(0..=num_funcs - 1)?; |
| 1687 |
Ok(ConstExpr::ref_func(func)) |
| 1688 |
})); |
| 1689 |
} |
| 1690 |
|
| 1691 |
HeapType::Concrete(ty) => { |
| 1692 |
for (i, fty) in self.funcs.iter().map(|(t, _)| *t).enumerate() { |
| 1693 |
if ty != fty { |
| 1694 |
continue; |
| 1695 |
} |
| 1696 |
choices.push(Box::new(move |_, _| Ok(ConstExpr::ref_func(i as u32)))); |
| 1697 |
} |
| 1698 |
} |
| 1699 |
|
| 1700 |
// TODO: fill out more GC types e.g `array.new` and |
| 1701 |
// `struct.new` |
| 1702 |
_ => {} |
| 1703 |
} |
| 1704 |
} |
| 1705 |
} |
| 1706 |
|
| 1707 |
let f = u.choose(&choices)?; |
| 1708 |
let ret = f(u, ty); |
| 1709 |
self.const_expr_choices = choices; |
| 1710 |
ret |
| 1711 |
} |
| 1712 |
|
| 1713 |
fn arbitrary_globals(&mut self, u: &mut Unstructured) -> Result<()> { |
| 1714 |
arbitrary_loop(u, self.config.min_globals, self.config.max_globals, |u| { |
| 1715 |
if !self.can_add_local_or_import_global() { |
| 1716 |
return Ok(false); |
| 1717 |
} |
| 1718 |
|
| 1719 |
let ty = self.arbitrary_global_type(u)?; |
| 1720 |
self.add_arbitrary_global_of_type(ty, u)?; |
| 1721 |
|
| 1722 |
Ok(true) |
| 1723 |
}) |
| 1724 |
} |
| 1725 |
|
| 1726 |
fn required_exports(&mut self, u: &mut Unstructured) -> Result<bool> { |
| 1727 |
let example_module = if let Some(wasm) = self.config.exports.clone() { |
| 1728 |
wasm |
| 1729 |
} else { |
| 1730 |
return Ok(false); |
| 1731 |
}; |
| 1732 |
|
| 1733 |
#[cfg(feature = "wasmparser")] |
| 1734 |
{ |
| 1735 |
self._required_exports(u, &example_module)?; |
| 1736 |
Ok(true) |
| 1737 |
} |
| 1738 |
#[cfg(not(feature = "wasmparser"))] |
| 1739 |
{ |
| 1740 |
let _ = (example_module, u); |
| 1741 |
panic!("support for `exports` was disabled at compile time"); |
| 1742 |
} |
| 1743 |
} |
| 1744 |
|
| 1745 |
#[cfg(feature = "wasmparser")] |
| 1746 |
fn _required_exports(&mut self, u: &mut Unstructured, example_module: &[u8]) -> Result<()> { |
| 1747 |
let mut required_exports: Vec<wasmparser::Export> = vec![]; |
| 1748 |
let mut validator = wasmparser::Validator::new(); |
| 1749 |
let exports_types = validator |
| 1750 |
.validate_all(&example_module) |
| 1751 |
.expect("Failed to validate `exports` Wasm"); |
| 1752 |
for payload in wasmparser::Parser::new(0).parse_all(&example_module) { |
| 1753 |
match payload.expect("Failed to read `exports` Wasm") { |
| 1754 |
wasmparser::Payload::ExportSection(export_reader) => { |
| 1755 |
required_exports = export_reader |
| 1756 |
.into_iter() |
| 1757 |
.collect::<Result<_, _>>() |
| 1758 |
.expect("Failed to read `exports` export section"); |
| 1759 |
} |
| 1760 |
_ => {} |
| 1761 |
} |
| 1762 |
} |
| 1763 |
|
| 1764 |
// For each export, add necessary prerequisites to the module. |
| 1765 |
let exports_types = exports_types.as_ref(); |
| 1766 |
for export in required_exports { |
| 1767 |
let new_index = match exports_types |
| 1768 |
.entity_type_from_export(&export) |
| 1769 |
.unwrap_or_else(|| { |
| 1770 |
panic!( |
| 1771 |
"Unable to get type from export {:?} in `exports` Wasm", |
| 1772 |
export, |
| 1773 |
) |
| 1774 |
}) { |
| 1775 |
// For functions, add the type and a function with that type. |
| 1776 |
wasmparser::types::EntityType::Func(id) => { |
| 1777 |
let subtype = exports_types.get(id).unwrap_or_else(|| { |
| 1778 |
panic!( |
| 1779 |
"Unable to get subtype for function {:?} in `exports` Wasm", |
| 1780 |
id |
| 1781 |
) |
| 1782 |
}); |
| 1783 |
match &subtype.composite_type.inner { |
| 1784 |
wasmparser::CompositeInnerType::Func(func_type) => { |
| 1785 |
assert!( |
| 1786 |
subtype.is_final, |
| 1787 |
"Subtype {:?} from `exports` Wasm is not final", |
| 1788 |
subtype |
| 1789 |
); |
| 1790 |
assert!( |
| 1791 |
subtype.supertype_idx.is_none(), |
| 1792 |
"Subtype {:?} from `exports` Wasm has non-empty supertype", |
| 1793 |
subtype |
| 1794 |
); |
| 1795 |
let new_type = Rc::new(FuncType { |
| 1796 |
params: func_type |
| 1797 |
.params() |
| 1798 |
.iter() |
| 1799 |
.copied() |
| 1800 |
.map(|t| t.try_into().unwrap()) |
| 1801 |
.collect(), |
| 1802 |
results: func_type |
| 1803 |
.results() |
| 1804 |
.iter() |
| 1805 |
.copied() |
| 1806 |
.map(|t| t.try_into().unwrap()) |
| 1807 |
.collect(), |
| 1808 |
}); |
| 1809 |
self.rec_groups.push(self.types.len()..self.types.len() + 1); |
| 1810 |
let type_index = self.add_type(SubType { |
| 1811 |
is_final: true, |
| 1812 |
supertype: None, |
| 1813 |
composite_type: CompositeType::new_func( |
| 1814 |
Rc::clone(&new_type), |
| 1815 |
false, |
| 1816 |
), // TODO: handle shared |
| 1817 |
}); |
| 1818 |
let func_index = self.funcs.len() as u32; |
| 1819 |
self.funcs.push((type_index, new_type)); |
| 1820 |
self.num_defined_funcs += 1; |
| 1821 |
func_index |
| 1822 |
} |
| 1823 |
_ => panic!( |
| 1824 |
"Unable to handle type {:?} from `exports` Wasm", |
| 1825 |
subtype.composite_type |
| 1826 |
), |
| 1827 |
} |
| 1828 |
} |
| 1829 |
// For globals, add a new global. |
| 1830 |
wasmparser::types::EntityType::Global(global_type) => { |
| 1831 |
self.add_arbitrary_global_of_type(global_type.try_into().unwrap(), u)? |
| 1832 |
} |
| 1833 |
wasmparser::types::EntityType::Table(_) |
| 1834 |
| wasmparser::types::EntityType::Memory(_) |
| 1835 |
| wasmparser::types::EntityType::Tag(_) => { |
| 1836 |
panic!( |
| 1837 |
"Config `exports` has an export of type {:?} which cannot yet be handled.", |
| 1838 |
export.kind |
| 1839 |
) |
| 1840 |
} |
| 1841 |
}; |
| 1842 |
self.exports |
| 1843 |
.push((export.name.to_string(), export.kind.into(), new_index)); |
| 1844 |
self.export_names.insert(export.name.to_string()); |
| 1845 |
} |
| 1846 |
|
| 1847 |
Ok(()) |
| 1848 |
} |
| 1849 |
|
| 1850 |
fn arbitrary_exports(&mut self, u: &mut Unstructured) -> Result<()> { |
| 1851 |
if self.config.max_type_size < self.type_size && !self.config.export_everything { |
| 1852 |
return Ok(()); |
| 1853 |
} |
| 1854 |
|
| 1855 |
// Build up a list of candidates for each class of import |
| 1856 |
let mut choices: Vec<Vec<(ExportKind, u32)>> = Vec::with_capacity(6); |
| 1857 |
choices.push( |
| 1858 |
(0..self.funcs.len()) |
| 1859 |
.map(|i| (ExportKind::Func, i as u32)) |
| 1860 |
.collect(), |
| 1861 |
); |
| 1862 |
choices.push( |
| 1863 |
(0..self.tables.len()) |
| 1864 |
.map(|i| (ExportKind::Table, i as u32)) |
| 1865 |
.collect(), |
| 1866 |
); |
| 1867 |
choices.push( |
| 1868 |
(0..self.memories.len()) |
| 1869 |
.map(|i| (ExportKind::Memory, i as u32)) |
| 1870 |
.collect(), |
| 1871 |
); |
| 1872 |
choices.push( |
| 1873 |
(0..self.globals.len()) |
| 1874 |
.map(|i| (ExportKind::Global, i as u32)) |
| 1875 |
.collect(), |
| 1876 |
); |
| 1877 |
|
| 1878 |
// If the configuration demands exporting everything, we do so here and |
| 1879 |
// early-return. |
| 1880 |
if self.config.export_everything { |
| 1881 |
for choices_by_kind in choices { |
| 1882 |
for (kind, idx) in choices_by_kind { |
| 1883 |
let name = unique_string(1_000, &mut self.export_names, u)?; |
| 1884 |
self.add_arbitrary_export(name, kind, idx)?; |
| 1885 |
} |
| 1886 |
} |
| 1887 |
return Ok(()); |
| 1888 |
} |
| 1889 |
|
| 1890 |
arbitrary_loop(u, self.config.min_exports, self.config.max_exports, |u| { |
| 1891 |
// Remove all candidates for export whose type size exceeds our |
| 1892 |
// remaining budget for type size. Then also remove any classes |
| 1893 |
// of exports which no longer have any candidates. |
| 1894 |
// |
| 1895 |
// If there's nothing remaining after this, then we're done. |
| 1896 |
let max_size = self.config.max_type_size - self.type_size; |
| 1897 |
for list in choices.iter_mut() { |
| 1898 |
list.retain(|(kind, idx)| self.type_of(*kind, *idx).size() + 1 < max_size); |
| 1899 |
} |
| 1900 |
choices.retain(|list| !list.is_empty()); |
| 1901 |
if choices.is_empty() { |
| 1902 |
return Ok(false); |
| 1903 |
} |
| 1904 |
|
| 1905 |
// Pick a name, then pick the export, and then we can record |
| 1906 |
// information about the chosen export. |
| 1907 |
let name = unique_string(1_000, &mut self.export_names, u)?; |
| 1908 |
let list = u.choose(&choices)?; |
| 1909 |
let (kind, idx) = *u.choose(list)?; |
| 1910 |
self.add_arbitrary_export(name, kind, idx)?; |
| 1911 |
Ok(true) |
| 1912 |
}) |
| 1913 |
} |
| 1914 |
|
| 1915 |
fn add_arbitrary_export(&mut self, name: String, kind: ExportKind, idx: u32) -> Result<()> { |
| 1916 |
let ty = self.type_of(kind, idx); |
| 1917 |
self.type_size += 1 + ty.size(); |
| 1918 |
if self.type_size <= self.config.max_type_size { |
| 1919 |
self.exports.push((name, kind, idx)); |
| 1920 |
Ok(()) |
| 1921 |
} else { |
| 1922 |
// If our addition of exports takes us above the allowed number of |
| 1923 |
// types, we fail; this error code is not the most illustrative of |
| 1924 |
// the cause but is the best available from `arbitrary`. |
| 1925 |
Err(arbitrary::Error::IncorrectFormat) |
| 1926 |
} |
| 1927 |
} |
| 1928 |
|
| 1929 |
fn arbitrary_start(&mut self, u: &mut Unstructured) -> Result<()> { |
| 1930 |
if !self.config.allow_start_export { |
| 1931 |
return Ok(()); |
| 1932 |
} |
| 1933 |
|
| 1934 |
let mut choices = Vec::with_capacity(self.funcs.len() as usize); |
| 1935 |
|
| 1936 |
for (func_idx, ty) in self.funcs() { |
| 1937 |
if ty.params.is_empty() && ty.results.is_empty() { |
| 1938 |
choices.push(func_idx); |
| 1939 |
} |
| 1940 |
} |
| 1941 |
|
| 1942 |
if !choices.is_empty() && u.arbitrary().unwrap_or(false) { |
| 1943 |
let f = *u.choose(&choices)?; |
| 1944 |
self.start = Some(f); |
| 1945 |
} |
| 1946 |
|
| 1947 |
Ok(()) |
| 1948 |
} |
| 1949 |
|
| 1950 |
fn arbitrary_elems(&mut self, u: &mut Unstructured) -> Result<()> { |
| 1951 |
// Create a helper closure to choose an arbitrary offset. |
| 1952 |
let mut global_i32 = vec![]; |
| 1953 |
let mut global_i64 = vec![]; |
| 1954 |
if !self.config.disallow_traps { |
| 1955 |
for i in self.globals_for_const_expr(ValType::I32) { |
| 1956 |
global_i32.push(i); |
| 1957 |
} |
| 1958 |
for i in self.globals_for_const_expr(ValType::I64) { |
| 1959 |
global_i64.push(i); |
| 1960 |
} |
| 1961 |
} |
| 1962 |
let disallow_traps = self.config.disallow_traps; |
| 1963 |
let arbitrary_active_elem = |
| 1964 |
|u: &mut Unstructured, min_mem_size: u64, table: Option<u32>, table_ty: &TableType| { |
| 1965 |
let global_choices = if table_ty.table64 { |
| 1966 |
&global_i64 |
| 1967 |
} else { |
| 1968 |
&global_i32 |
| 1969 |
}; |
| 1970 |
let (offset, max_size_hint) = if !global_choices.is_empty() && u.arbitrary()? { |
| 1971 |
let g = u.choose(&global_choices)?; |
| 1972 |
(Offset::Global(*g), None) |
| 1973 |
} else { |
| 1974 |
let max_mem_size = if disallow_traps { |
| 1975 |
table_ty.minimum |
| 1976 |
} else if table_ty.table64 { |
| 1977 |
u64::MAX |
| 1978 |
} else { |
| 1979 |
u64::from(u32::MAX) |
| 1980 |
}; |
| 1981 |
let offset = arbitrary_offset(u, min_mem_size, max_mem_size, 0)?; |
| 1982 |
let max_size_hint = if disallow_traps |
| 1983 |
|| (offset <= min_mem_size |
| 1984 |
&& u.int_in_range(0..=CHANCE_OFFSET_INBOUNDS)? != 0) |
| 1985 |
{ |
| 1986 |
Some(min_mem_size - offset) |
| 1987 |
} else { |
| 1988 |
None |
| 1989 |
}; |
| 1990 |
|
| 1991 |
let offset = if table_ty.table64 { |
| 1992 |
Offset::Const64(offset as i64) |
| 1993 |
} else { |
| 1994 |
Offset::Const32(offset as i32) |
| 1995 |
}; |
| 1996 |
(offset, max_size_hint) |
| 1997 |
}; |
| 1998 |
Ok((ElementKind::Active { table, offset }, max_size_hint)) |
| 1999 |
}; |
| 2000 |
|
| 2001 |
// Generate a list of candidates for "kinds" of elements segments. For |
| 2002 |
// example we can have an active segment for any existing table or |
| 2003 |
// passive/declared segments if the right wasm features are enabled. |
| 2004 |
type GenElemSegment<'a> = |
| 2005 |
dyn Fn(&mut Unstructured) -> Result<(ElementKind, Option<u64>)> + 'a; |
| 2006 |
let mut choices: Vec<Box<GenElemSegment>> = Vec::new(); |
| 2007 |
|
| 2008 |
// Bulk memory enables passive/declared segments, and note that the |
| 2009 |
// types used are selected later. |
| 2010 |
if self.config.bulk_memory_enabled { |
| 2011 |
choices.push(Box::new(|_| Ok((ElementKind::Passive, None)))); |
| 2012 |
choices.push(Box::new(|_| Ok((ElementKind::Declared, None)))); |
| 2013 |
} |
| 2014 |
|
| 2015 |
for (i, ty) in self.tables.iter().enumerate() { |
| 2016 |
// If this table starts with no capacity then any non-empty element |
| 2017 |
// segment placed onto it will immediately trap, which isn't too |
| 2018 |
// too interesting. If that's the case give it an unlikely chance |
| 2019 |
// of proceeding. |
| 2020 |
if ty.minimum == 0 && u.int_in_range(0..=CHANCE_SEGMENT_ON_EMPTY)? != 0 { |
| 2021 |
continue; |
| 2022 |
} |
| 2023 |
|
| 2024 |
let minimum = ty.minimum; |
| 2025 |
// If the first table is a funcref table then it's a candidate for |
| 2026 |
// the MVP encoding of element segments. |
| 2027 |
let ty = *ty; |
| 2028 |
if i == 0 && ty.element_type == RefType::FUNCREF { |
| 2029 |
choices.push(Box::new(move |u| { |
| 2030 |
arbitrary_active_elem(u, minimum, None, &ty) |
| 2031 |
})); |
| 2032 |
} |
| 2033 |
if self.config.bulk_memory_enabled { |
| 2034 |
let idx = Some(i as u32); |
| 2035 |
choices.push(Box::new(move |u| { |
| 2036 |
arbitrary_active_elem(u, minimum, idx, &ty) |
| 2037 |
})); |
| 2038 |
} |
| 2039 |
} |
| 2040 |
|
| 2041 |
if choices.is_empty() { |
| 2042 |
return Ok(()); |
| 2043 |
} |
| 2044 |
|
| 2045 |
arbitrary_loop( |
| 2046 |
u, |
| 2047 |
self.config.min_element_segments, |
| 2048 |
self.config.max_element_segments, |
| 2049 |
|u| { |
| 2050 |
// Pick a kind of element segment to generate which will also |
| 2051 |
// give us a hint of the maximum size, if any. |
| 2052 |
let (kind, max_size_hint) = u.choose(&choices)?(u)?; |
| 2053 |
let max = max_size_hint |
| 2054 |
.map(|i| usize::try_from(i).unwrap()) |
| 2055 |
.unwrap_or_else(|| self.config.max_elements); |
| 2056 |
|
| 2057 |
// Infer, from the kind of segment, the type of the element |
| 2058 |
// segment. Passive/declared segments can be declared with any |
| 2059 |
// reference type, but active segments must match their table. |
| 2060 |
let ty = match kind { |
| 2061 |
ElementKind::Passive | ElementKind::Declared => self.arbitrary_ref_type(u)?, |
| 2062 |
ElementKind::Active { table, .. } => { |
| 2063 |
let idx = table.unwrap_or(0); |
| 2064 |
self.arbitrary_matching_ref_type(u, self.tables[idx as usize].element_type)? |
| 2065 |
} |
| 2066 |
}; |
| 2067 |
|
| 2068 |
// The `Elements::Functions` encoding is only possible when the |
| 2069 |
// element type is a `funcref` because the binary format can't |
| 2070 |
// allow encoding any other type in that form. |
| 2071 |
let can_use_function_list = ty == RefType::FUNCREF; |
| 2072 |
if !self.config.reference_types_enabled { |
| 2073 |
assert!(can_use_function_list); |
| 2074 |
} |
| 2075 |
|
| 2076 |
// If a function list is possible then build up a list of |
| 2077 |
// functions that can be selected from. |
| 2078 |
let mut func_candidates = Vec::new(); |
| 2079 |
if can_use_function_list { |
| 2080 |
match ty.heap_type { |
| 2081 |
HeapType::Abstract { |
| 2082 |
ty: AbstractHeapType::Func, |
| 2083 |
.. |
| 2084 |
} => { |
| 2085 |
func_candidates.extend(0..self.funcs.len() as u32); |
| 2086 |
} |
| 2087 |
HeapType::Concrete(ty) => { |
| 2088 |
for (i, (fty, _)) in self.funcs.iter().enumerate() { |
| 2089 |
if *fty == ty { |
| 2090 |
func_candidates.push(i as u32); |
| 2091 |
} |
| 2092 |
} |
| 2093 |
} |
| 2094 |
_ => {} |
| 2095 |
} |
| 2096 |
} |
| 2097 |
|
| 2098 |
// And finally actually generate the arbitrary elements of this |
| 2099 |
// element segment. Function indices are used if they're either |
| 2100 |
// forced or allowed, and otherwise expressions are used |
| 2101 |
// instead. |
| 2102 |
let items = if !self.config.reference_types_enabled |
| 2103 |
|| (can_use_function_list && u.arbitrary()?) |
| 2104 |
{ |
| 2105 |
let mut init = vec![]; |
| 2106 |
if func_candidates.len() > 0 { |
| 2107 |
arbitrary_loop(u, self.config.min_elements, max, |u| { |
| 2108 |
let func_idx = *u.choose(&func_candidates)?; |
| 2109 |
init.push(func_idx); |
| 2110 |
Ok(true) |
| 2111 |
})?; |
| 2112 |
} |
| 2113 |
Elements::Functions(init) |
| 2114 |
} else { |
| 2115 |
let mut init = vec![]; |
| 2116 |
arbitrary_loop(u, self.config.min_elements, max, |u| { |
| 2117 |
init.push(self.arbitrary_const_expr(ValType::Ref(ty), u)?); |
| 2118 |
Ok(true) |
| 2119 |
})?; |
| 2120 |
Elements::Expressions(init) |
| 2121 |
}; |
| 2122 |
|
| 2123 |
self.elems.push(ElementSegment { kind, ty, items }); |
| 2124 |
Ok(true) |
| 2125 |
}, |
| 2126 |
) |
| 2127 |
} |
| 2128 |
|
| 2129 |
fn arbitrary_code(&mut self, u: &mut Unstructured) -> Result<()> { |
| 2130 |
self.compute_interesting_values(); |
| 2131 |
|
| 2132 |
self.code.reserve(self.num_defined_funcs); |
| 2133 |
let mut allocs = CodeBuilderAllocations::new(self, self.config.exports.is_some()); |
| 2134 |
for (_, ty) in self.funcs[self.funcs.len() - self.num_defined_funcs..].iter() { |
| 2135 |
let body = self.arbitrary_func_body(u, ty, &mut allocs)?; |
| 2136 |
self.code.push(body); |
| 2137 |
} |
| 2138 |
allocs.finish(u, self)?; |
| 2139 |
Ok(()) |
| 2140 |
} |
| 2141 |
|
| 2142 |
fn arbitrary_func_body( |
| 2143 |
&self, |
| 2144 |
u: &mut Unstructured, |
| 2145 |
ty: &FuncType, |
| 2146 |
allocs: &mut CodeBuilderAllocations, |
| 2147 |
) -> Result<Code> { |
| 2148 |
let mut locals = self.arbitrary_locals(u)?; |
| 2149 |
let builder = allocs.builder(ty, &mut locals); |
| 2150 |
let instructions = if self.config.allow_invalid_funcs && u.arbitrary().unwrap_or(false) { |
| 2151 |
Instructions::Arbitrary(arbitrary_vec_u8(u)?) |
| 2152 |
} else { |
| 2153 |
Instructions::Generated(builder.arbitrary(u, self)?) |
| 2154 |
}; |
| 2155 |
|
| 2156 |
Ok(Code { |
| 2157 |
locals, |
| 2158 |
instructions, |
| 2159 |
}) |
| 2160 |
} |
| 2161 |
|
| 2162 |
fn arbitrary_locals(&self, u: &mut Unstructured) -> Result<Vec<ValType>> { |
| 2163 |
let mut ret = Vec::new(); |
| 2164 |
arbitrary_loop(u, 0, 100, |u| { |
| 2165 |
ret.push(self.arbitrary_valtype(u)?); |
| 2166 |
Ok(true) |
| 2167 |
})?; |
| 2168 |
Ok(ret) |
| 2169 |
} |
| 2170 |
|
| 2171 |
fn arbitrary_data(&mut self, u: &mut Unstructured) -> Result<()> { |
| 2172 |
// With bulk-memory we can generate passive data, otherwise if there are |
| 2173 |
// no memories we can't generate any data. |
| 2174 |
let memories = self.memories.len() as u32; |
| 2175 |
if memories == 0 && !self.config.bulk_memory_enabled { |
| 2176 |
return Ok(()); |
| 2177 |
} |
| 2178 |
let disallow_traps = self.config.disallow_traps; |
| 2179 |
let mut choices32: Vec<Box<dyn Fn(&mut Unstructured, u64, usize) -> Result<Offset>>> = |
| 2180 |
vec![]; |
| 2181 |
choices32.push(Box::new(|u, min_size, data_len| { |
| 2182 |
let min = u32::try_from(min_size.saturating_mul(64 * 1024)) |
| 2183 |
.unwrap_or(u32::MAX) |
| 2184 |
.into(); |
| 2185 |
let max = if disallow_traps { min } else { u32::MAX.into() }; |
| 2186 |
Ok(Offset::Const32( |
| 2187 |
arbitrary_offset(u, min, max, data_len)? as i32 |
| 2188 |
)) |
| 2189 |
})); |
| 2190 |
let mut choices64: Vec<Box<dyn Fn(&mut Unstructured, u64, usize) -> Result<Offset>>> = |
| 2191 |
vec![]; |
| 2192 |
choices64.push(Box::new(|u, min_size, data_len| { |
| 2193 |
let min = min_size.saturating_mul(64 * 1024); |
| 2194 |
let max = if disallow_traps { min } else { u64::MAX }; |
| 2195 |
Ok(Offset::Const64( |
| 2196 |
arbitrary_offset(u, min, max, data_len)? as i64 |
| 2197 |
)) |
| 2198 |
})); |
| 2199 |
if !self.config.disallow_traps { |
| 2200 |
for i in self.globals_for_const_expr(ValType::I32) { |
| 2201 |
choices32.push(Box::new(move |_, _, _| Ok(Offset::Global(i)))); |
| 2202 |
} |
| 2203 |
for i in self.globals_for_const_expr(ValType::I64) { |
| 2204 |
choices64.push(Box::new(move |_, _, _| Ok(Offset::Global(i)))); |
| 2205 |
} |
| 2206 |
} |
| 2207 |
|
| 2208 |
// Build a list of candidate memories that we'll add data initializers |
| 2209 |
// for. If a memory doesn't have an initial size then any initializers |
| 2210 |
// for that memory will trap instantiation, which isn't too |
| 2211 |
// interesting. Try to make this happen less often by making it less |
| 2212 |
// likely that a memory with 0 size will have a data segment. |
| 2213 |
let mut memories = Vec::new(); |
| 2214 |
for (i, mem) in self.memories.iter().enumerate() { |
| 2215 |
if mem.minimum > 0 || u.int_in_range(0..=CHANCE_SEGMENT_ON_EMPTY)? == 0 { |
| 2216 |
memories.push(i as u32); |
| 2217 |
} |
| 2218 |
} |
| 2219 |
|
| 2220 |
// With memories we can generate data segments, and with bulk memory we |
| 2221 |
// can generate passive segments. Without these though we can't create |
| 2222 |
// a valid module with data segments. |
| 2223 |
if memories.is_empty() && !self.config.bulk_memory_enabled { |
| 2224 |
return Ok(()); |
| 2225 |
} |
| 2226 |
|
| 2227 |
arbitrary_loop( |
| 2228 |
u, |
| 2229 |
self.config.min_data_segments, |
| 2230 |
self.config.max_data_segments, |
| 2231 |
|u| { |
| 2232 |
let mut init: Vec<u8> = u.arbitrary()?; |
| 2233 |
|
| 2234 |
// Passive data can only be generated if bulk memory is enabled. |
| 2235 |
// Otherwise if there are no memories we *only* generate passive |
| 2236 |
// data. Finally if all conditions are met we use an input byte to |
| 2237 |
// determine if it should be passive or active. |
| 2238 |
let kind = |
| 2239 |
if self.config.bulk_memory_enabled && (memories.is_empty() || u.arbitrary()?) { |
| 2240 |
DataSegmentKind::Passive |
| 2241 |
} else { |
| 2242 |
let memory_index = *u.choose(&memories)?; |
| 2243 |
let mem = &self.memories[memory_index as usize]; |
| 2244 |
let f = if mem.memory64 { |
| 2245 |
u.choose(&choices64)? |
| 2246 |
} else { |
| 2247 |
u.choose(&choices32)? |
| 2248 |
}; |
| 2249 |
let mut offset = f(u, mem.minimum, init.len())?; |
| 2250 |
|
| 2251 |
// If traps are disallowed then truncate the size of the |
| 2252 |
// data segment to the minimum size of memory to guarantee |
| 2253 |
// it will fit. Afterwards ensure that the offset of the |
| 2254 |
// data segment is in-bounds by clamping it to the |
| 2255 |
if self.config.disallow_traps { |
| 2256 |
let max_size = (u64::MAX / 64 / 1024).min(mem.minimum) * 64 * 1024; |
| 2257 |
init.truncate(max_size as usize); |
| 2258 |
let max_offset = max_size - init.len() as u64; |
| 2259 |
match &mut offset { |
| 2260 |
Offset::Const32(x) => { |
| 2261 |
*x = (*x as u64).min(max_offset) as i32; |
| 2262 |
} |
| 2263 |
Offset::Const64(x) => { |
| 2264 |
*x = (*x as u64).min(max_offset) as i64; |
| 2265 |
} |
| 2266 |
Offset::Global(_) => unreachable!(), |
| 2267 |
} |
| 2268 |
} |
| 2269 |
DataSegmentKind::Active { |
| 2270 |
offset, |
| 2271 |
memory_index, |
| 2272 |
} |
| 2273 |
}; |
| 2274 |
self.data.push(DataSegment { kind, init }); |
| 2275 |
Ok(true) |
| 2276 |
}, |
| 2277 |
) |
| 2278 |
} |
| 2279 |
|
| 2280 |
fn params_results(&self, ty: &BlockType) -> (Vec<ValType>, Vec<ValType>) { |
| 2281 |
match ty { |
| 2282 |
BlockType::Empty => (vec![], vec![]), |
| 2283 |
BlockType::Result(t) => (vec![], vec![*t]), |
| 2284 |
BlockType::FunctionType(ty) => { |
| 2285 |
let ty = self.func_type(*ty); |
| 2286 |
(ty.params.to_vec(), ty.results.to_vec()) |
| 2287 |
} |
| 2288 |
} |
| 2289 |
} |
| 2290 |
|
| 2291 |
/// Returns an iterator of all globals which can be used in constant |
| 2292 |
/// expressions for a value of type `ty` specified. |
| 2293 |
fn globals_for_const_expr(&self, ty: ValType) -> impl Iterator<Item = u32> + '_ { |
| 2294 |
// Before the GC proposal only imported globals could be referenced, but |
| 2295 |
// the GC proposal relaxed this feature to allow any global. |
| 2296 |
let num_imported_globals = self.globals.len() - self.defined_globals.len(); |
| 2297 |
let max_global = if self.config.gc_enabled { |
| 2298 |
self.globals.len() |
| 2299 |
} else { |
| 2300 |
num_imported_globals |
| 2301 |
}; |
| 2302 |
|
| 2303 |
self.globals[..max_global] |
| 2304 |
.iter() |
| 2305 |
.enumerate() |
| 2306 |
.filter_map(move |(i, g)| { |
| 2307 |
// Mutable globals cannot participate in constant expressions, |
| 2308 |
// but otherwise so long as the global is a subtype of the |
| 2309 |
// desired type it's a candidate. |
| 2310 |
if !g.mutable && self.val_type_is_sub_type(g.val_type, ty) { |
| 2311 |
Some(i as u32) |
| 2312 |
} else { |
| 2313 |
None |
| 2314 |
} |
| 2315 |
}) |
| 2316 |
} |
| 2317 |
|
| 2318 |
fn compute_interesting_values(&mut self) { |
| 2319 |
debug_assert!(self.interesting_values32.is_empty()); |
| 2320 |
debug_assert!(self.interesting_values64.is_empty()); |
| 2321 |
|
| 2322 |
let mut interesting_values32 = HashSet::new(); |
| 2323 |
let mut interesting_values64 = HashSet::new(); |
| 2324 |
|
| 2325 |
let mut interesting = |val: u64| { |
| 2326 |
interesting_values32.insert(val as u32); |
| 2327 |
interesting_values64.insert(val); |
| 2328 |
}; |
| 2329 |
|
| 2330 |
// Zero is always interesting. |
| 2331 |
interesting(0); |
| 2332 |
|
| 2333 |
// Max values are always interesting. |
| 2334 |
interesting(u8::MAX as _); |
| 2335 |
interesting(u16::MAX as _); |
| 2336 |
interesting(u32::MAX as _); |
| 2337 |
interesting(u64::MAX); |
| 2338 |
|
| 2339 |
// Min values are always interesting. |
| 2340 |
interesting(i8::MIN as _); |
| 2341 |
interesting(i16::MIN as _); |
| 2342 |
interesting(i32::MIN as _); |
| 2343 |
interesting(i64::MIN as _); |
| 2344 |
|
| 2345 |
for i in 0..64 { |
| 2346 |
// Powers of two. |
| 2347 |
interesting(1 << i); |
| 2348 |
|
| 2349 |
// Inverted powers of two. |
| 2350 |
interesting(!(1 << i)); |
| 2351 |
|
| 2352 |
// Powers of two minus one, AKA high bits unset and low bits set. |
| 2353 |
interesting((1 << i) - 1); |
| 2354 |
|
| 2355 |
// Negative powers of two, AKA high bits set and low bits unset. |
| 2356 |
interesting(((1_i64 << 63) >> i) as _); |
| 2357 |
} |
| 2358 |
|
| 2359 |
// Some repeating bit patterns. |
| 2360 |
for pattern in [0b01010101, 0b00010001, 0b00010001, 0b00000001] { |
| 2361 |
for b in [pattern, !pattern] { |
| 2362 |
interesting(u64::from_ne_bytes([b, b, b, b, b, b, b, b])); |
| 2363 |
} |
| 2364 |
} |
| 2365 |
|
| 2366 |
// Interesting float values. |
| 2367 |
let mut interesting_f64 = |x: f64| interesting(x.to_bits()); |
| 2368 |
interesting_f64(0.0); |
| 2369 |
interesting_f64(-0.0); |
| 2370 |
interesting_f64(f64::INFINITY); |
| 2371 |
interesting_f64(f64::NEG_INFINITY); |
| 2372 |
interesting_f64(f64::EPSILON); |
| 2373 |
interesting_f64(-f64::EPSILON); |
| 2374 |
interesting_f64(f64::MIN); |
| 2375 |
interesting_f64(f64::MIN_POSITIVE); |
| 2376 |
interesting_f64(f64::MAX); |
| 2377 |
interesting_f64(f64::NAN); |
| 2378 |
let mut interesting_f32 = |x: f32| interesting(x.to_bits() as _); |
| 2379 |
interesting_f32(0.0); |
| 2380 |
interesting_f32(-0.0); |
| 2381 |
interesting_f32(f32::INFINITY); |
| 2382 |
interesting_f32(f32::NEG_INFINITY); |
| 2383 |
interesting_f32(f32::EPSILON); |
| 2384 |
interesting_f32(-f32::EPSILON); |
| 2385 |
interesting_f32(f32::MIN); |
| 2386 |
interesting_f32(f32::MIN_POSITIVE); |
| 2387 |
interesting_f32(f32::MAX); |
| 2388 |
interesting_f32(f32::NAN); |
| 2389 |
|
| 2390 |
// Interesting values related to table bounds. |
| 2391 |
for t in self.tables.iter() { |
| 2392 |
interesting(t.minimum as _); |
| 2393 |
if let Some(x) = t.minimum.checked_add(1) { |
| 2394 |
interesting(x as _); |
| 2395 |
} |
| 2396 |
|
| 2397 |
if let Some(x) = t.maximum { |
| 2398 |
interesting(x as _); |
| 2399 |
if let Some(y) = x.checked_add(1) { |
| 2400 |
interesting(y as _); |
| 2401 |
} |
| 2402 |
} |
| 2403 |
} |
| 2404 |
|
| 2405 |
// Interesting values related to memory bounds. |
| 2406 |
for m in self.memories.iter() { |
| 2407 |
let min = m.minimum.saturating_mul(crate::page_size(m).into()); |
| 2408 |
interesting(min); |
| 2409 |
for i in 0..5 { |
| 2410 |
if let Some(x) = min.checked_add(1 << i) { |
| 2411 |
interesting(x); |
| 2412 |
} |
| 2413 |
if let Some(x) = min.checked_sub(1 << i) { |
| 2414 |
interesting(x); |
| 2415 |
} |
| 2416 |
} |
| 2417 |
|
| 2418 |
if let Some(max) = m.maximum { |
| 2419 |
let max = max.saturating_mul(crate::page_size(m).into()); |
| 2420 |
interesting(max); |
| 2421 |
for i in 0..5 { |
| 2422 |
if let Some(x) = max.checked_add(1 << i) { |
| 2423 |
interesting(x); |
| 2424 |
} |
| 2425 |
if let Some(x) = max.checked_sub(1 << i) { |
| 2426 |
interesting(x); |
| 2427 |
} |
| 2428 |
} |
| 2429 |
} |
| 2430 |
} |
| 2431 |
|
| 2432 |
self.interesting_values32.extend(interesting_values32); |
| 2433 |
self.interesting_values64.extend(interesting_values64); |
| 2434 |
|
| 2435 |
// Sort for determinism. |
| 2436 |
self.interesting_values32.sort(); |
| 2437 |
self.interesting_values64.sort(); |
| 2438 |
} |
| 2439 |
|
| 2440 |
fn arbitrary_const_instruction( |
| 2441 |
&self, |
| 2442 |
ty: ValType, |
| 2443 |
u: &mut Unstructured<'_>, |
| 2444 |
) -> Result<Instruction> { |
| 2445 |
debug_assert!(self.interesting_values32.len() > 0); |
| 2446 |
debug_assert!(self.interesting_values64.len() > 0); |
| 2447 |
match ty { |
| 2448 |
ValType::I32 => Ok(Instruction::I32Const(if u.arbitrary()? { |
| 2449 |
*u.choose(&self.interesting_values32)? as i32 |
| 2450 |
} else { |
| 2451 |
u.arbitrary()? |
| 2452 |
})), |
| 2453 |
ValType::I64 => Ok(Instruction::I64Const(if u.arbitrary()? { |
| 2454 |
*u.choose(&self.interesting_values64)? as i64 |
| 2455 |
} else { |
| 2456 |
u.arbitrary()? |
| 2457 |
})), |
| 2458 |
ValType::F32 => Ok(Instruction::F32Const(if u.arbitrary()? { |
| 2459 |
f32::from_bits(*u.choose(&self.interesting_values32)?) |
| 2460 |
} else { |
| 2461 |
u.arbitrary()? |
| 2462 |
})), |
| 2463 |
ValType::F64 => Ok(Instruction::F64Const(if u.arbitrary()? { |
| 2464 |
f64::from_bits(*u.choose(&self.interesting_values64)?) |
| 2465 |
} else { |
| 2466 |
u.arbitrary()? |
| 2467 |
})), |
| 2468 |
ValType::V128 => Ok(Instruction::V128Const(if u.arbitrary()? { |
| 2469 |
let upper = (*u.choose(&self.interesting_values64)? as i128) << 64; |
| 2470 |
let lower = *u.choose(&self.interesting_values64)? as i128; |
| 2471 |
upper | lower |
| 2472 |
} else { |
| 2473 |
u.arbitrary()? |
| 2474 |
})), |
| 2475 |
ValType::Ref(ty) => { |
| 2476 |
assert!(ty.nullable); |
| 2477 |
Ok(Instruction::RefNull(ty.heap_type)) |
| 2478 |
} |
| 2479 |
} |
| 2480 |
} |
| 2481 |
} |
| 2482 |
|
| 2483 |
pub(crate) fn arbitrary_limits64( |
| 2484 |
u: &mut Unstructured, |
| 2485 |
min_minimum: Option<u64>, |
| 2486 |
max_minimum: u64, |
| 2487 |
max_required: bool, |
| 2488 |
max_inbounds: u64, |
| 2489 |
) -> Result<(u64, Option<u64>)> { |
| 2490 |
assert!( |
| 2491 |
min_minimum.unwrap_or(0) <= max_minimum, |
| 2492 |
"{} <= {max_minimum}", |
| 2493 |
min_minimum.unwrap_or(0), |
| 2494 |
); |
| 2495 |
assert!( |
| 2496 |
min_minimum.unwrap_or(0) <= max_inbounds, |
| 2497 |
"{} <= {max_inbounds}", |
| 2498 |
min_minimum.unwrap_or(0), |
| 2499 |
); |
| 2500 |
|
| 2501 |
let min = gradually_grow(u, min_minimum.unwrap_or(0), max_inbounds, max_minimum)?; |
| 2502 |
assert!(min <= max_minimum, "{min} <= {max_minimum}"); |
| 2503 |
|
| 2504 |
let max = if max_required || u.arbitrary().unwrap_or(false) { |
| 2505 |
Some(u.int_in_range(min..=max_minimum)?) |
| 2506 |
} else { |
| 2507 |
None |
| 2508 |
}; |
| 2509 |
assert!(min <= max.unwrap_or(min), "{min} <= {}", max.unwrap_or(min)); |
| 2510 |
|
| 2511 |
Ok((min, max)) |
| 2512 |
} |
| 2513 |
|
| 2514 |
pub(crate) fn configured_valtypes(config: &Config) -> Vec<ValType> { |
| 2515 |
let mut valtypes = Vec::with_capacity(25); |
| 2516 |
valtypes.push(ValType::I32); |
| 2517 |
valtypes.push(ValType::I64); |
| 2518 |
if config.allow_floats { |
| 2519 |
valtypes.push(ValType::F32); |
| 2520 |
valtypes.push(ValType::F64); |
| 2521 |
} |
| 2522 |
if config.simd_enabled { |
| 2523 |
valtypes.push(ValType::V128); |
| 2524 |
} |
| 2525 |
if config.gc_enabled && config.reference_types_enabled { |
| 2526 |
for nullable in [ |
| 2527 |
// TODO: For now, only create allow nullable reference |
| 2528 |
// types. Eventually we should support non-nullable reference types, |
| 2529 |
// but this means that we will also need to recognize when it is |
| 2530 |
// impossible to create an instance of the reference (eg `(ref |
| 2531 |
// nofunc)` has no instances, and self-referential types that |
| 2532 |
// contain a non-null self-reference are also impossible to create). |
| 2533 |
true, |
| 2534 |
] { |
| 2535 |
use AbstractHeapType::*; |
| 2536 |
for ty in [ |
| 2537 |
Any, Eq, I31, Array, Struct, None, Func, NoFunc, Extern, NoExtern, |
| 2538 |
] { |
| 2539 |
valtypes.push(ValType::Ref(RefType { |
| 2540 |
nullable, |
| 2541 |
// TODO: handle shared |
| 2542 |
heap_type: HeapType::Abstract { shared: false, ty }, |
| 2543 |
})); |
| 2544 |
} |
| 2545 |
} |
| 2546 |
} else if config.reference_types_enabled { |
| 2547 |
valtypes.push(ValType::EXTERNREF); |
| 2548 |
valtypes.push(ValType::FUNCREF); |
| 2549 |
} |
| 2550 |
valtypes |
| 2551 |
} |
| 2552 |
|
| 2553 |
pub(crate) fn arbitrary_table_type( |
| 2554 |
u: &mut Unstructured, |
| 2555 |
config: &Config, |
| 2556 |
module: Option<&Module>, |
| 2557 |
) -> Result<TableType> { |
| 2558 |
let table64 = config.memory64_enabled && u.arbitrary()?; |
| 2559 |
// We don't want to generate tables that are too large on average, so |
| 2560 |
// keep the "inbounds" limit here a bit smaller. |
| 2561 |
let max_inbounds = 10_000; |
| 2562 |
let min_elements = if config.disallow_traps { Some(1) } else { None }; |
| 2563 |
let max_elements = min_elements.unwrap_or(0).max(config.max_table_elements); |
| 2564 |
let (minimum, maximum) = arbitrary_limits64( |
| 2565 |
u, |
| 2566 |
min_elements, |
| 2567 |
max_elements, |
| 2568 |
config.table_max_size_required, |
| 2569 |
max_inbounds.min(max_elements), |
| 2570 |
)?; |
| 2571 |
if config.disallow_traps { |
| 2572 |
assert!(minimum > 0); |
| 2573 |
} |
| 2574 |
let element_type = match module { |
| 2575 |
Some(module) => module.arbitrary_ref_type(u)?, |
| 2576 |
None => RefType::FUNCREF, |
| 2577 |
}; |
| 2578 |
Ok(TableType { |
| 2579 |
element_type, |
| 2580 |
minimum, |
| 2581 |
maximum, |
| 2582 |
table64, |
| 2583 |
shared: false, // TODO: handle shared |
| 2584 |
}) |
| 2585 |
} |
| 2586 |
|
| 2587 |
pub(crate) fn arbitrary_memtype(u: &mut Unstructured, config: &Config) -> Result<MemoryType> { |
| 2588 |
// When threads are enabled, we only want to generate shared memories about |
| 2589 |
// 25% of the time. |
| 2590 |
let shared = config.threads_enabled && u.ratio(1, 4)?; |
| 2591 |
|
| 2592 |
let memory64 = config.memory64_enabled && u.arbitrary()?; |
| 2593 |
let page_size_log2 = if config.custom_page_sizes_enabled && u.arbitrary()? { |
| 2594 |
Some(if u.arbitrary()? { 0 } else { 16 }) |
| 2595 |
} else { |
| 2596 |
None |
| 2597 |
}; |
| 2598 |
|
| 2599 |
let min_pages = if config.disallow_traps { Some(1) } else { None }; |
| 2600 |
let max_pages = min_pages.unwrap_or(0).max(if memory64 { |
| 2601 |
u64::try_from(config.max_memory64_bytes >> page_size_log2.unwrap_or(16)) |
| 2602 |
// Can only fail when we have a custom page size of 1 byte and a |
| 2603 |
// memory size of `2**64 == u64::MAX + 1`. In this case, just |
| 2604 |
// saturate to `u64::MAX`. |
| 2605 |
.unwrap_or(u64::MAX as u64) |
| 2606 |
} else { |
| 2607 |
u32::try_from(config.max_memory32_bytes >> page_size_log2.unwrap_or(16)) |
| 2608 |
// Similar case as above, but while we could represent `2**32` in our |
| 2609 |
// `u64` here, 32-bit memories' limits must fit in a `u32`. |
| 2610 |
.unwrap_or(u32::MAX) |
| 2611 |
.into() |
| 2612 |
}); |
| 2613 |
|
| 2614 |
// We want to favor keeping the total memories <= 1gb in size. |
| 2615 |
let max_all_mems_in_bytes = 1 << 30; |
| 2616 |
let max_this_mem_in_bytes = max_all_mems_in_bytes / u64::try_from(config.max_memories).unwrap(); |
| 2617 |
let max_inbounds = max_this_mem_in_bytes >> page_size_log2.unwrap_or(16); |
| 2618 |
let max_inbounds = max_inbounds.clamp(min_pages.unwrap_or(0), max_pages); |
| 2619 |
|
| 2620 |
let (minimum, maximum) = arbitrary_limits64( |
| 2621 |
u, |
| 2622 |
min_pages, |
| 2623 |
max_pages, |
| 2624 |
config.memory_max_size_required || shared, |
| 2625 |
max_inbounds, |
| 2626 |
)?; |
| 2627 |
|
| 2628 |
Ok(MemoryType { |
| 2629 |
minimum, |
| 2630 |
maximum, |
| 2631 |
memory64, |
| 2632 |
shared, |
| 2633 |
page_size_log2, |
| 2634 |
}) |
| 2635 |
} |
| 2636 |
|
| 2637 |
pub(crate) fn arbitrary_tag_type( |
| 2638 |
u: &mut Unstructured, |
| 2639 |
candidate_func_types: &[u32], |
| 2640 |
get_func_type: impl FnOnce(u32) -> Rc<FuncType>, |
| 2641 |
) -> Result<TagType> { |
| 2642 |
let max = candidate_func_types.len() - 1; |
| 2643 |
let ty = candidate_func_types[u.int_in_range(0..=max)?]; |
| 2644 |
Ok(TagType { |
| 2645 |
func_type_idx: ty, |
| 2646 |
func_type: get_func_type(ty), |
| 2647 |
}) |
| 2648 |
} |
| 2649 |
|
| 2650 |
/// This function generates a number between `min` and `max`, favoring values |
| 2651 |
/// between `min` and `max_inbounds`. |
| 2652 |
/// |
| 2653 |
/// The thinking behind this function is that it's used for things like offsets |
| 2654 |
/// and minimum sizes which, when very large, can trivially make the wasm oom or |
| 2655 |
/// abort with a trap. This isn't the most interesting thing to do so it tries |
| 2656 |
/// to favor numbers in the `min..max_inbounds` range to avoid immediate ooms. |
| 2657 |
fn gradually_grow(u: &mut Unstructured, min: u64, max_inbounds: u64, max: u64) -> Result<u64> { |
| 2658 |
if min == max { |
| 2659 |
return Ok(min); |
| 2660 |
} |
| 2661 |
let x = { |
| 2662 |
let min = min as f64; |
| 2663 |
let max = max as f64; |
| 2664 |
let max_inbounds = max_inbounds as f64; |
| 2665 |
let x = u.arbitrary::<u32>()?; |
| 2666 |
let x = f64::from(x); |
| 2667 |
let x = map_custom( |
| 2668 |
x, |
| 2669 |
f64::from(u32::MIN)..f64::from(u32::MAX), |
| 2670 |
min..max_inbounds, |
| 2671 |
min..max, |
| 2672 |
); |
| 2673 |
assert!(min <= x, "{min} <= {x}"); |
| 2674 |
assert!(x <= max, "{x} <= {max}"); |
| 2675 |
x.round() as u64 |
| 2676 |
}; |
| 2677 |
|
| 2678 |
// Conversion between `u64` and `f64` is lossy, especially for large |
| 2679 |
// numbers, so just clamp the final result. |
| 2680 |
return Ok(x.clamp(min, max)); |
| 2681 |
|
| 2682 |
/// Map a value from within the input range to the output range(s). |
| 2683 |
/// |
| 2684 |
/// This will first map the input range into the `0..1` input range, and |
| 2685 |
/// then depending on the value it will either map it exponentially |
| 2686 |
/// (favoring small values) into the `output_inbounds` range or it will map |
| 2687 |
/// it into the `output` range. |
| 2688 |
fn map_custom( |
| 2689 |
value: f64, |
| 2690 |
input: Range<f64>, |
| 2691 |
output_inbounds: Range<f64>, |
| 2692 |
output: Range<f64>, |
| 2693 |
) -> f64 { |
| 2694 |
assert!(!value.is_nan(), "{}", value); |
| 2695 |
assert!(value.is_finite(), "{}", value); |
| 2696 |
assert!(input.start < input.end, "{} < {}", input.start, input.end); |
| 2697 |
assert!( |
| 2698 |
output.start < output.end, |
| 2699 |
"{} < {}", |
| 2700 |
output.start, |
| 2701 |
output.end |
| 2702 |
); |
| 2703 |
assert!(value >= input.start, "{} >= {}", value, input.start); |
| 2704 |
assert!(value <= input.end, "{} <= {}", value, input.end); |
| 2705 |
assert!( |
| 2706 |
output.start <= output_inbounds.start, |
| 2707 |
"{} <= {}", |
| 2708 |
output.start, |
| 2709 |
output_inbounds.start |
| 2710 |
); |
| 2711 |
assert!( |
| 2712 |
output_inbounds.end <= output.end, |
| 2713 |
"{} <= {}", |
| 2714 |
output_inbounds.end, |
| 2715 |
output.end |
| 2716 |
); |
| 2717 |
|
| 2718 |
let x = map_linear(value, input, 0.0..1.0); |
| 2719 |
let result = if x < PCT_INBOUNDS { |
| 2720 |
if output_inbounds.start == output_inbounds.end { |
| 2721 |
output_inbounds.start |
| 2722 |
} else { |
| 2723 |
let unscaled = x * x * x * x * x * x; |
| 2724 |
map_linear(unscaled, 0.0..1.0, output_inbounds) |
| 2725 |
} |
| 2726 |
} else { |
| 2727 |
map_linear(x, 0.0..1.0, output.clone()) |
| 2728 |
}; |
| 2729 |
|
| 2730 |
assert!(result >= output.start, "{} >= {}", result, output.start); |
| 2731 |
assert!(result <= output.end, "{} <= {}", result, output.end); |
| 2732 |
result |
| 2733 |
} |
| 2734 |
|
| 2735 |
/// Map a value from within the input range linearly to the output range. |
| 2736 |
/// |
| 2737 |
/// For example, mapping `0.5` from the input range `0.0..1.0` to the output |
| 2738 |
/// range `1.0..3.0` produces `2.0`. |
| 2739 |
fn map_linear( |
| 2740 |
value: f64, |
| 2741 |
Range { |
| 2742 |
start: in_low, |
| 2743 |
end: in_high, |
| 2744 |
}: Range<f64>, |
| 2745 |
Range { |
| 2746 |
start: out_low, |
| 2747 |
end: out_high, |
| 2748 |
}: Range<f64>, |
| 2749 |
) -> f64 { |
| 2750 |
assert!(!value.is_nan(), "{}", value); |
| 2751 |
assert!(value.is_finite(), "{}", value); |
| 2752 |
assert!(in_low < in_high, "{} < {}", in_low, in_high); |
| 2753 |
assert!(out_low < out_high, "{} < {}", out_low, out_high); |
| 2754 |
assert!(value >= in_low, "{} >= {}", value, in_low); |
| 2755 |
assert!(value <= in_high, "{} <= {}", value, in_high); |
| 2756 |
|
| 2757 |
let dividend = out_high - out_low; |
| 2758 |
let divisor = in_high - in_low; |
| 2759 |
let slope = dividend / divisor; |
| 2760 |
let result = out_low + (slope * (value - in_low)); |
| 2761 |
|
| 2762 |
assert!(result >= out_low, "{} >= {}", result, out_low); |
| 2763 |
assert!(result <= out_high, "{} <= {}", result, out_high); |
| 2764 |
result |
| 2765 |
} |
| 2766 |
} |
| 2767 |
|
| 2768 |
/// Selects a reasonable offset for an element or data segment. This favors |
| 2769 |
/// having the segment being in-bounds, but it may still generate |
| 2770 |
/// any offset. |
| 2771 |
fn arbitrary_offset( |
| 2772 |
u: &mut Unstructured, |
| 2773 |
limit_min: u64, |
| 2774 |
limit_max: u64, |
| 2775 |
segment_size: usize, |
| 2776 |
) -> Result<u64> { |
| 2777 |
let size = u64::try_from(segment_size).unwrap(); |
| 2778 |
|
| 2779 |
// If the segment is too big for the whole memory, just give it any |
| 2780 |
// offset. |
| 2781 |
if size > limit_min { |
| 2782 |
u.int_in_range(0..=limit_max) |
| 2783 |
} else { |
| 2784 |
gradually_grow(u, 0, limit_min - size, limit_max) |
| 2785 |
} |
| 2786 |
} |
| 2787 |
|
| 2788 |
fn unique_import_strings(max_size: usize, u: &mut Unstructured) -> Result<(String, String)> { |
| 2789 |
let module = limited_string(max_size, u)?; |
| 2790 |
let field = limited_string(max_size, u)?; |
| 2791 |
Ok((module, field)) |
| 2792 |
} |
| 2793 |
|
| 2794 |
fn arbitrary_vec_u8(u: &mut Unstructured) -> Result<Vec<u8>> { |
| 2795 |
let size = u.arbitrary_len::<u8>()?; |
| 2796 |
Ok(u.bytes(size)?.to_vec()) |
| 2797 |
} |
| 2798 |
|
| 2799 |
impl EntityType { |
| 2800 |
fn size(&self) -> u32 { |
| 2801 |
match self { |
| 2802 |
EntityType::Tag(_) |
| 2803 |
| EntityType::Global(_) |
| 2804 |
| EntityType::Table(_) |
| 2805 |
| EntityType::Memory(_) => 1, |
| 2806 |
EntityType::Func(_, ty) => 1 + (ty.params.len() + ty.results.len()) as u32, |
| 2807 |
} |
| 2808 |
} |
| 2809 |
} |
| 2810 |
|
| 2811 |
/// A container for the kinds of instructions that wasm-smith is allowed to |
| 2812 |
/// emit. |
| 2813 |
/// |
| 2814 |
/// # Example |
| 2815 |
/// |
| 2816 |
/// ``` |
| 2817 |
/// # use wasm_smith::{InstructionKinds, InstructionKind}; |
| 2818 |
/// let kinds = InstructionKinds::new(&[InstructionKind::Numeric, InstructionKind::Memory]); |
| 2819 |
/// assert!(kinds.contains(InstructionKind::Memory)); |
| 2820 |
/// ``` |
| 2821 |
#[derive(Clone, Copy, Debug, Default)] |
| 2822 |
#[cfg_attr(feature = "serde_derive", derive(serde_derive::Deserialize))] |
| 2823 |
pub struct InstructionKinds(pub(crate) FlagSet<InstructionKind>); |
| 2824 |
|
| 2825 |
impl InstructionKinds { |
| 2826 |
/// Create a new container. |
| 2827 |
pub fn new(kinds: &[InstructionKind]) -> Self { |
| 2828 |
Self(kinds.iter().fold(FlagSet::default(), |ks, k| ks | *k)) |
| 2829 |
} |
| 2830 |
|
| 2831 |
/// Include all [InstructionKind]s. |
| 2832 |
pub fn all() -> Self { |
| 2833 |
Self(FlagSet::full()) |
| 2834 |
} |
| 2835 |
|
| 2836 |
/// Include no [InstructionKind]s. |
| 2837 |
pub fn none() -> Self { |
| 2838 |
Self(FlagSet::default()) |
| 2839 |
} |
| 2840 |
|
| 2841 |
/// Check if the [InstructionKind] is contained in this set. |
| 2842 |
#[inline] |
| 2843 |
pub fn contains(&self, kind: InstructionKind) -> bool { |
| 2844 |
self.0.contains(kind) |
| 2845 |
} |
| 2846 |
|
| 2847 |
/// Restrict each [InstructionKind] to its subset not involving floats |
| 2848 |
pub fn without_floats(&self) -> Self { |
| 2849 |
let mut floatless = self.0; |
| 2850 |
if floatless.contains(InstructionKind::Numeric) { |
| 2851 |
floatless -= InstructionKind::Numeric; |
| 2852 |
floatless |= InstructionKind::NumericInt; |
| 2853 |
} |
| 2854 |
if floatless.contains(InstructionKind::Vector) { |
| 2855 |
floatless -= InstructionKind::Vector; |
| 2856 |
floatless |= InstructionKind::VectorInt; |
| 2857 |
} |
| 2858 |
if floatless.contains(InstructionKind::Memory) { |
| 2859 |
floatless -= InstructionKind::Memory; |
| 2860 |
floatless |= InstructionKind::MemoryInt; |
| 2861 |
} |
| 2862 |
Self(floatless) |
| 2863 |
} |
| 2864 |
} |
| 2865 |
|
| 2866 |
flags! { |
| 2867 |
/// Enumerate the categories of instructions defined in the [WebAssembly |
| 2868 |
/// specification](https://webassembly.github.io/spec/core/syntax/instructions.html). |
| 2869 |
#[allow(missing_docs)] |
| 2870 |
#[cfg_attr(feature = "_internal_cli", derive(serde_derive::Deserialize))] |
| 2871 |
pub enum InstructionKind: u16 { |
| 2872 |
NumericInt = 1 << 0, |
| 2873 |
Numeric = (1 << 1) | (1 << 0), |
| 2874 |
VectorInt = 1 << 2, |
| 2875 |
Vector = (1 << 3) | (1 << 2), |
| 2876 |
Reference = 1 << 4, |
| 2877 |
Parametric = 1 << 5, |
| 2878 |
Variable = 1 << 6, |
| 2879 |
Table = 1 << 7, |
| 2880 |
MemoryInt = 1 << 8, |
| 2881 |
Memory = (1 << 9) | (1 << 8), |
| 2882 |
Control = 1 << 10, |
| 2883 |
Aggregate = 1 << 11, |
| 2884 |
} |
| 2885 |
} |
| 2886 |
|
| 2887 |
impl FromStr for InstructionKinds { |
| 2888 |
type Err = String; |
| 2889 |
fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> { |
| 2890 |
let mut kinds = vec![]; |
| 2891 |
for part in s.split(",") { |
| 2892 |
let kind = InstructionKind::from_str(part)?; |
| 2893 |
kinds.push(kind); |
| 2894 |
} |
| 2895 |
Ok(InstructionKinds::new(&kinds)) |
| 2896 |
} |
| 2897 |
} |
| 2898 |
|
| 2899 |
impl FromStr for InstructionKind { |
| 2900 |
type Err = String; |
| 2901 |
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { |
| 2902 |
match s.to_lowercase().as_str() { |
| 2903 |
"numeric_non_float" => Ok(InstructionKind::NumericInt), |
| 2904 |
"numeric" => Ok(InstructionKind::Numeric), |
| 2905 |
"vector_non_float" => Ok(InstructionKind::VectorInt), |
| 2906 |
"vector" => Ok(InstructionKind::Vector), |
| 2907 |
"reference" => Ok(InstructionKind::Reference), |
| 2908 |
"parametric" => Ok(InstructionKind::Parametric), |
| 2909 |
"variable" => Ok(InstructionKind::Variable), |
| 2910 |
"table" => Ok(InstructionKind::Table), |
| 2911 |
"memory_non_float" => Ok(InstructionKind::MemoryInt), |
| 2912 |
"memory" => Ok(InstructionKind::Memory), |
| 2913 |
"control" => Ok(InstructionKind::Control), |
| 2914 |
_ => Err(format!("unknown instruction kind: {}", s)), |
| 2915 |
} |
| 2916 |
} |
| 2917 |
} |