patch_method/
patch_method.rs1use 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 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 let index = body.position(|i| i.opcode == OpCode::Add).unwrap();
32 body.instructions[index] = Instruction::simple(OpCode::Mul);
33
34 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}