I have a dynamically created assembly, a module, a class and a dynamically generated method.
AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(...);
ModuleBuilder module = assembly.DefineDynamicModule(...);
TypeBuilder tb = module.DefineType(...);
MethodBuilder mb = tb.DefineMethod(...);
ILGenerator gen = mb.GetILGenerator();
How can I debug method code generated with ILGenerator
? I use Visual Studio 2012 debugger, but it just steps through a method call.
You need to mark the generated code as debuggable.
Something like:
Type daType = typeof(DebuggableAttribute);
ConstructorInfo ctorInfo = daType.GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) });
CustomAttributeBuilder caBuilder = new CustomAttributeBuilder(ctorInfo, new object[] {
DebuggableAttribute.DebuggingModes.DisableOptimizations |
DebuggableAttribute.DebuggingModes.Default
});
assembly.SetCustomAttribute(caBuilder);
You also should add a sourcefile:
ISymbolDocumentWriter doc = module.DefineDocument(@"SourceCode.txt", Guid.Empty, Guid.Empty, Guid.Empty);
You should now be able to step into the dynamically generated method.
If you are generating raw IL without any source, then : this is always going to be rough. You might want to consider a package like Sigil, which is a wrapper around ILGenerator
, but which will give you useful error messages (while emitting, not while running) if you make any subtle errors - stack corruption, etc.
Either that, or: write the module with save-to-disk enabled, and during debugging write a regular dll to disk - you can then run PEVerify
on the dll, which will find most typical errors (again, stack corruption, etc). Or of course - you can load it into your favorite IL tool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With