Instrumenting assemblies with Mono.Cecil and IronRuby

I just finished working on a script that I am really proud of. So proud that I want to share it with all of you.

I am working on making modifications to a third party application. I have source for some of the application, but unfortunately just having the source has not answered all of my questions. The application’s architecture is rather convoluted, and the source code is filled with hints that it was produced by very inexperienced hands. To steal a quote that I read on twitter a couple of months ago, “I was hoping to at least get spaghetti, but this code is just soup.”

So, I wanted to instrument the code so that I could get a better idea about what was going on in one particular library, specifically one that leverages Microsoft’s Workflow Foundation. My first stab at this was to just read the source in and add code to each method that marks the insert and exit points. I was planning on using the System.CodeDom libraries for this, and I was rather disappointed to discover that CodeParser is not implemented by the .NET Framework for C#.

So I turned to Mono.Cecil instead. I wrote a utility that modifies every constructor and every method. For each one, a message is inserted at the beginning of the method to note that it has started, and a message is inserted right before the return statement to note that the method is complete. Messages are transmitted through log4net, so you will need to play with your app.config to make the tracing messages show up.

The utility is written in ruby and will only run from IronRuby, because it makes heavy use of the .NET Framework. Oh, and the utility has the ability to apply and remove the instrumentation to an assembly, so you can put it back the way you found it.

Enjoy and let me know if you find any problems.


Leave a Reply