Search code examples
c#reflectiondnlib

Dnlib - Execute IL MethodBody from loaded assembly


I am working on an unpacker for a simple .Net packer.

I would like to execute a method from a loaded assembly using dnlib.

I can't use System.Reflection because the packer pack the original executable and then it will unpack in memory before executing so using reflection give me the error unable to find xxx module.

Currently i scan the loaded assembly and get MethodDef of methods that i need to perform unpacking.

As you know there is a way to execute the IL code from a loaded assembly in dnlib using C#?

The idea is to call packers methods to avoid rewriting of the unpacker at each packer update.

Is this scenario possible? Or it is just a dream? XD

If it is not possible the other idea that i have is to write an IL emulator.

There are other path to solve this?

Thanks a lot for your time.


Solution

  • You don't need dnlib, just call the assembly using these methods. This example calls a method with a single integer as the argument that returns a string.

    var assembly = Assembly.LoadFile(fullpathofexecutable);
    BindingFlags eFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
    
    Type classInstance = GetClass("Class196", assembly.GetTypes());
    
    MethodInfo myMethod = classInstance.GetMethod("methodThatIWantToExecute", eFlags);
    
    object[] arguments = {1,2,3 };
    string result = (string)myMethod.Invoke(null, arguments);