Jump to content
Tuts 4 You

[dnlib] Injecting class with method.


IllusiveMan

Recommended Posts

IllusiveMan

Hello guys. I have some problems with injecting new class with one method inside it. Basicly this class is placed in my project and i need to insert it in assembly using dnlib, then call the method from it from constructor.


My code sample:



AssemblyDef assembly = AssemblyDef.Load(FilePath);
ModuleDef module = assembly.Modules[0];
Importer importer = new Importer(module); // Create new importer.
IMethod meth = importer.Import(typeof(MyClass).GetMethod("Initialize")); // Trying to import initialization method and then place it into a new class.
TypeDef type = new TypeDefUser("NewClass"); // Creating new type.
type.Attributes = TypeAttributes.Class; // Setting class attribute.
type.Methods.Add(meth.ResolveMethodDef()); // Catching Null exception here.
module.Types.Add(type); // Adding new type into our module.
////////////////////////////////////
MethodDef cctor = module.GlobalType.FindOrCreateStaticConstructor();
cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, meth)); // Need to call that method here.

So, i also have another question opposite topic subject. How can i enumerate all assembly references with dnlib?


Link to comment

A proper way of doing it is complicated since you'd have to clone the type, its members etc. A simple hack is to just remove the type from the original assembly and insert it in the new assembly.

var type = xxxx;

module.Types.Remove(type);

newModule.Types.Add(type);

If that type references other types, you'd have to do the same thing for every type. ConfuserEx has some code that imports its protection code into the protected application. Maybe that could be used if you want a better solution.

var m = module as ModuleDefMD;// if you've loaded it from disk / byte[] / stream, this will never be null

if (m == null)

throw new ...

foreach (var asmRef in m.GetAssemblyRefs())

Console.WriteLine("{0", asmRef);

  • Like 2
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...