Skip to main content

patch_method/
patch_method.rs

1//! Patches the IL of the sample assembly and writes a new assembly.
2//!
3//! ```sh
4//! crates/hao/tests/fixtures/build.sh
5//! cargo run --example patch_method -- crates/hao/tests/fixtures/out/Sample.dll out/Sample.dll
6//! cp crates/hao/tests/fixtures/out/Sample.runtimeconfig.json out/
7//! dotnet out/Sample.dll
8//! ```
9
10use hao::dotnet::csharp::WriteCSharp;
11use hao::prelude::well_known::ConsoleMethod;
12use hao::prelude::*;
13
14fn main() -> hao::error::Result<()> {
15    let mut args = std::env::args().skip(1);
16    let (input, output) = match (args.next(), args.next()) {
17        (Some(i), Some(o)) => (i, o),
18        _ => panic!("usage: patch_method <Sample.dll> <output.dll>"),
19    };
20    let mut module = Module::from_path_no_resolve(&input)?;
21
22    // A common BCL member whose signature is known: one call, no hand-written sig.
23    let write_line =
24        module.import_well_known_method(WellKnownMethod::Console(ConsoleMethod::WriteLineStr))?;
25
26    let add = module.find_method("Sample.Calc", "Add").expect("Calc.Add");
27    println!("before:\n{}", add.get().body.as_ref().unwrap().csharp());
28
29    add.edit_body(|body| {
30        // a + b  ->  a * b
31        let index = body.position(|i| i.opcode == OpCode::Add).unwrap();
32        body.instructions[index] = Instruction::simple(OpCode::Mul);
33
34        // Console.WriteLine("Add called") at the start of the method.
35        body.insert(
36            0,
37            [
38                Instruction::ldstr("Add called"),
39                Instruction::call(write_line),
40            ],
41        );
42    });
43    println!("after:\n{}", add.get().body.as_ref().unwrap().csharp());
44
45    let main = module.entry_point.clone().expect("entry point");
46    main.edit_body(|body| {
47        body.replace_operand(
48            &"Hello from hao".into(),
49            "Hello from a patched assembly".into(),
50        )
51    });
52
53    if let Some(dir) = std::path::Path::new(&output).parent() {
54        std::fs::create_dir_all(dir).ok();
55    }
56    module.write_to_path(&output)?;
57    println!("wrote {}", output);
58    Ok(())
59}