Inject Method with Mono.Cecil

烂漫一生 提交于 2019-12-13 06:24:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!