Debian Codegraph @

crates/wasm-mutate/src/mutators/peephole/eggsy/encoder.rs

raw
1 //! Helper methods for encoding eterm expressions to Wasm and back
2
3 use crate::WasmMutate;
4 use crate::mutators::peephole::dfg::MiniDFG;
5 use crate::mutators::peephole::eggsy::encoder::expr2wasm::expr2wasm;
6 use crate::mutators::peephole::{EG, Lang};
7 use crate::mutators::peephole::{OperatorAndByteOffset, dfg::BBlock};
8 use egg::RecExpr;
9
10 use wasm_encoder::Function;
11
12 use self::expr2wasm::ResourceRequest;
13
14 pub mod expr2wasm;
15 pub mod rebuild;
16
17 /// Turns wasm to eterm and back
18 pub struct Encoder;
19
20 /// Traversing node events
21 enum TraversalEvent {
22 Enter,
23 Exit,
24 }
25
26 impl Encoder {
27 /// Reassembles the mutated function and return a `Function` entry
28 pub fn build_function(
29 config: &mut WasmMutate,
30 insertion_point: usize,
31 expr: &RecExpr<Lang>,
32 operators: &[OperatorAndByteOffset],
33 basicblock: &BBlock, // move to the analysis
34 newfunc: &mut Function,
35 dfg: &MiniDFG,
36 egraph: &EG,
37 ) -> crate::Result<Vec<ResourceRequest>> {
38 // Copy previous code
39 let range = basicblock.range.clone();
40 let byterange = (&operators[0].1, &operators[range.start].1);
41 let bytes = &config.info().get_code_section().data[*byterange.0..*byterange.1];
42 newfunc.raw(bytes.iter().copied());
43
44 // Write all entries in the minidfg in reverse order
45 // The stack neutral will be preserved but the position of the changed operands not that much :(
46 // The edges of the stackentries are always backward in the array, so, it consistent to
47 // do the writing in reverse
48 let mut resource_request = vec![];
49 for (entryidx, parent) in dfg.parents.iter().enumerate() {
50 // It is a root, write then
51 if parent.is_none() {
52 let entry = &dfg.entries[entryidx];
53 let to_encode = if entry.operator_idx == insertion_point {
54 expr.clone()
55 } else {
56 dfg.get_expr(entry.operator_idx)
57 };
58 resource_request.extend(expr2wasm(config, &to_encode, newfunc, egraph)?);
59 }
60 }
61
62 // Copy remaining function
63 let range = basicblock.range.clone();
64 let byterange = (
65 &operators[range.end].1, // In the worst case the next instruction will be and end
66 &operators[operators.len() - 1].1,
67 );
68 let bytes = &config.info().get_code_section().data[*byterange.0..=*byterange.1];
69
70 newfunc.raw(bytes.iter().copied());
71 Ok(resource_request)
72 }
73 }