[Mono-dev] Method code injection

Rodrigo B. de Oliveira rodrigobamboo at gmail.com
Sat Mar 13 08:14:23 EST 2010


Hey Amir!

Yes, you can use Mono.Cecil:

    import System
    import Mono.Cecil
    import Mono.Cecil.Cil

    pathToAssembly = "/tmp/test.exe"
    asm = AssemblyFactory.GetAssembly(pathToAssembly)

    module = asm.MainModule
    method = module.Types["Program"].Methods.GetMethod("Main")[0]

    worker = method.Body.CilWorker
    firstInstruction = method.Body.Instructions[0]
    worker.InsertBefore(firstInstruction, worker.Create(OpCodes.Ldstr,
"Hello!"))
    worker.InsertBefore(firstInstruction, worker.Create(OpCodes.Call,
module.Import(typeof(Console).GetMethod("WriteLine", (string,)))))

    AssemblyFactory.SaveAssembly(asm, pathToAssembly)
    AppDomain.CurrentDomain.ExecuteAssembly(pathToAssembly)


More information about the Mono-devel-list mailing list