Debian Codegraph @

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

raw ◀ ▶
1 Debian patch touch this file
1 //! This mutator modifies the constant initializer expressions between various valid forms in
2 //! entities which require constant initializers.
3
4 use crate::{Error, Mutator, ReencodeResult};
•5 use rand::RngExt;
6 use wasm_encoder::reencode::{self, Reencode, RoundtripReencoder};
7 use wasm_encoder::{ElementSection, GlobalSection};
8 use wasmparser::{ConstExpr, ElementSectionReader, GlobalSectionReader};
9
10 #[derive(PartialEq, Copy, Clone)]
11 pub enum ConstExpressionMutator {
12 Global,
13 ElementOffset,
14 ElementFunc,
15 }
16
17 struct InitTranslator<'cfg, 'wasm> {
18 config: &'cfg mut crate::WasmMutate<'wasm>,
19 skip_inits: u32,
20 kind: ConstExpressionMutator,
21 }
22
23 impl<'cfg, 'wasm> InitTranslator<'cfg, 'wasm> {
24 /// Reduces the expression skip counter by 1 and indicates whether the current expression
25 /// should be processed.
26 ///
27 /// If current expression ought to be modified, this function will return `true`.
28 fn should_process(&mut self) -> bool {
29 // NB: by wrapping the counter here we ensure that we usually apply just one transformation
30 // during a walk of a WASM module, because we'd need to skip u32::MAX initializers once we
31 // apply the first transformation.
32 let (new_counter, was_zero) = self.skip_inits.overflowing_sub(1);
33 self.skip_inits = new_counter;
34 was_zero
35 }
36 }
37
38 impl<'cfg, 'wasm> Reencode for InitTranslator<'cfg, 'wasm> {
39 type Error = Error;
40
41 /// Handle `elem`s with values of the `ElementItem::Func` kind. This function will not be
42 /// called for values of the `ElementItem::Expr` kind.
43 fn function_index(&mut self, idx: u32) -> ReencodeResult<u32> {
44 if self.kind != ConstExpressionMutator::ElementFunc || !self.should_process() {
45 return Ok(idx);
46 }
47
48 log::trace!("... replacing referenced function index with 0");
49 // FIXME: generate random function indices when `!config.reduce`.
50 Ok(0)
51 }
52
53 /// Handle `global` initializers and `elem`s with values of the `ElementItem::Expr` kind.
54 ///
55 /// This function will not be called for `elem` values of the `ElementItem::Func` kind.
56 fn const_expr(&mut self, e: ConstExpr<'_>) -> ReencodeResult<wasm_encoder::ConstExpr> {
57 use crate::module::PrimitiveTypeInfo as T;
58 use wasm_encoder::ConstExpr as CE;
59 use wasmparser::Operator as O;
60
61 if !self.should_process() {
62 return reencode::utils::const_expr(self, e);
63 }
64
65 let mut reader = e.get_operators_reader();
66
67 if !self.config.reduce {
68 // FIXME: implement non-reducing mutations for constant expressions.
69 return Err(reencode::Error::UserError(Error::no_mutations_applicable()));
70 }
71
72 let op = reader.read()?;
73
74 // Don't mutate further if the expressions are already their most reduced form.
75 let is_simplest = match op {
76 O::RefNull { .. } | O::I32Const { value: 0 | 1 } | O::I64Const { value: 0 | 1 } => true,
77 O::F32Const { value } => value.bits() == 0,
78 O::F64Const { value } => value.bits() == 0,
79 O::V128Const { value } => value.i128() == 0,
80 _ => false,
81 };
82 if is_simplest {
83 return Err(reencode::Error::UserError(Error::no_mutations_applicable()));
84 }
85
86 let ty = match op {
87 O::I32Const { .. } => T::I32,
88 O::I64Const { .. } => T::I64,
89 O::V128Const { .. } => T::V128,
90 O::F32Const { .. } => T::F32,
91 O::F64Const { .. } => T::F64,
92 O::RefFunc { .. }
93 | O::RefNull {
94 hty: wasmparser::HeapType::FUNC,
95 } => T::FuncRef,
96 O::RefNull {
97 hty: wasmparser::HeapType::EXTERN,
98 } => T::ExternRef,
99 O::GlobalGet { global_index } => self.config.info().global_types[global_index as usize],
100 other => {
101 log::info!("unsupported opcode in init expr {other:?}");
102 return Err(reencode::Error::UserError(Error::no_mutations_applicable()));
103 }
104 };
105
106 // For globals give a 25% chance to produce a const with 0 value
107 // (arguably the simplest representation) to give a chance to
108 // quickly discover this final reduction if it is in fact
109 // applicable.
110 //
111 // For element offsets always generate `i32.const 0` (effectively
112 // removing the offset) as other values may not necessarily be valid
113 // (e.g. maximum table size is limited)
114 let is_element_offset = matches!(self.kind, ConstExpressionMutator::ElementOffset);
115 let should_zero = is_element_offset || self.config.rng().random::<u8>() & 0b11 == 0;
116 let new_op = match ty {
117 T::I32 if should_zero => CE::i32_const(0),
118 T::I64 if should_zero => CE::i64_const(0),
119 T::V128 if should_zero => CE::v128_const(0),
120 T::F32 if should_zero => CE::f32_const(0.0.into()),
121 T::F64 if should_zero => CE::f64_const(0.0.into()),
122 T::I32 => CE::i32_const(if let O::I32Const { value } = op {
123 let range = if value < 0 { value..0 } else { 0..value };
124 self.config.rng().random_range(range)
125 } else {
126 self.config.rng().random()
127 }),
128 T::I64 => CE::i64_const(if let O::I64Const { value } = op {
129 let range = if value < 0 { value..0 } else { 0..value };
130 self.config.rng().random_range(range)
131 } else {
132 self.config.rng().random()
133 }),
134 T::V128 => CE::v128_const(if let O::V128Const { value } = op {
135 self.config.rng().random_range(0..value.i128() as u128) as i128
136 } else {
137 self.config.rng().random()
138 }),
139 T::F32 => CE::f32_const(if let O::F32Const { value } = op {
140 (f32::from_bits(value.bits()) / 2.0).into()
141 } else {
142 f32::from_bits(self.config.rng().random()).into()
143 }),
144 T::F64 => CE::f64_const(if let O::F64Const { value } = op {
145 (f64::from_bits(value.bits()) / 2.0).into()
146 } else {
147 f64::from_bits(self.config.rng().random()).into()
148 }),
149 T::FuncRef => CE::ref_null(wasm_encoder::HeapType::FUNC),
150 T::ExternRef => CE::ref_null(wasm_encoder::HeapType::EXTERN),
151 T::Empty => unreachable!(),
152 };
153 log::trace!("... replacing original expression with {new_op:?}");
154 Ok(new_op)
155 }
156 }
157
158 impl Mutator for ConstExpressionMutator {
159 fn mutate<'a>(
160 &self,
161 config: &'a mut crate::WasmMutate,
162 ) -> crate::Result<Box<dyn Iterator<Item = crate::Result<wasm_encoder::Module>> + 'a>> {
163 let skip_err = Error::no_mutations_applicable();
164 match self {
165 Self::Global => {
166 let num_total = config.info().num_local_globals();
167 let mutate_idx = config.rng().random_range(0..num_total);
168 let section = config.info().globals.ok_or(skip_err)?;
169 let mut new_section = GlobalSection::new();
170 let reader = config.info().get_binary_reader(section);
171 let reader = GlobalSectionReader::new(reader)?;
172 let mut translator = InitTranslator {
173 config,
174 skip_inits: 0,
175 kind: *self,
176 };
177 for (idx, global) in reader.into_iter().enumerate() {
178 translator.config.consume_fuel(1)?;
179 let global = global?;
180 if idx as u32 == mutate_idx {
181 log::trace!("Modifying global at index {idx}...");
182 translator.parse_global(&mut new_section, global)?;
183 } else {
184 RoundtripReencoder.parse_global(&mut new_section, global)?;
185 }
186 }
187 let new_module = config.info().replace_section(section, &new_section);
188 Ok(Box::new(std::iter::once(Ok(new_module))))
189 }
190 Self::ElementOffset | Self::ElementFunc => {
191 let num_total = config.info().num_elements();
192 let mutate_idx = config.rng().random_range(0..num_total);
193 let section = config.info().elements.ok_or(skip_err)?;
194 let mut new_section = ElementSection::new();
195 let reader = config.info().get_binary_reader(section);
196 let reader = ElementSectionReader::new(reader)?;
197 let mut translator = InitTranslator {
198 config,
199 skip_inits: 0,
200 kind: *self,
201 };
202 for (idx, element) in reader.into_iter().enumerate() {
203 translator.config.consume_fuel(1)?;
204 let element = element?;
205 if idx as u32 == mutate_idx {
206 if let Self::ElementFunc = self {
207 // Pick a specific element item to mutate. We do this through an option
208 // to skip a specific number of activations of the Translator methods.
209 let item_count = match &element.items {
210 wasmparser::ElementItems::Functions(r) => r.count(),
211 wasmparser::ElementItems::Expressions(_, r) => r.count(),
212 };
213 if item_count > 0 {
214 let skip = translator.config.rng().random_range(0..item_count);
215 translator.skip_inits = skip
216 } else {
217 return Err(Error::no_mutations_applicable());
218 }
219 }
220 log::trace!("Modifying {} element's ({})...", idx, translator.skip_inits);
221 translator.parse_element(&mut new_section, element)?;
222 } else {
223 RoundtripReencoder.parse_element(&mut new_section, element)?;
224 }
225 }
226 let new_module = config.info().replace_section(section, &new_section);
227 Ok(Box::new(std::iter::once(Ok(new_module))))
228 }
229 }
230 }
231
232 fn can_mutate(&self, config: &crate::WasmMutate) -> bool {
233 // the implementation here can only reduce for now,
234 // but could be extended to mutate arbitrarily.
235 if !config.reduce {
236 return false;
237 }
238
239 let any_data = match self {
240 Self::Global => config.info().num_local_globals() > 0,
241 Self::ElementOffset | Self::ElementFunc => config.info().num_elements() > 0,
242 };
243 !config.preserve_semantics && any_data
244 }
245 }
246
247 #[cfg(test)]
248 mod tests {
249 fn match_reduction<T>(original: &str, mutator: T, expected: &str)
250 where
251 T: crate::Mutator + Clone,
252 {
253 let mut config = crate::WasmMutate::default();
254 config.reduce = true;
255 config.match_mutation(original, mutator, expected)
256 }
257
258 #[test]
259 fn reduce_global_const_i32() {
260 match_reduction(
261 "(module (global i32 (i32.const 42)))",
262 super::ConstExpressionMutator::Global,
263 "(module (global i32 (i32.const 0)))",
264 );
265 match_reduction(
266 "(module (global i32 (i32.const 10)))",
267 super::ConstExpressionMutator::Global,
268 "(module (global i32 (i32.const 5)))",
269 );
270 }
271
272 #[test]
273 fn reduce_global_xref() {
274 match_reduction(
275 r#"(module (import "m" "g" (global i32)) (global i32 (global.get 0)))"#,
276 super::ConstExpressionMutator::Global,
277 r#"(module (import "m" "g" (global i32)) (global i32 (i32.const 0)))"#,
278 );
279 }
280
281 #[test]
282 fn reduce_global_const_f32() {
283 match_reduction(
284 r#"(module (global f32 (f32.const 2.0)))"#,
285 super::ConstExpressionMutator::Global,
286 r#"(module (global f32 (f32.const 1.0)))"#,
287 );
288 match_reduction(
289 r#"(module (global f32 (f32.const 2.0)))"#,
290 super::ConstExpressionMutator::Global,
291 r#"(module (global f32 (f32.const 0.0)))"#,
292 );
293 }
294
295 #[test]
296 fn reduce_elem_funcref() {
297 match_reduction(
298 r#"(module (table 0 funcref) (elem func $a $b) (func $a) (func $b))"#,
299 super::ConstExpressionMutator::ElementFunc,
300 r#"(module (table 0 funcref) (elem func $a $a) (func $a) (func $b))"#,
301 );
302 }
303
304 #[test]
305 fn reduce_elem_expr() {
306 match_reduction(
307 r#"(module (table 0 funcref) (elem funcref (ref.func 0)) (func $a))"#,
308 super::ConstExpressionMutator::ElementFunc,
309 r#"(module (table 0 funcref) (elem funcref (ref.null func)) (func $a))"#,
310 );
311 }
312
313 #[test]
314 fn reduce_elem_base() {
315 match_reduction(
316 r#"(module
317 (import "m" "g" (global i32))
318 (table 0 funcref)
319 (func $f)
320 (elem (offset (global.get 0)) $f))"#,
321 super::ConstExpressionMutator::ElementOffset,
322 r#"(module
323 (import "m" "g" (global i32))
324 (table 0 funcref)
325 (func $f)
326 (elem (offset (i32.const 0)) $f))"#,
327 );
328 }
329 }