Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug dynamically generated method?

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.

like image 744
Qué Padre Avatar asked Aug 01 '13 13:08

Qué Padre


2 Answers

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.

like image 105
Sani Singh Huttunen Avatar answered Sep 20 '22 15:09

Sani Singh Huttunen


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.

like image 31
Marc Gravell Avatar answered Sep 22 '22 15:09

Marc Gravell