0xd4d / dnlib

Reads and writes .NET assemblies and modules
MIT License
2.17k stars 587 forks source link

Function is not defined in this module #76

Closed vmcall closed 8 years ago

vmcall commented 8 years ago

I'm trying to add basic junk methods to my obfuscator. I grab all methods (besides constructors) from mscorlib.dll. I then inject five functions into the global type, the exact same way i inject my string decryption functions (which works) But when i write the assembly, i get this error:

Unhandled Exception: dnlib.DotNet.Writer.ModuleWriterException: Method System.Void System.Security.CodeAccessPermission::AssertAllPossible() (0600382C) is not defined in this module (). A method was removed that is still referenced by this module.

_RandomMethod returns a random method that is static and has a return type of System.Void

I've tried changing the method body to a nop, and the methods are injected successfully, so problem is 99% that the compiler isn't happy with my way of calling the methods?

private MethodDef MakeJunkMethod(MethodDef randomMethod)
{
    MethodImplAttributes methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed;
    MethodAttributes methFlags = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;

    MethodDef JunkMethod = new MethodDefUser(_RandomMethodName, MethodSig.CreateStatic(_Module.CorLibTypes.Void), methImplFlags, methFlags);

    CilBody body = new CilBody();

    body.Instructions.Add(new Instruction(OpCodes.Call, randomMethod));
    body.Instructions.Add(new Instruction(OpCodes.Ret));

    JunkMethod.MethodBody = body;
    JunkMethod.Body.KeepOldMaxStack = true;

    return JunkMethod;
}
private void InjectJunkMethod()
{
    TypeDef module = _Module.GlobalType;
    module.Methods.Add(MakeJunkMethod(_RandomJunkMethod));
}
0xd4d commented 8 years ago

Possible reasons:

  1. You removed a method from an assembly but that assembly is still referencing the method Solution: change all refs to MemberRefs to the new assembly.
  2. You just moved a method from some assembly to another assembly and the method contains references to the original assembly. Solution: do a proper clone of the method. See ConfuserEx source code.
vmcall commented 8 years ago

I'm not cloning any methods though, I'm creating a new method that calls the method