| 1 |
//! This mutator selects a random `loop` construction in a function and tries to unroll it. |
| 2 |
//! This mutator only works on empty-returning loops |
| 3 |
use std::{collections::HashMap, slice::Iter}; |
| 4 |
|
| 5 |
use rand::prelude::*; |
| 6 |
use wasm_encoder::{Function, Instruction, ValType}; |
| 7 |
use wasmparser::{BlockType, Operator}; |
| 8 |
|
| 9 |
use crate::{ |
| 10 |
Error, WasmMutate, |
| 11 |
module::map_block_type, |
| 12 |
mutators::{ |
| 13 |
OperatorAndByteOffset, |
| 14 |
codemotion::{ |
| 15 |
AstMutator, |
| 16 |
ir::{ |
| 17 |
AstWriter, |
| 18 |
parse_context::{Ast, Node}, |
| 19 |
}, |
| 20 |
}, |
| 21 |
}, |
| 22 |
}; |
| 23 |
|
| 24 |
/// This mutator selects a random `loop` construction in a function and tries to unroll it. |
| 25 |
/// This mutator only works on empty-returning loops |
| 26 |
pub struct LoopUnrollMutator; |
| 27 |
|
| 28 |
#[derive(Default)] |
| 29 |
struct LoopUnrollWriter { |
| 30 |
loop_to_mutate: usize, |
| 31 |
} |
| 32 |
|
| 33 |
impl LoopUnrollWriter { |
| 34 |
fn write_and_fix_loop_body<'a>( |
| 35 |
&self, |
| 36 |
chunk: Iter<OperatorAndByteOffset>, |
| 37 |
to_fix: &HashMap<usize, Instruction>, |
| 38 |
newfunc: &mut Function, |
| 39 |
input_wasm: &'a [u8], |
| 40 |
) -> crate::Result<()> { |
| 41 |
for (idx, ((_, curr_offset), (_, next_offset))) in |
| 42 |
chunk.clone().zip(chunk.skip(1)).enumerate() |
| 43 |
{ |
| 44 |
if to_fix.contains_key(&idx) { |
| 45 |
newfunc.instruction(&to_fix[&idx]); |
| 46 |
} else { |
| 47 |
let piece = &input_wasm[*curr_offset..*next_offset]; |
| 48 |
newfunc.raw(piece.to_vec()); |
| 49 |
} |
| 50 |
} |
| 51 |
Ok(()) |
| 52 |
} |
| 53 |
|
| 54 |
fn unroll_loop<'a>( |
| 55 |
&self, |
| 56 |
ast: &Ast, |
| 57 |
nodeidx: usize, |
| 58 |
newfunc: &mut Function, |
| 59 |
operators: &Vec<OperatorAndByteOffset>, |
| 60 |
input_wasm: &'a [u8], |
| 61 |
) -> crate::Result<()> { |
| 62 |
let nodes = ast.get_nodes(); |
| 63 |
|
| 64 |
let mut current_depth = 0; |
| 65 |
let mut to_fix = HashMap::new(); |
| 66 |
|
| 67 |
match &nodes[nodeidx] { |
| 68 |
Node::Loop { body: _, ty, range } => { |
| 69 |
let chunk = &operators[range.start + 1 /* skip the loop instruction */..range.end]; |
| 70 |
newfunc.instructions().block(map_block_type(*ty)?); |
| 71 |
for (idx, (op, _)) in chunk.iter().enumerate() { |
| 72 |
match op { |
| 73 |
Operator::Block { .. } |
| 74 |
| Operator::Loop { .. } |
| 75 |
| Operator::If { .. } |
| 76 |
| Operator::TryTable { .. } => { |
| 77 |
current_depth += 1; |
| 78 |
} |
| 79 |
Operator::End { .. } => { |
| 80 |
current_depth -= 1; |
| 81 |
} |
| 82 |
Operator::Br { relative_depth } => { |
| 83 |
if *relative_depth > current_depth { |
| 84 |
// Out jump...annotate for fixing |
| 85 |
to_fix.insert(idx, Instruction::Br(relative_depth + 1)); |
| 86 |
} |
| 87 |
} |
| 88 |
Operator::BrIf { relative_depth } => { |
| 89 |
if *relative_depth > current_depth { |
| 90 |
// Out jump...annotate for fixing |
| 91 |
to_fix.insert(idx, Instruction::BrIf(relative_depth + 1)); |
| 92 |
} |
| 93 |
} |
| 94 |
Operator::BrTable { targets } => { |
| 95 |
let mut jmpfix = vec![]; |
| 96 |
for i in targets.targets() { |
| 97 |
let d = i?; |
| 98 |
if d > current_depth { |
| 99 |
// Out jump...annotate for fixing |
| 100 |
jmpfix.push(d + 1) |
| 101 |
} else { |
| 102 |
jmpfix.push(d) |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
let mut def = targets.default(); |
| 107 |
if def > current_depth { |
| 108 |
def += 1; |
| 109 |
} |
| 110 |
|
| 111 |
to_fix.insert(idx, Instruction::BrTable(jmpfix.into(), def)); |
| 112 |
} |
| 113 |
|
| 114 |
Operator::BrOnCast { .. } |
| 115 |
| Operator::BrOnCastFail { .. } |
| 116 |
| Operator::BrOnNull { .. } |
| 117 |
| Operator::BrOnNonNull { .. } => { |
| 118 |
log::info!("unsupported operator {op:?}"); |
| 119 |
return Err(Error::no_mutations_applicable()); |
| 120 |
} |
| 121 |
_ => {} |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
// Write the unroll |
| 126 |
newfunc.instructions().block(map_block_type(*ty)?); |
| 127 |
// Write A' br B' |
| 128 |
let including_chunk = |
| 129 |
operators[range.start + 1 /* skip the loop instruction */..range.end + 1] |
| 130 |
.iter(); |
| 131 |
self.write_and_fix_loop_body(including_chunk, &to_fix, newfunc, input_wasm)?; |
| 132 |
|
| 133 |
// Write A' br B' |
| 134 |
newfunc.instructions().br(1); |
| 135 |
newfunc.instructions().end(); |
| 136 |
// Write the Loop |
| 137 |
newfunc.instructions().loop_(map_block_type(*ty)?); |
| 138 |
|
| 139 |
// Write A' br B' |
| 140 |
let including_chunk = |
| 141 |
operators[range.start + 1 /* skip the loop instruction */..range.end + 1] |
| 142 |
.iter(); |
| 143 |
self.write_and_fix_loop_body(including_chunk, &to_fix, newfunc, input_wasm)?; |
| 144 |
|
| 145 |
// Closing loop |
| 146 |
newfunc.instructions().end(); |
| 147 |
|
| 148 |
// Closing end |
| 149 |
newfunc.instructions().end(); |
| 150 |
} |
| 151 |
_ => unreachable!("Invalid node passed as a loop to unroll"), |
| 152 |
} |
| 153 |
Ok(()) |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
impl AstWriter for LoopUnrollWriter { |
| 158 |
fn write_loop<'a>( |
| 159 |
&self, |
| 160 |
ast: &Ast, |
| 161 |
nodeidx: usize, |
| 162 |
body: &[usize], |
| 163 |
newfunc: &mut Function, |
| 164 |
operators: &Vec<OperatorAndByteOffset>, |
| 165 |
input_wasm: &'a [u8], |
| 166 |
ty: &wasmparser::BlockType, |
| 167 |
) -> crate::Result<()> { |
| 168 |
if self.loop_to_mutate == nodeidx { |
| 169 |
self.unroll_loop(ast, nodeidx, newfunc, operators, input_wasm)?; |
| 170 |
} else { |
| 171 |
self.write_loop_default(ast, nodeidx, body, newfunc, operators, input_wasm, ty)?; |
| 172 |
} |
| 173 |
Ok(()) |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
impl LoopUnrollMutator { |
| 178 |
/// Returns the indexes of empty return loop definitions inside the Wasm function |
| 179 |
pub fn get_empty_returning_loops<'a>(&self, ast: &'a Ast) -> Vec<usize> { |
| 180 |
let nodes = ast.get_nodes(); |
| 181 |
let mut loops = vec![]; |
| 182 |
for idx in ast.get_loops() { |
| 183 |
let n = &nodes[*idx]; |
| 184 |
match n { |
| 185 |
Node::Loop { |
| 186 |
ty, |
| 187 |
range: _, |
| 188 |
body: _, |
| 189 |
} => { |
| 190 |
if let BlockType::Empty = ty { |
| 191 |
loops.push(*idx) |
| 192 |
} |
| 193 |
} |
| 194 |
_ => unreachable!("Invalid loop node"), |
| 195 |
} |
| 196 |
} |
| 197 |
loops |
| 198 |
} |
| 199 |
} |
| 200 |
|
| 201 |
impl AstMutator for LoopUnrollMutator { |
| 202 |
fn can_mutate(&self, _config: &crate::WasmMutate, ast: &Ast) -> bool { |
| 203 |
let empty_returning_loops = self.get_empty_returning_loops(ast); |
| 204 |
!empty_returning_loops.is_empty() |
| 205 |
} |
| 206 |
|
| 207 |
fn mutate<'a>( |
| 208 |
&self, |
| 209 |
config: &'a mut WasmMutate, |
| 210 |
ast: &Ast, |
| 211 |
locals: &[(u32, ValType)], |
| 212 |
operators: &Vec<OperatorAndByteOffset>, |
| 213 |
input_wasm: &'a [u8], |
| 214 |
) -> crate::Result<Function> { |
| 215 |
// Select the if index |
| 216 |
let mut newfunc = Function::new(locals.to_vec()); |
| 217 |
let empty_returning_loops = self.get_empty_returning_loops(ast); |
| 218 |
let loop_index = empty_returning_loops |
| 219 |
.choose(config.rng()) |
| 220 |
.expect("This mutator should check first if the AST contains at least one loop node"); |
| 221 |
let writer = LoopUnrollWriter { |
| 222 |
loop_to_mutate: *loop_index, |
| 223 |
}; |
| 224 |
writer.write(ast, ast.get_root(), &mut newfunc, operators, input_wasm)?; |
| 225 |
Ok(newfunc) |
| 226 |
} |
| 227 |
} |