| 1 |
//! Mutator that removes a random preexisting export |
| 2 |
|
| 3 |
use super::Mutator; |
| 4 |
use crate::{Result, WasmMutate}; |
| •5 |
use rand::RngExt; |
| 6 |
use wasm_encoder::{ExportKind, ExportSection, Module}; |
| 7 |
use wasmparser::ExportSectionReader; |
| 8 |
|
| 9 |
/// Mutator that removes a random preexisting export |
| 10 |
#[derive(Clone, Copy)] |
| 11 |
pub struct RemoveExportMutator; |
| 12 |
|
| 13 |
impl Mutator for RemoveExportMutator { |
| 14 |
fn mutate<'a>( |
| 15 |
&self, |
| 16 |
config: &'a mut WasmMutate, |
| 17 |
) -> Result<Box<dyn Iterator<Item = Result<Module>> + 'a>> { |
| 18 |
let mut exports = ExportSection::new(); |
| 19 |
let exports_idx = config.info().exports.unwrap(); |
| 20 |
let reader = config.info().get_binary_reader(exports_idx); |
| 21 |
let reader = ExportSectionReader::new(reader)?; |
| 22 |
let max_exports = u64::from(reader.count()); |
| 23 |
let skip_at = config.rng().random_range(0..max_exports); |
| 24 |
|
| 25 |
for (i, export) in reader.into_iter().enumerate() { |
| 26 |
let export = export?; |
| 27 |
config.consume_fuel(1)?; |
| 28 |
|
| 29 |
if skip_at == i as u64 { |
| 30 |
log::trace!("Removing export {export:?} at index {skip_at}"); |
| 31 |
continue; |
| 32 |
} |
| 33 |
|
| 34 |
match export.kind { |
| 35 |
wasmparser::ExternalKind::Func => { |
| 36 |
exports.export(export.name, ExportKind::Func, export.index); |
| 37 |
} |
| 38 |
wasmparser::ExternalKind::Table => { |
| 39 |
exports.export(export.name, ExportKind::Table, export.index); |
| 40 |
} |
| 41 |
wasmparser::ExternalKind::Memory => { |
| 42 |
exports.export(export.name, ExportKind::Memory, export.index); |
| 43 |
} |
| 44 |
wasmparser::ExternalKind::Global => { |
| 45 |
exports.export(export.name, ExportKind::Global, export.index); |
| 46 |
} |
| 47 |
_ => { |
| 48 |
panic!("Unknown export {export:?}") |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
Ok(Box::new(std::iter::once(Ok(config |
| 54 |
.info() |
| 55 |
.replace_section( |
| 56 |
config.info().exports.unwrap(), |
| 57 |
&exports, |
| 58 |
))))) |
| 59 |
} |
| 60 |
|
| 61 |
fn can_mutate<'a>(&self, config: &'a WasmMutate) -> bool { |
| 62 |
!config.preserve_semantics && config.info().has_exports() && config.info().exports_count > 0 |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
#[cfg(test)] |
| 67 |
mod tests { |
| 68 |
use super::RemoveExportMutator; |
| 69 |
|
| 70 |
#[test] |
| 71 |
fn test_remove_export_mutator() { |
| 72 |
crate::mutators::match_mutation( |
| 73 |
r#" |
| 74 |
(module |
| 75 |
(func (export "exported_func") (result i32) |
| 76 |
i32.const 42 |
| 77 |
) |
| 78 |
) |
| 79 |
"#, |
| 80 |
RemoveExportMutator, |
| 81 |
r#" |
| 82 |
(module (type (;0;) |
| 83 |
(func (result i32))) |
| 84 |
(func (;0;) (type 0) (result i32) |
| 85 |
i32.const 42))"#, |
| 86 |
); |
| 87 |
} |
| 88 |
} |