Wednesday 23 December 2009

CIL Debugging

Some weeks ago while chatting with a friend something came up in the conversation that brought to my mind some old memories of those times (it was in 2003) when I used to do some coding in CIL (also known as MSIL). The thing is "how do you debug CIL code?".
With the VS Debugger, MDBG or SharpDevelop Debugger you can't debug at the CIL level, just high level language (with Native Assembly view). The answer is simple, and now you can find some more entries explaining the wholeprocess, but given that it's something that I found out by myself back in those times, I'm feeling like posting about it.

First, an obvious question, what do we need for our source level debugging?
We need the .exe, the source code file and a .pdb file that somehow links the .exe with the source file. When we compile with the csc using the /DEBUG option, we're linking to the C# source, so if we want to link with the CIL source, we need that CIL source and the corresponding compiler.

So, all this comes down to giving an odd detour from your initial C# (or VB.Net...) code to the final .exe using some of the tools available with the Framework.


  • First we compile from C# to .exe
    csc debug2009.cs


  • then, we disassemble that .exe, and get a .il file
    ildasm /OUT=Debug2009.il debug2009.exe


  • and then we assemble that .il file into a new .exe, using the /DEBUG switch.
    ilasm /EXE /DEBUG Debug2009.il
    this last step is the fundamental one, this way we obtain a .pdb file containing debug information for the CIL code, not for the C# code.



So, now we can launch the new .exe file, attach a debugger to it (for example the SharpDevelop one) and all the magic happens when the information in the .exe, .pdb and .il files is used together:



In those times when I had some CIL knowledge (it's gone terribly rustied after not using it for years) I wrote some basic articles about CIL programming for @rroba, a Spanish magazine (hey, I even got paid for it!). It's in Spanish, and sure contains some conceptual errors that I think I would not reproduce now, but anyway I'll leave it here just in case it could be of any use to someone.



(Sorry, I still have not been able to upload the files)

No comments:

Post a Comment