问题
How can I inject a custom method into a .net assembly using mono.cecil, and then call it in the entrypoint? I like to do this to implement security methods after the binary is built.
回答1:
To inject method you need to get the type you want to add it the method and then add a MethoDefinition
.
var mainModule = ModuleDefinition.ReadModule(assemblyPath);
var type = module.Types.Single(t => t.Name == "TypeYouWant");
var newMethodDef= new MethodDefinition("Name", MethodAttributes.Public, mainModule.TypeSystem.Void);
type.Methods.Add(newMethodDef);
To call this method form the entry point, you need to get the entry point MethodDefinition
and the new injected MethodReference
and add instruction in the entry point method to call the new injected method.
var newMethodRef = type.Methods.Single(m => m.Name == "Name").Resolve();
var entryPoint= type.Methods.Single(m => m.Name == "YourEntryPoint");
var firstInstruction = entryPoint.Body.Instructions.First();
var il = entryPoint.Body.GetILProcessor();
il.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Callvirt, newMethodRef));
mainModule.Write(assemblyPath);
Note: Yes I know its C# and not VB but I'm sure once you got the idea you can easily convert it to VB.
回答2:
You can make use of the Module.Import()
function.
Example Class can be seen in the video: https://www.youtube.com/watch?v=heTCisgYjhs
Credits to TheUnknownProgrammer's importer class.
来源:https://stackoverflow.com/questions/23461472/inject-method-with-mono-cecil