0

I'm trying to inject a class with a method in a file. I'm aware that there is a working solution in ConfuserEx's source code but it kinda requires editing dnlib's code which I want to avoid.

ModuleDef manifestModule = assembly.ManifestModule;
Importer importer = new Importer(manifestModule);
IMethod method = importer.Import(typeof(AntiDumpRuntime).GetMethod("Initialize"));

TypeDef type = new TypeDefUser("AntiDump");
type.Methods.Add(method.ResolveMethodDefThrow()); // dnlib.DotNet.MemberRefResolveException: 'Could not resolve method: System.Void Obfuscator.Core.Protections.AntiDump.AntiDumpRuntime::Initialize() (Obfuscator, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null)'
manifestModule.Types.Add(type);

In the above snippet I tried to do that via Importer class, but it throws an exception right on the commented row.

Here is the ConfuserEx's solution: https://github.com/yck1509/ConfuserEx/blob/master/Confuser.Core/Helpers/InjectHelper.cs And here is the modification needed to be done in dnlib: https://github.com/yck1509/dnlib/blob/master/src/DotNet/Importer.cs#L72

nop
  • 4,711
  • 6
  • 32
  • 93

1 Answers1

0

The newest version of dnlib contain the changes you require to get it working. The importer has an constructor that allows setting a ImportMapper implementation. Using this you can properly inject code with the default version of dnlib.

I'm maintaining a fork of ConfuserEx that uses the dnlib without modifications. So it works fine.

Nitram
  • 6,486
  • 2
  • 21
  • 32
  • Would you like to share code implementation for ``InjectContext`` class? – nop Feb 27 '19 at 16:36
  • Have a look [here](https://github.com/mkaring/ConfuserEx/blob/release/2.0/Confuser.Helpers/InjectHelper.cs) and in the nested classes (they are in different files). You find the implementation of the ImportMapper in there. – Nitram Feb 27 '19 at 16:39
  • Oh i didn't recognize that's another ConfuserEx link. Is it compatible with .net 4.5 since there are Immutable lists – nop Feb 27 '19 at 17:10
  • You can implement it without the Immutable Lists. But the package also works with .net 4.5. – Nitram Feb 27 '19 at 17:58
  • Thank you! Accepting this answer. – nop Jun 09 '19 at 22:27