Sunday, June 6, 2010

How to Debug through .NET Framework Source Code (with VS 2010)

Back in my school days, when I used Java as primary programming language, I used to step through Java platform code a lot. I did that mostly because of curiosity. I wanted to see how all these classes and methods were implemented. Also, I wanted to learn about coding practices used at Sun Microsystems.

In general, the ability to debug through platform code is not used for educational purposes only. It is very useful and important because it can help us to further investigate subtle errors in our applications.

In most Java IDEs we can step through Java platform code in the same way we step through user code – by using basic debugger commands. We can also set break points, view values of various variables, etc. All these can be done without any additional configuration.

Right now I use .NET framework much more than Java, and in several cases, the feature described above (used within Visual Studio 2010 and with .NET Framework source code) proved very useful.

.NET Framework source code has more restrictive license than Java Platform source code. That means that .NET Framework source code debugging is somehow restricted too. Particularly, it is limited to source code of several most important assemblies (such as mscorlib.dll, System.dll, System.Data.dll, etc.) In Visual Studio 2010, this feature is available by default. However, it still requires some additional configuration.

First of all, we have to open Options Dialog (Main Menu –> Tools –> Options) and navigate to Debugging –> General page. Here we have to:

  • Uncheck Enable Just My Code (Managed only), which will enable stepping through non-user code.
  • Check  Enable .NET Framework source stepping.
  • Check Enable source server support. This option enables downloading of sources when they are available for symbol files that Visual Studio downloads.

Then we have to go to Debugging –> Symbols page and:

  • add the following symbol path
  • set the path where symbols will be cached (text field with title Cache symbols in this directory). Some of the symbol files downloaded during this process are very large, so it is recommended to cache them. Otherwise, they will be downloaded each time we start debugging session.

Before we step into source of some framework module, we need to ensure that appropriate symbols are loaded. Visual Studio loads symbols for all modules except for those explicitly excluded. Just in case, you can go to Modules Window (Ctrl + Alt + U) and see if symbols are loaded for module you wish to debug. If not, right click on it and then click on Load Symbols From –> Symbol Path popup menu item.

When we try to step into framework source code for the first time, we are asked to read and accept the license agreement.

After this we should be able to easily step through .NET Framework source code.

No comments: