Nerdy tidbits from my life as a software engineer

Wednesday, March 18, 2009

Debugging Reflection.Emit Code Generations

It would really be nice if there was an easy way to do figure out how what the helpful “System.InvalidProgramException: Common Language Runtime detected an invalid program” exception when you have it.  The only way I’ve been able to debug problems with generated IL is by trial and error: comment out a bunch of lines of generation code, recompile, and then see if that works.  The real problem with the generated stuff is that you can’t do the usual debugging technique, which is to compare your auto-generated code with something that you generated with the compiler.  This, really, is the main difficulty with generating assemblies in .NET.

I know that you can use windbg to get to the bottom of a lot of this, but this is not a particularly intuitive way to figure things out.  It will be really nice when they finish opening up the compiler to programmatically generate types based on source code (have you seen Anders’ PDC presentation?  Very cool stuff).  That will make all of this reflection.emit stuff a thousand times easier.

3 comments:

Jason Bock said...

I've written something here that might help:

http://www.codeplex.com/EmitDebugger

The unfortunate part is that the Emit classes are not extensible so I had to wrap the classes with an exact API. HTH.

Jason Bock said...

Also:

http://www.codeplex.com/AssemblyVerifier

This just wraps peverify but you can call it on your emitted assembly right after you bake it - I've found this to be extremely helpful in chasing down bugs as well.

Michael J. Braude said...

Those look very, very helpful. Thanks!