Debian Codegraph @

crates/wasm-mutate/src/mutators/rename_export.rs

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //! Mutator that generates a random renaming of a preexisting export
2 use super::Mutator;
3 use crate::{Result, WasmMutate};
4 use rand::Rng;
5 use wasm_encoder::{ExportKind, ExportSection, Module};
6 use wasmparser::ExportSectionReader;
7
8 /// Generates a random renaming of pre-existing exports.
9 ///
10 /// The export entry is selected randomly and then a new `field` name is
11 /// generated.
12 #[derive(Clone, Copy)]
13 pub struct RenameExportMutator {
14 /// The maximum length of the generated export entry
15 pub max_name_size: usize,
16 }
17
18 impl RenameExportMutator {
19 /// Copied and transformed from wasm-smith name generation
20 fn limited_string(&self, config: &mut WasmMutate, original: &str) -> crate::Result<String> {
21 loop {
22 config.consume_fuel(1)?;
23 let mut bytes = original.as_bytes().to_vec();
24 config.raw_mutate(&mut bytes, self.max_name_size)?;
25
26 match std::str::from_utf8(&bytes) {
27 Ok(_) => {}
28 Err(e) => {
29 let i = e.valid_up_to();
30 bytes.drain(i..);
31 }
32 };
33 if bytes.len() > self.max_name_size {
34 continue;
35 }
36 let ret = String::from_utf8(bytes).unwrap();
37 if ret != original && config.info().export_names.contains(&ret) {
38 continue;
39 }
40 return Ok(ret);
41 }
42 }
43 }
44
45 impl Mutator for RenameExportMutator {
46 fn mutate<'a>(
47 &self,
48 config: &'a mut WasmMutate,
49 ) -> Result<Box<dyn Iterator<Item = Result<Module>> + 'a>> {
50 let mut exports = ExportSection::new();
51 let exports_idx = config.info().exports.unwrap();
52 let reader = config.info().get_binary_reader(exports_idx);
53 let reader = ExportSectionReader::new(reader)?;
54 let max_exports = u64::from(reader.count());
55 let skip_at = config.rng().random_range(0..max_exports);
56
57 for (i, export) in reader.into_iter().enumerate() {
58 let export = export?;
59 config.consume_fuel(1)?;
60
61 let new_name = if skip_at != i as u64 {
62 // otherwise bypass
63 String::from(export.name)
64 } else {
65 let new_name = self.limited_string(config, export.name)?;
66 log::debug!("Renaming export {export:?} by {new_name:?}");
67 new_name
68 };
69
70 match export.kind {
71 wasmparser::ExternalKind::Func => {
72 exports.export(new_name.as_str(), ExportKind::Func, export.index);
73 }
74 wasmparser::ExternalKind::Table => {
75 exports.export(new_name.as_str(), ExportKind::Table, export.index);
76 }
77 wasmparser::ExternalKind::Memory => {
78 exports.export(new_name.as_str(), ExportKind::Memory, export.index);
79 }
80 wasmparser::ExternalKind::Global => {
81 exports.export(new_name.as_str(), ExportKind::Global, export.index);
82 }
83 _ => {
84 panic!("Unknown export {export:?}")
85 }
86 }
87 }
88 Ok(Box::new(std::iter::once(Ok(config
89 .info()
90 .replace_section(
91 config.info().exports.unwrap(),
92 &exports,
93 )))))
94 }
95
96 fn can_mutate<'a>(&self, config: &'a WasmMutate) -> bool {
97 !config.preserve_semantics && config.info().has_exports() && config.info().exports_count > 0
98 }
99 }
100
101 #[cfg(test)]
102 mod tests {
103 use super::RenameExportMutator;
104 use crate::WasmMutate;
105 use std::sync::Arc;
106
107 #[test]
108 fn test_rename_export_mutator() {
109 // From https://developer.mozilla.org/en-US/docs/WebAssembly/Text_format_to_wasm
110
111 let mut config = WasmMutate::default();
112 config.raw_mutate_func(Some(Arc::new(|data, _| {
113 assert_eq!(data, b"exported_func");
114 *data = Vec::new();
115 Ok(())
116 })));
117 config.match_mutation(
118 r#"
119 (module
120 (func (export "exported_func") (result i32)
121 i32.const 42
122 )
123 )
124 "#,
125 RenameExportMutator { max_name_size: 2 }, // the string is empty,
126 r#"(module
127 (type (;0;) (func (result i32)))
128 (func (;0;) (type 0) (result i32)
129 i32.const 42)
130 (export "" (func 0)))"#,
131 );
132 }
133 }