inject/
inject.rs

1extern crate sophon_wasm;
2
3use std::env;
4
5use sophon_wasm::elements;
6use sophon_wasm::builder;
7
8pub fn inject_nop(opcodes: &mut elements::Opcodes) {
9    use sophon_wasm::elements::Opcode::*;
10    let opcodes = opcodes.elements_mut();
11    let mut position = 0;
12    loop {
13        let need_inject = match &opcodes[position] {
14            &Block(_) | &If(_) => true,
15            _ => false,
16        };
17        if need_inject {
18            opcodes.insert(position + 1, Nop);
19        }
20
21        position += 1;
22        if position >= opcodes.len() {
23            break;
24        }
25    }
26}
27
28fn main() {
29    let args = env::args().collect::<Vec<_>>();
30    if args.len() != 3 {
31        println!("Usage: {} input_file.wasm output_file.wasm", args[0]);
32        return;
33    }
34
35    let mut module = sophon_wasm::deserialize_file(&args[1]).unwrap();
36
37    for section in module.sections_mut() {
38        match section {
39            &mut elements::Section::Code(ref mut code_section) => {
40                for ref mut func_body in code_section.bodies_mut() {
41                    inject_nop(func_body.code_mut());
42                }
43            },
44            _ => { }
45        }
46    }
47
48    let mut build = builder::from_module(module);
49    let import_sig = build.push_signature(
50        builder::signature()
51            .param().i32()
52            .param().i32()
53            .return_type().i32()
54            .build_sig()
55    );
56    let build = build.import()
57        .module("env")
58        .field("log")
59        .external().func(import_sig)
60        .build();
61
62    sophon_wasm::serialize_to_file(&args[2], build.build()).unwrap();
63}