1

I am creating my own program for changing .exe code via dnlib.
Then I want to create a Dictionary via IL and Dnlib code.
But there are not many tutorials for both so it's pretty hard..
It writes wrong Dictionary code and makes DnSpy crash.
My code:

            MethodDef cctor = Module.GlobalType.FindOrCreateStaticConstructor();
        IList<Instruction> inst = cctor.Body.Instructions;
        var objectCtor = new MemberRefUser(Module, ".ctor",
                    MethodSig.CreateInstance(Module.CorLibTypes.Void),
                    Module.CorLibTypes.Object.TypeDefOrRef);
        var Global_Array = new FieldDefUser(
"field_obfuscator_array",
new FieldSig(Module.CorLibTypes.GetCorLibTypeSig(,
FieldAttributes.Public | FieldAttributes.Static);
        Module.GlobalType.Fields.Add(Global_Array);
        if (inst.Count < 1)
            inst.Add(new Instruction(OpCodes.Ret));
        inst.Insert(0, new Instruction(OpCodes.Ldc_I4, 100000));
        inst.Insert(1, new Instruction(OpCodes.Newobj, "[mscorlib]System.Collections.Generic.Dictionary`2"));
        inst.Insert(2, new Instruction(OpCodes.Stsfld, Global_Array));

Any help is highly appreciated, thanks!

  • 1
    I am not accustomed to dnlib, but I suppose "[mscorlib]System.Collections.Generic.Dictionary\`2" is not a correct argument for `newobj`. *ITypeDefOrRef* or *CorLibTypeSig* might be a better candidate. – IS4 Jan 30 '18 at 12:19
  • What are the generic parameters you want the dictionary to have? – Thomas Flinkow Jan 03 '19 at 09:58

1 Answers1

0

The easiest way is to write this implementation in C# then drop it in decompiler (eg dnspy in this case or other doesnt matter - just need to be have IL code reader).

There is 3-ways to do this:

  1. Open your type/method whatever you will have, you could change it in top by clicking on C# -> IL or click to open with right-click on mouse, here is! From C# to IL
  2. Select method, right-click on mouse edit method body, done! After that you could just write the same IL code as well as in dnspy via dnlib.

image tutorial

  1. Create the same code (create something like external components inside of your project where you are using dnlib and changing the module) - write the same Class - Method - Fields etc then load it through Importer (do your magic - import this method, a lot of examples is right here)

Example code for dnlib how it could be done:

var externalComponentsImporter = new Importer(externalComponentsModuleDefMD, ImporterOptions.TryToUseDefs);
var redirectStubMethodDef = externalComponentsImporter.Import(typeof(Hooking).GetMethod(nameof(Hooking.RedirectStub), BindingFlags.Public | BindingFlags.Static)).ResolveMethodDefThrow();

// Play around with ImporterOptions enum
sunnamed
  • 96
  • 1
  • 10