<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Low Level Design</title>
	<atom:link href="http://lowleveldesign.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://lowleveldesign.wordpress.com</link>
	<description>.NET debugging, deployment, performance measurement</description>
	<lastBuildDate>Thu, 23 Feb 2012 11:45:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='lowleveldesign.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Low Level Design</title>
		<link>http://lowleveldesign.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://lowleveldesign.wordpress.com/osd.xml" title="Low Level Design" />
	<atom:link rel='hub' href='http://lowleveldesign.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Adplus: handling managed exceptions</title>
		<link>http://lowleveldesign.wordpress.com/2012/01/16/adplus-managed-exceptions/</link>
		<comments>http://lowleveldesign.wordpress.com/2012/01/16/adplus-managed-exceptions/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 00:59:54 +0000</pubDate>
		<dc:creator>Sebastian Solnica</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Exceptions]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[adplus]]></category>
		<category><![CDATA[clr]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[debugging tools for windows]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://lowleveldesign.wordpress.com/?p=591</guid>
		<description><![CDATA[In this post I&#8217;m going to concentrate on managed exceptions and the ways how we can handle them using Adplus. Some time ago John Robbins in his Bugslayer column wrote a great article about handling specific managed exceptions using Adplus. Although the general concept of the managed exception hasn&#8217;t changed (and so the SOS commands) [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=591&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I&#8217;m going to concentrate on managed exceptions and the ways how we can handle them using Adplus. Some time ago John Robbins in his <em>Bugslayer</em> column wrote a great <a href="http://msdn.microsoft.com/en-us/magazine/cc163530.aspx" title="Minidumps for Specific Exceptions" target="_blank">article</a> about handling specific managed exceptions using Adplus. Although the general concept of the managed exception hasn&#8217;t changed (and so the SOS commands) his scripts do not work with the latest installation of Adplus. With the version 6.12 of the <em><a href="http://msdn.microsoft.com/en-us/windows/hardware/gg463009" title="Debugging Tools for Windows" target="_blank">Debugging Tools for Windows</a></em> we received a brand new version of Adplus (7th) which was transformed from a VB script to a .NET application. Although the command line options seems to be compatible with the previous version, the configuration file structure changed significantly. Old scripts need to be rewritten in order to work with the new version. In this post I will not only <em>upgrade</em> John Robbin&#8217;s scripts but also show you some (I hope interesting) new features of Adplus.</p>
<p><span id="more-591"></span></p>
<h2>Creating Adplus configuration file</h2>
<p>As command line parameters do not allow us to use many Adplus advanced features I generally prefer to store Adplus run settings in config files with names explaining their usage. In this post we will work on some sections of the configuration file but I strongly encourage you to read the Adplus documentation and find detailed information about the configuration file structure. We will start from the following <code>log-exceptions.adplus.config</code> file (all samples can be downloaded from <a href="http://lowleveldesign.codeplex.com/releases/view/80582" title="Sample files for the post." target="_blank">the blog samples website</a>):</p>
<p><pre class="brush: xml;">
&lt;adplus version=&quot;2&quot;&gt;
  &lt;settings&gt;
    &lt;runmode&gt;crash&lt;/runmode&gt;
    &lt;lastscriptcommand&gt;qd&lt;/lastscriptcommand&gt;
  &lt;/settings&gt;
  &lt;exceptions&gt;
    &lt;allexceptions&gt;
      &lt;actions1&gt;LOG&lt;/actions1&gt;
      &lt;returnaction1&gt;GN&lt;/returnaction1&gt;
      &lt;actions2&gt;LOG&lt;/actions2&gt;
      &lt;returnaction2&gt;GN&lt;/returnaction2&gt;
    &lt;/allexceptions&gt;
    &lt;allevents&gt;
      &lt;actions1&gt;LOG&lt;/actions1&gt;
      &lt;returnaction1&gt;GN&lt;/returnaction1&gt;
      &lt;actions2&gt;LOG&lt;/actions2&gt;
      &lt;returnaction2&gt;GN&lt;/returnaction2&gt;
    &lt;/allevents&gt;
  &lt;/exceptions&gt;
&lt;/adplus&gt;
</pre></p>
<p>If we use the above configuration file with the Thrower.exe application (can be downloaded from <a href="http://lowleveldesign.codeplex.com/releases/view/80582" title="Sample files for the post." target="_blank">here</a>):</p>
<p><pre class="brush: plain;">
&gt; adplus -c log-exceptions.adplus.config -o c:\dumps -sc Thrower.exe
</pre></p>
<p>Adplus will geneate three files in the output directory: </p>
<ul>
<li><strong>ADPlust_report.txt</strong> &#8211; contains the settings with which the Adplus was run</li>
<li><strong>DebuggerScript.txt</strong> &#8211; the script generated by the Adplus and executed in the debugger at the beginning of the debugging process</li>
<li><strong>Adplus_log</strong> &#8211; all the ouput produced by the debugger</li>
</ul>
<p>If we look at the Adplus_log we can see that not much information was provided about the exceptions that occurred:<br />
<pre class="brush: plain;">
...
(12d8.1a14): CLR exception - code e0434352 (first chance)
FirstChance_clr_NET_CLR
ModLoad: 000007fe`e5e30000 000007fe`e5f1a000   C:\Windows\Microsoft.NET\Framework64\v4.0.30319\diasymreader.dll
FirstChance_ld_DLL_Load
(12d8.1a14): CLR exception - code e0434352 (first chance)
FirstChance_clr_NET_CLR
(12d8.1a14): CLR exception - code e0434352 (first chance)
FirstChance_clr_NET_CLR
ModLoad: 000007fe`fca50000 000007fe`fca5c000   C:\Windows\system32\VERSION.dll
FirstChance_ld_DLL_Load
(12d8.1a14): CLR exception - code e0434352 (!!! second chance !!!)
SecondChance_clr_NET_CLR
...
</pre><br />
We can only deduce that there were three CLR exceptions (code e0434352) from which two were handled in the application code (only <a href="http://stackoverflow.com/questions/4070040/first-chance-vs-second-chance-exception" title="What is a first chance exception?" target="_blank">first chance</a> logged by the debugger) and the third broke the application (thus second chance logged). Unfortunately we can&#8217;t either see what the exception type was or who threw it. As <strong>cdb</strong> (internally used by Adplus) is a native debugger it does not understand .NET metadata concept. In order to work with .NET types and methods we need to use a <em>native-managed translator</em>, example of which is <strong>a Windbg SOS extension</strong>. It&#8217;s by default placed in the .NET Framework installation directory and we just need to instruct Adplus how to load it. For this purpose we can modify the <code>postcommands</code> section of the configuration file. In Adplus v7 all actions must be defined as keywords and only in keywords we can issue the debugger commands. Our modified <code>log-exceptions-and-load-sos.adplus.config</code> file will look as follows:</p>
<p><pre class="brush: xml;">
&lt;adplus version=&quot;2&quot;&gt;
  &lt;keywords&gt;
    &lt;!-- 
    If you are attaching to the process just use: .loadby sos clr.
    
    If it's .net 2.0 you need to use: sxe -c &quot;.loadby sos mscorwks&quot; ld:mscorjit
    or only .loadby sos mscorwks if you are attaching to the process
     --&gt;
    &lt;keyword name=&quot;LoadSOS&quot;&gt;sxe -c &quot;.loadby sos clr;gn&quot; ld:clrjit&lt;/keyword&gt;
  &lt;/keywords&gt;
  &lt;settings&gt;
    &lt;runmode&gt;crash&lt;/runmode&gt;
    &lt;lastscriptcommand&gt;qd&lt;/lastscriptcommand&gt;
  &lt;/settings&gt;
  &lt;postcommands&gt;
    &lt;debugactions&gt;LoadSOS&lt;/debugactions&gt;
  &lt;/postcommands&gt;
  &lt;exceptions&gt;
    &lt;allexceptions&gt;
      &lt;actions1&gt;LOG&lt;/actions1&gt;
      &lt;returnaction1&gt;GN&lt;/returnaction1&gt;
      &lt;actions2&gt;LOG&lt;/actions2&gt;
      &lt;returnaction2&gt;GN&lt;/returnaction2&gt;
    &lt;/allexceptions&gt;
    &lt;allevents&gt;
      &lt;actions1&gt;LOG&lt;/actions1&gt;
      &lt;returnaction1&gt;GN&lt;/returnaction1&gt;
      &lt;actions2&gt;LOG&lt;/actions2&gt;
      &lt;returnaction2&gt;GN&lt;/returnaction2&gt;
    &lt;/allevents&gt;
  &lt;/exceptions&gt;
&lt;/adplus&gt;
</pre></p>
<h2>Logging the managed exception type and stack trace</h2>
<p>At this point we should have a SOS extension loaded into the debugger and thus be able to use commands that it provides. Let&#8217;s define two new keywords (help on the SOS commands can be found <a href="http://msdn.microsoft.com/en-us/library/bb190764.aspx" title="SOS commands reference">on MSDN</a>):</p>
<p><pre class="brush: plain;">
...
&lt;keyword name=&quot;PrintManagedException&quot;&gt;!PrintException&lt;/keyword&gt;
&lt;keyword name=&quot;ManagedStack&quot;&gt;!CLRStack -a&lt;/keyword&gt;
...
</pre></p>
<p>Next step is to define new exception type handling in the <code>exceptions</code> section of the configuration file. As I&#8217;ve already pointed the cdb debugger is not aware of .NET exception types. Fortunately all framework exceptions have the same code and so it&#8217;s easy to write a general handler for them. Our final <code>log-managed-exceptions.adplus.config</code> will be as follows (notice that we are concerned only about 1st chance exception):</p>
<p><pre class="brush: xml; highlight: [10,11,33,34,35,36,37,38];">
&lt;adplus version=&quot;2&quot;&gt;
  &lt;keywords&gt;
    &lt;!-- 
    If you are attaching to the process just use: .loadby sos clr.
    
    If it's .net 2.0 you need to use: sxe -c &quot;.loadby sos mscorwks&quot; ld:mscorjit
    or only .loadby sos mscorwks if you are attaching to the process
     --&gt;
    &lt;keyword name=&quot;LoadSOS&quot;&gt;sxe -c &quot;.loadby sos clr;gn&quot; ld:clrjit&lt;/keyword&gt;
    &lt;keyword name=&quot;PrintManagedException&quot;&gt;!PrintException&lt;/keyword&gt;
    &lt;keyword name=&quot;ManagedStack&quot;&gt;!CLRStack -a&lt;/keyword&gt;
  &lt;/keywords&gt;
  &lt;settings&gt;
    &lt;runmode&gt;crash&lt;/runmode&gt;
    &lt;lastscriptcommand&gt;qd&lt;/lastscriptcommand&gt;
  &lt;/settings&gt;
  &lt;postcommands&gt;
    &lt;debugactions&gt;LoadSOS&lt;/debugactions&gt;
  &lt;/postcommands&gt;
  &lt;exceptions&gt;
    &lt;allexceptions&gt;
      &lt;actions1&gt;LOG&lt;/actions1&gt;
      &lt;returnaction1&gt;GN&lt;/returnaction1&gt;
      &lt;actions2&gt;LOG&lt;/actions2&gt;
      &lt;returnaction2&gt;GN&lt;/returnaction2&gt;
    &lt;/allexceptions&gt;
    &lt;allevents&gt;
      &lt;actions1&gt;LOG&lt;/actions1&gt;
      &lt;returnaction1&gt;GN&lt;/returnaction1&gt;
      &lt;actions2&gt;LOG&lt;/actions2&gt;
      &lt;returnaction2&gt;GN&lt;/returnaction2&gt;
    &lt;/allevents&gt;
    &lt;exception code=&quot;clr&quot;&gt;
      &lt;actions1&gt;PrintManagedException;ManagedStack&lt;/actions1&gt;
      &lt;returnaction1&gt;GN&lt;/returnaction1&gt;
      &lt;actions2&gt;Log&lt;/actions2&gt;
      &lt;returnaction2&gt;GN&lt;/returnaction2&gt;
    &lt;/exception&gt;
  &lt;/exceptions&gt;
&lt;/adplus&gt;
</pre></p>
<p>After issuing:<br />
<pre class="brush: plain;">
&gt; adplus -c log-managed-exceptions.adplus.config -o c:\dumps -sc Thrower.exe
</pre><br />
in the Adplus_log we should have entries similar to this one:</p>
<p><pre class="brush: plain; highlight: [3,4,12,13];">
(ef8.145c): CLR exception - code e0434352 (first chance)
Exception object: 00000000024e1778
Exception type:   System.InvalidOperationException
Message:          ex1
InnerException:   &lt;none&gt;
StackTrace (generated):
&lt;none&gt;
StackTraceString: &lt;none&gt;
HResult: 80131509
OS Thread Id: 0x145c (0)
Child SP         IP               Call Site
000000000013ee38 000007fefda8cacd [HelperMethodFrame: 000000000013ee38] 
000000000013ef80 000007ff0016019f Thrower.Main(System.String[])
    PARAMETERS:
        args (0x000000000013f020) = 0x00000000024e16f0
    LOCALS:
        0x000000000013efa8 = 0x0000000000000000
        0x000000000013efb0 = 0x0000000000000000
</pre><br />
which gives us much more information about what happened in the application.</p>
<h2>Creating a dump when a managed exception occurs</h2>
<p>Very often the above Adplus_log is not enough to successfully diagnose the exception&#8217;s root cause. At these moments you might try to add just few more debugger commands to keywords section (for locks, processes or threads), but definitely the best solution would be to have a memory dump (snapshot) taken at the time of the failure. With a full memory dump you will be able to examine the stacks of all the threads, read garbage collector heap(s) or find lock acquisitions. Native debuggers (such as cdb or windbg) allow you to control what should be written to the dump file. Read help of a <code>.dump</code> command to see all the options available. However, in managed debugging scenarios, most of the times, you will need a full memory dump (created with the <code>\ma</code> switch). There is already an Adplus built-in keyword for creating this kind of dumps and its name is (I bet you guessed:)) <code>FullDump</code>. Let&#8217;s try it in our CLR first chance exceptions:</p>
<p><pre class="brush: xml; highlight: [4];">
...
  &lt;exceptions&gt;
    &lt;exception code=&quot;clr&quot;&gt;
      &lt;actions1&gt;PrintManagedException;ManagedStack;FullDump&lt;/actions1&gt;
      &lt;returnaction1&gt;GN&lt;/returnaction1&gt;
      &lt;actions2&gt;Log;FullDump&lt;/actions2&gt;
      &lt;returnaction2&gt;GN&lt;/returnaction2&gt;
    &lt;/exception&gt;
  &lt;/exceptions&gt;
...
</pre></p>
<p>After running the Thrower application under Adplus you should have noticed that four dump files were generated in the output directory. Unfortunately the time needed to write dumps to the disk impacts the application performance and responsiveness, especially when the number of thrown exceptions is high (though this often signifies a buggy application) or when the application consumes big chunks of memory. Sometimes your process runs in a strict environment and if it does not respond in a predefined amount of time it will be killed (IIS application pool might be a good example here). For reasons listed above and all others that might come to your head you should generate memory dumps carefully and only when it&#8217;s really necessary. It might be a good general practice to first run application using <code>log-managed-exceptions.adplus.config</code> file (eventually generating full dumps only for the failures &#8211; second chance exceptions). After analyzing the generated logs you should find exceptions that raise your suspicion and generate full dumps only for them. This is the subject of the next paragraph.</p>
<h2>Filtering exceptions</h2>
<p>So you&#8217;ve found exception types for which you would like Adplus to generate full memory dumps. There is a special SOS command <strong>!StopOnException</strong> that will help us here. When issued in the debugger it adds a new handling mechanism for the clr exception:</p>
<p><pre class="brush: plain; highlight: [6]; wrap-lines: false;">
0:000&gt; !soe -create System.ArgumentNullException 1
Breakpoint set
0:000&gt; sx
...
 clr - CLR exception - break - not handled
       Command: &quot;!soe  System.ArgumentNullException 1;.if(@$t1==0) {g} .else {.echo 'System.ArgumentNullException hit'}&quot;
...
</pre></p>
<p>Moving back to Adplus let&#8217;s define two new keywords in the keywords section:</p>
<p><pre class="brush: xml; wrap-lines: false;">
&lt;keywords&gt;
...
    &lt;keyword name=&quot;FullDumpOnSystemArgumentException&quot;&gt;!soe  System.ArgumentNullException 1;.if(@$t1==1) {.dump /ma /u ${AdpDumpDir}\FULLDUMP_SystemArgumentException_${AdpProcName}_.dmp}&lt;/keyword&gt;
    &lt;keyword name=&quot;FullDumpOnSystemInvalidOperationException&quot;&gt;!soe  System.InvalidOperationException 1;.if(@$t1==1) {.dump /ma /u ${AdpDumpDir}\FULLDUMP_SystemInvalidOperationException_${AdpProcName}_.dmp}&lt;/keyword&gt;
&lt;/keywords&gt;
...
</pre></p>
<p>Now, we can modify the exception handling logic and use our newly defined keywords (file <code>log-and-dump-specific-managed-exceptions.adplus.config</code> from samples):</p>
<p><pre class="brush: xml;">
...
  &lt;exceptions&gt;
    &lt;exception code=&quot;clr&quot;&gt;
      &lt;actions1&gt;
         PrintManagedException;
         ManagedStack;
         FullDumpOnSystemArgumentException;
         FullDumpOnSystemInvalidOperationException
      &lt;/actions1&gt;
      &lt;returnaction1&gt;GN&lt;/returnaction1&gt;
      &lt;actions2&gt;Log;FullDump&lt;/actions2&gt;
      &lt;returnaction2&gt;GN&lt;/returnaction2&gt;
    &lt;/exception&gt;
  &lt;/exceptions&gt;
...
</pre></p>
<p>After running Adplus with the new configuration file, it should generate two full dumps for the first chance <code>System.ArgumentNullException</code> and <code>System.InvalidOperationException</code> and one full dump for the second chance <code>System.NotImplementedException</code>. </p>
<p>I hope that you find this article helpful &#8211; if you would like to play with Adplus all configuration files as well as the Thrower application can be downloaded from <a href="http://lowleveldesign.codeplex.com/releases/view/80582" target="_blank">http://lowleveldesign.codeplex.com/releases/view/80582</a>. Happy debugging! <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />Filed under: <a href='http://lowleveldesign.wordpress.com/category/codeproject/'>CodeProject</a>, <a href='http://lowleveldesign.wordpress.com/category/debugging/'>Debugging</a>, <a href='http://lowleveldesign.wordpress.com/category/clr/exceptions/'>Exceptions</a>, <a href='http://lowleveldesign.wordpress.com/category/tools/'>Tools</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lowleveldesign.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lowleveldesign.wordpress.com/591/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lowleveldesign.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lowleveldesign.wordpress.com/591/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lowleveldesign.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lowleveldesign.wordpress.com/591/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lowleveldesign.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lowleveldesign.wordpress.com/591/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lowleveldesign.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lowleveldesign.wordpress.com/591/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lowleveldesign.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lowleveldesign.wordpress.com/591/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lowleveldesign.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lowleveldesign.wordpress.com/591/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=591&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lowleveldesign.wordpress.com/2012/01/16/adplus-managed-exceptions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e908dab390254580734da838f8050fba?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lowleveldesign</media:title>
		</media:content>
	</item>
		<item>
		<title>PDB files out of the debugger</title>
		<link>http://lowleveldesign.wordpress.com/2011/12/09/pdb-file-out-of-debugger/</link>
		<comments>http://lowleveldesign.wordpress.com/2011/12/09/pdb-file-out-of-debugger/#comments</comments>
		<pubDate>Fri, 09 Dec 2011 08:42:12 +0000</pubDate>
		<dc:creator>Sebastian Solnica</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[PDB files]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[pdb]]></category>
		<category><![CDATA[symbol files]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://lowleveldesign.wordpress.com/?p=514</guid>
		<description><![CDATA[I suppose that I don&#8217;t need to stress how important it is to have valid PDB files while debugging. Normally the PDB files are silently loaded by the debugger and you are happy to see all the symbols resolved in your modules window. Unfortunately you may also run into situation when the debugger will not [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=514&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I suppose that I don&#8217;t need to stress how important it is to have valid PDB files while debugging. Normally the PDB files are silently loaded by the debugger and you are happy to see all the symbols resolved in your modules window. Unfortunately you may also run into situation when the debugger will not be able to find matching symbols. The reason may be as trivial as a broken Internet connection or much more complicated like mismatched signatures. In this post I&#8217;m going to show you how to check your symbol files before debugging as well as how to extract the source file information from them. As there are different ways (and tools) to manipulate the symbol files I will present the ones that I am aware of, but feel free to leave comments about tools that I might have missed and I will try to update the post.</p>
<p><span id="more-514"></span></p>
<h2>Downloading a PDB file for a given PE file</h2>
<p>Some time ago Mike Stall blogged about <a title="Symbol APIs" href="http://blogs.msdn.com/b/jmstall/archive/2005/10/08/symbol-apis.aspx" target="_blank">different Symbol APIs</a> available for developers. As the PDB file format is a Microsoft&#8217;s secret all the tools that I&#8217;m presenting are just wrappers over those APIs. To work with PDB files we first need to get them. Let&#8217;s list the tools that will help us in it.</p>
<h3>symchk.exe</h3>
<p>Symbol Checker (Symchk.exe) is an application that compares executable files to symbol files to verify that the matching symbols are available. Symchk may also be used to populate your symbol cache. It can read symbol information from <strong>PE files</strong> (exe, dll), <strong>dump files</strong> and <strong>processes</strong>. It also supports recursive directory search and batch files. </p>
<p>We will start from loading symbols for <strong>the kernel32.dll library</strong>:<br />
<pre class="brush: plain; highlight: [4]; wrap-lines: false;">
c:\Windows\System32&gt;echo %_NT_SYMBOL_PATH%
SRV*C:\Symbols\MSS*http://referencesource.microsoft.com/symbols;SRV*C:\Symbols\MSS*http://msdl.microsoft.com/download/symbols

c:\Windows\System32&gt;symchk /v /os kernel32.dll
[SYMCHK] Searching for symbols to c:\Windows\System32\kernel32.dll in path SRV*C:\Symbols\MSS*http://referencesource.microsoft.com/symbols;SRV*C:\Symbols\MSS*http://msdl.microsoft.com/download/symbols
DBGHELP: Symbol Search Path: SRV*C:\Symbols\MSS*http://referencesource.microsoft.com/symbols;SRV*C:\Symbols\MSS*http://msdl.microsoft.com/download/symbols
[SYMCHK] Using search path &quot;SRV*C:\Symbols\MSS*http://referencesource.microsoft.com/symbols;SRV*C:\Symbols\MSS*http://msdl.microsoft.com/download/symbols&quot;
DBGHELP: No header for c:\Windows\System32\kernel32.dll.  Searching for image on disk
DBGHELP: c:\Windows\System32\kernel32.dll - OK
SYMSRV:  C:\Symbols\MSS\kernel32.pdb\9B30FD7CD6B44975BF34B43B6EF668212\kernel32.pdb not found
SYMSRV:  http://referencesource.microsoft.com/symbols/kernel32.pdb/9B30FD7CD6B44975BF34B43B6EF668212/kernel32.pdb not found
SYMSRV:  kernel32.pdb from http://msdl.microsoft.com/download/symbols: 704453 bytes - copied
DBGHELP: kernel32 - public symbols
         C:\Symbols\MSS\kernel32.pdb\9B30FD7CD6B44975BF34B43B6EF668212\kernel32.pdb
[SYMCHK] MODULE64 Info ----------------------
[SYMCHK] Struct size: 1680 bytes
[SYMCHK] Base: 0x0000000078D20000
[SYMCHK] Image size: 1175552 bytes
[SYMCHK] Date: 0x4e21213b
[SYMCHK] Checksum: 0x0012386d
[SYMCHK] NumSyms: 0
[SYMCHK] SymType: SymPDB
[SYMCHK] ModName: kernel32
[SYMCHK] ImageName: c:\Windows\System32\kernel32.dll
[SYMCHK] LoadedImage: c:\Windows\System32\kernel32.dll
[SYMCHK] PDB: &quot;C:\Symbols\MSS\kernel32.pdb\9B30FD7CD6B44975BF34B43B6EF668212\kernel32.pdb&quot;
[SYMCHK] CV: RSDS
[SYMCHK] CV DWORD: 0x53445352
[SYMCHK] CV Data:  kernel32.pdb
[SYMCHK] PDB Sig:  0
[SYMCHK] PDB7 Sig: {9B30FD7C-D6B4-4975-BF34-B43B6EF66821}
[SYMCHK] Age: 2
[SYMCHK] PDB Matched:  TRUE
[SYMCHK] DBG Matched:  TRUE
[SYMCHK] Line nubmers: FALSE
[SYMCHK] Global syms:  FALSE
[SYMCHK] Type Info:    FALSE
[SYMCHK] ------------------------------------
SymbolCheckVersion  0x00000002
Result              0x00030001
DbgFilename
DbgTimeDateStamp    0x4e21213b
DbgSizeOfImage      0x0011f000
DbgChecksum         0x0012386d
PdbFilename         C:\Symbols\MSS\kernel32.pdb\9B30FD7CD6B44975BF34B43B6EF668212\kernel32.pdb
PdbSignature        {9B30FD7C-D6B4-4975-BF34-B43B6EF66821}
PdbDbiAge           0x00000002
[SYMCHK] [ 0x00000000 - 0x00030001 ] Checked &quot;c:\Windows\System32\kernel32.dll&quot;

SYMCHK: FAILED files = 0
SYMCHK: PASSED + IGNORED files = 1
</pre><br />
As you can see in the verbose mode (<strong>/v switch</strong>) you receive a lot of information about what symchk is doing. We can even read which symbols API it is using (dbghelp messages). The <strong>/os switch</strong> informs symchk to print full paths of the symbol files in the output messages. After running this command the kernel32.pdb file should be in our symbol store. If you would like to index the whole System32 directory you would like to use the <strong>/r switch</strong> which informs symchk to recursively step through the provided directory and download symbols for all the files found, eg. <code>symchk /r /v c:\windows\system32\*.dll</code></p>
<p>Let&#8217;s try to load symbols for <strong>the notepad.exe process</strong>:<br />
<pre class="brush: plain; highlight: [7]; wrap-lines: false;">
c:\temp\symtest&gt;tasklist /FI &quot;IMAGENAME eq notepad.exe&quot;

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
notepad.exe                   2264 Console                    1      6 036 K

c:\temp\symtest&gt;symchk /ip 2264 /s SRV*.*http://msdl.microsoft.com/download/symbols

SYMCHK: FAILED files = 0
SYMCHK: PASSED + IGNORED files = 26
</pre><br />
With the <strong>/ip switch</strong> we can provide just process ID and symchk will download symbol files for all the modules loaded in the process. In this example we also used the <strong>/s switch</strong> which provides symchk with symbol path that it should use (overriding _NT_SYMBOL_PATH if set). In our case we were downloading symbol files from the Microsoft public server to the current directory. The listing of this directory after running this command will look as follows:<br />
<pre class="brush: plain; wrap-lines: false;">
c:\temp\symtest&gt;tree .
Folder PATH listing
Volume serial number is 00000002 C622:C13F
C:\TEMP\SYMTEST
├───advapi32.pdb
│   └───6AEFDCFF7F2A429B8532CD2BFDDF85D12
├───CLBCatQ.pdb
│   └───60B9D310C472440BA13F66BFF0FC39E32
├───comctl32.pdb
│   └───943BA638A2CD4D88A1C7E7418EAF796C1
├───comdlg32.pdb
│   └───631B57376F8549FDB2E7A8AB3D2D1FDF2
├───cryptbase.pdb
│   └───F03E074BB9E74C9F9BBFB0E42EF3A0AB2
├───dwmapi.pdb
│   └───8683ED0C3DBE4053883EC22FD9B4F2102
├───gdi32.pdb
│   └───FB9403C3B1304DA192C4D0E3485E25ED2
├───imm32.pdb
│   └───98F27BA5AEE541ECBEE00CD03AD50FEE2
├───kernel32.pdb
│   └───9B30FD7CD6B44975BF34B43B6EF668212
├───kernelbase.pdb
│   └───61044362232B410AA600843CEBFD11612
...
</pre><br />
Another interesting switch is (<strong>/id</strong>) which enables you to debug dump files. </p>
<p>Another great functionality of symchk.exe is something called <strong>manifest files</strong>. Manifest files contain information about all symbols that must be downloaded. You may then run symchk with <strong>/om switch</strong> which will produce the manifest file without downloading any symbols. Then you can copy the manifest file to any computer that has the Internet connection and download the symbol files using <strong>/im switch</strong>. The snippet below shows an usage example:</p>
<p><pre class="brush: plain; highlight: [1,16]; wrap-lines: false;">
c:\temp\symtest&gt;symchk /om notepad-symbols.man /ip 2264

SYMCHK: FAILED files = 0
SYMCHK: PASSED + IGNORED files = 26

c:\temp\symtest&gt;type notepad-symbols.man
notepad.pdb,36CFD5F9888C4483B522B9DB242D84782,1
notepad.exe,4a5bc9b335000,1
ntdll.pdb,6192BFDB9F04442995FFCB0BE95172E12,1
ntdll.dll,4ce7c8f91a9000,1
kernel32.pdb,9B30FD7CD6B44975BF34B43B6EF668212,1
kernel32.dll,4e21213b11f000,1
kernelbase.pdb,61044362232B410AA600843CEBFD11612,1
KernelBase.dll,4e21213c6c000,1
...
c:\temp\symtest&gt;symchk /im notepad-symbols.man /s SRV*.*http://msdl.microsoft.com/download/symbols

SYMCHK: FAILED files = 0
SYMCHK: PASSED + IGNORED files = 52
</pre></p>
<h3>dbh.exe</h3>
<p>This tool is a wrapper over the DbgHelp.dll library and uncovers almost all of its functionality. We will just look at the one usage example so if you would like to go deeper have a look at the Debugging Tools for Windows help. When you run dbh.exe with a module name as an argument it will automatically download the symbol files. So by simply calling <code>dbh c:\windows\system32\kernel32.dll info</code> you will download the symbol file (_NT_SYMBOL_PATH environment variable is used) and print information about it and its PE file (kernel32.dll):</p>
<p><pre class="brush: plain; highlight: [1]; wrap-lines: false;">
c:\temp&gt;dbh c:\windows\system32\kernel32.dll info

    SizeOfStruct : 0x690
     BaseOfImage : 0x1677721664x
       ImageSize : 0x1000000
   TimeDateStamp : 0x4e21213b
        CheckSum : 0x12386d
         NumSyms : 0x0
         SymType : SymPdb
      ModuleName : kernel32
       ImageName : c:\windows\system32\kernel32.dll
 LoadedImageName : c:\windows\system32\kernel32.dll
   LoadedPdbName : C:\Symbols\MSS\kernel32.pdb\9B30FD7CD6B44975BF34B43B6EF668212\kernel32.pdb
           CVSig : 0x53445352
          CVData : kernel32.pdb
          PdbSig : 0x0
        PdbSig70 : 0x9b30fd7c, 0xd6b4, 0x4975, 0xbf, 0x34, 0xb4, 0x3b, 0x6e, 0xf6, 0x68, 0x21
          PdbAge : 0x2
    PdbUnmatched : false
    DbgUnmatched : false
     LineNumbers : false
   GlobalSymbols : false
        TypeInfo : false
   SourceIndexed : false
   PublicSymbols : true
     MachineType : X64
</pre><br />
If you would like to see some verbose information about PDB files loaded use <strong>-n switch</strong>. To change the default symbol path (or override _NT_SYMBOL_PATH settings) use the <strong>-s: switch</strong>.</p>
<h3>dumpbin.exe</h3>
<p>You might be surprised that this tool appears here, but have you ever noticed its <strong>/PDBPATH[:VERBOSE] switch</strong>? Issuing the <code>dumpbin /pdbpath:verbose</code> on our kernel32.dll library will result in downloading the PDB file from the public symbol store:<br />
<pre class="brush: plain; highlight: [1]; wrap-lines: false;">
c:\temp\symtest&gt;dumpbin /pdbpath:verbose c:\windows\system32\kernel32.dll
Microsoft (R) COFF/PE Dumper Version 10.00.40219.01
Copyright (C) Microsoft Corporation.  All rights reserved.

Dump of file c:\windows\system32\kernel32.dll

File Type: DLL
  PDB file 'c:\windows\system32\kernel32.pdb' checked.  (File not found)
  PDB file 'c:\temp\symtest\kernel32.pdb' checked.  (File not found)
  PDB file found at 'C:\Symbols\MSS\kernel32.pdb\9B30FD7CD6B44975BF34B43B6EF668212\kernel32.pdb'

  Summary

        2000 .data
        A000 .pdata
       6E000 .rdata
        8000 .reloc
        1000 .rsrc
       9B000 .text
</pre></p>
<h2>Downloading source code from the source server</h2>
<h3>srctool.exe</h3>
<p>This tool is quite interesting as it allows you to check which source files are indexed in the PDB file and eventually extract them. With <strong>-r switch</strong> you may check which source code paths were hardcoded in the PDB file, eg.<br />
<pre class="brush: plain;">
c:\temp&gt;srctool -r ConsoleApplication1.pdb
D:\lab\symbols-lab\symbols\ConsoleApplication1\Program.cs
D:\lab\symbols-lab\symbols\ConsoleApplication1\AdvertQuickView.cs
</pre><br />
Without any switch srctool will examine the source server stream in the PDB file (if it exists) and print commands that will be executed to extract the source files, eg:</p>
<p><pre class="brush: plain; highlight: [1]; wrap-lines: false;">
c:\temp&gt;srctool ConsoleApplication1.pdb
[D:\lab\symbols-lab\symbols\ConsoleApplication1\Program.cs] cmd: cmd /c svn.exe cat &quot;svn://localhost/test2/Program.cs@1&quot; --non-interactive --username admin --password admin &gt; &quot;
[D:\lab\symbols-lab\symbols\ConsoleApplication1\AdvertQuickView.cs] cmd: cmd /c svn.exe cat &quot;svn://localhost/test2/AdvertQuickView.cs@1&quot; --non-interactive --username admin --password admin &gt; &quot;

ConsoleApplication1.pdb: 2 source files are indexed
</pre><br />
To run the commands and thus extract the source files you just need to add the <strong>-x switch</strong> to the above call. Additionally using the <strong>-d switch</strong> you may specify the directory to which the source files will be extracted (by default it&#8217;s the current directory).  </p>
<h3>pdbstr</h3>
<p>If you would like to have a better control over the source server stream you may check the pdbstr command. With its aid you can read and update the source server information in the PDB file. The source server stream is actually a text block with predefined sections (more info can be found <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms680641(v=vs.85).aspx" title="Source Server specification" target="_blank">here</a>). You can dump its content by issuing:<br />
<pre class="brush: plain;">
c:\temp&gt;pdbstr -r -p:ConsoleApplication1.pdb -s:srcsrv &gt; stream.txt
</pre><br />
The stream.txt file should contain something like:<br />
<pre class="brush: plain; wrap-lines: false;">
SRCSRV: ini ------------------------------------------------
VERSION=1
INDEXVERSION=2
VERCTRL=Subversion
DATETIME=Thu Nov 17 13:31:46 2011
SRCSRV: variables ------------------------------------------
SVNUSER=admin
SVNPASS=admin
SVN_EXTRACT_TARGET=%targ%\%fnbksl%(%var3%)\%var4%\%fnfile%(%var1%)
SVN_EXTRACT_CMD=cmd /c svn.exe cat &quot;%var2%%var3%@%var4%&quot; --non-interactive --username %svnuser% --password %svnpass% &gt; &quot;
%svn_extract_target%&quot;
SRCSRVTRG=%SVN_extract_target%
SRCSRVCMD=%SVN_extract_cmd%
SRCSRV: source files ---------------------------------------
D:\lab\symbols-lab\symbols\ConsoleApplication1\Program.cs*svn://localhost/*test2/Program.cs*1
D:\lab\symbols-lab\symbols\ConsoleApplication1\AdvertQuickView.cs*svn://localhost/*test2/AdvertQuickView.cs*1
SRCSRV: end ------------------------------------------------
</pre><br />
You can then apply the changes you&#8217;d like and save the new source stream definition back to the PDB file:<br />
<pre class="brush: plain;">
c:\temp&gt;pdbstr -w -p:ConsoleApplication1.pdb -s:srcsrv -i:stream.txt
</pre><br />
Pdbstr will not extract the source code files for you but from the source stream content you can easily read where to find them.</p>
<p>That will end our list of PDB tools &#8211; I hope that you will find it useful. Please remember to leave a comment if you know any other tool that should be enlisted here. </p>
<br />Filed under: <a href='http://lowleveldesign.wordpress.com/category/codeproject/'>CodeProject</a>, <a href='http://lowleveldesign.wordpress.com/category/debugging/pdb-files/'>PDB files</a>, <a href='http://lowleveldesign.wordpress.com/category/tools/'>Tools</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lowleveldesign.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lowleveldesign.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lowleveldesign.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lowleveldesign.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lowleveldesign.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lowleveldesign.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lowleveldesign.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lowleveldesign.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lowleveldesign.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lowleveldesign.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lowleveldesign.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lowleveldesign.wordpress.com/514/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lowleveldesign.wordpress.com/514/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lowleveldesign.wordpress.com/514/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=514&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lowleveldesign.wordpress.com/2011/12/09/pdb-file-out-of-debugger/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e908dab390254580734da838f8050fba?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lowleveldesign</media:title>
		</media:content>
	</item>
		<item>
		<title>Forget PowerPoint &#8211; make a slideshow in&#8230; a debugger :)</title>
		<link>http://lowleveldesign.wordpress.com/2011/11/20/slideshow-in-debugger/</link>
		<comments>http://lowleveldesign.wordpress.com/2011/11/20/slideshow-in-debugger/#comments</comments>
		<pubDate>Sun, 20 Nov 2011 13:34:27 +0000</pubDate>
		<dc:creator>Sebastian Solnica</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[debugger]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[pdb]]></category>
		<category><![CDATA[powerpoint]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://lowleveldesign.wordpress.com/?p=517</guid>
		<description><![CDATA[Few days ago I had a presentation in the Warsaw .NET Group about PDB files. To make the slideshow more attractive (or rather original:)) I decided to replace the PowerPoint with something more connected with the subject, such as&#8230; the Visual Studio debugger. The only question was how to actually achieve this. The idea grew [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=517&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Few days ago I had a presentation in the <a title="Warszawska Grup .NET" href="http://www.wg.net.pl/" target="_blank">Warsaw .NET Group</a> about PDB files. To make the slideshow more attractive (or rather original:)) I decided to replace the PowerPoint with something more connected with the subject, such as&#8230; the Visual Studio debugger. The only question was how to actually achieve this. The idea grew in my head after reading a brilliant <a title="Debugging Dynamically Generated Code (Reflection.Emit)" href="http://blogs.msdn.com/b/jmstall/archive/2005/02/03/366429.aspx" target="_blank">Mike Stall&#8217;s post about debugging dynamically generated code</a>. Mike shows in it how to emit sequence points for a text file of your choice and so bind this file with the generated MSIL. If done correctly, the debugger will load the text file, allowing you to step through its content and at the same time execute the emitted MSIL. So what if we could use the presentation table of contents as our source file and for each title (line of the table of contents) emit MSIL which will present a corresponding slide in the console window? This will actually make the debugger play the role of the PowerPoint:)</p>
<p><span id="more-517"></span></p>
<h2>Prepare the content</h2>
<p>Let&#8217;s start from a table of contents for a hypothetical 3-slides presentation:</p>
<p><pre class="brush: plain;">
Welcome

1. Slide1
1.1 Slide1.1
2. Slide2

Thank you
</pre></p>
<p>Save this content as a <code>toc.txt</code> file &#8211; this will be our source file. Now let&#8217;s prepare slides. You may create a sub-directory <code>slides</code> or even create a separate directories for each group of slides &#8211; as you will shortly see there is no restriction here. In our case let&#8217;s stay with the one-directory-for-all approach. Let&#8217;s now assume that we want some contents to be presented for slides entitled: <em>Welcome</em>, <em>1.1 Slide1.1</em> ,<em>2. Slide2</em> and <em>Thank you</em> (we omit <em>1. Slide1</em> by purpose). As mentioned previously the slides will be presented on the console so we may safely store their contents in text files named adequately: <em>welcome.txt</em>, <em>slide1.1.txt</em> and <em>slide2.txt</em>. Example content for a <em>welcome.txt</em> might be as follows:</p>
<p><pre class="brush: plain;">
                     SAMPLE PRESENTATION
                     ===================

                      Sebastian Solnica

              http://lowleveldesign.wordpress.com
</pre></p>
<p>Now we need to prepare a mapping file that will map the slide title with its corresponding content. Create a new text file and fill it with the following text:</p>
<p><pre class="brush: plain;">
Welcome
 slides\welcome.txt
1.1 Slide1.1
 slides\slide1.1.txt
2. Slide2
 slides\slide2.txt
Thank you
 thank-you.txt
</pre></p>
<p>Each indented line stores a path to the content of the slide with the title above it. The titles must be the same as in the <code>toc.txt</code> file and the file paths must be valid (however as you can see not all titles need to be mapped).</p>
<h2>Create the presentation <em>compiler</em></h2>
<p>Having the presentation content ready we now need to create an exe file that will be run by the debugger. I suppose that the easiest approach is to use classes from the <code>System.Reflection.Emit</code> namespace. The pseudo code for the <em>compiler</em> (or rather <em>emitter</em>) will be as follows:</p>
<p><pre class="brush: csharp;">
var asm = new DynamicAssembly()
MakeDebuggable(asm)

var mappingsContent = ReadFile(toc_slides.txt)
var mappings = StoreMappingsInDictionary(mappingsContent) // slide title -&gt; slide file

for each slideTitle in GetContent(toc.txt) {
  if (mappings.Contains(slideTitle)) {
    EmitMsilCodeThatWillReadAndPrintTheSlide(mappings[slideTitle]);
    MarkSequencePoint(currentLineNum); // binds a line of the source code with the emitted MSIL
  }
}

SaveAssembly(asm)
</pre></p>
<p>I will now explain few methods that occur in the code above that might have confused you (the C# source code that implements the above logic can be downloaded from <a href="http://lowleveldesign.codeplex.com/releases/view/77177" target="_blank">here</a>). <strong><code>MakeDebuggable</code></strong> is responsible for adding a <code>DebuggableAttribute</code> to the assembly. This attribute informs the JIT compiler that it should produce assembly code that will be debuggable (more <a href="http://blogs.msdn.com/b/rmbyers/archive/2005/06/26/432922.aspx">here</a>). To make the debugging process possible we also need to create a PDB file that will store the debug information for our module. <code>ModuleBuilder</code> contains a special method called <code>DefineDocument</code> that will do this for us. Here&#8217;s a C# code that implements all the logic described:</p>
<p><pre class="brush: csharp;">
Type daType = typeof(DebuggableAttribute);
ConstructorInfo daCtor = daType.GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) });
CustomAttributeBuilder daBuilder = new CustomAttributeBuilder(daCtor, new object[] { 
    DebuggableAttribute.DebuggingModes.DisableOptimizations | 
    DebuggableAttribute.DebuggingModes.Default });
assemblyBuilder.SetCustomAttribute(daBuilder);

ModuleBuilder module = assemblyBuilder.DefineDynamicModule(outputFileName, true); // &lt;-- pass 'true' to track debug info.

// Tell Emit about the source file that we want to associate this with. 
ISymbolDocumentWriter doc = module.DefineDocument(tableOfContentsPath, Guid.Empty, Guid.Empty, Guid.Empty);
</pre></p>
<p><strong><code>EmitMsilCodeThatWillReadAndPrintTheSlide</code></strong> emits MSIL that will open the slide file, read it at once and print the content to the console. Ildasm the code below and you will get it:) (or check <code>emitReadAndPrintSlideMethod</code> in <code>Program.cs</code> from <a href="http://lowleveldesign.codeplex.com/releases/view/77177" target="_blank">the slide compiler source code</a>):</p>
<p><pre class="brush: csharp;">
using (StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
   Console.Clear();
   Console.Write(reader.ReadToEnd());
}
</pre> </p>
<p>To make the assembly smaller you may consider putting this logic in a separate method and emit just calls to this method with adequate parameters (this is what I do in the sample code). For each slide printed we need to inform the debugger which line of the source code (or table of contents in our case:)) should be highlighted. For this purpose we use <code>MarkSequencePoint</code> method of the <code>ILGenerator</code> instance:</p>
<p><pre class="brush: csharp;">
ilGenerator.MarkSequencePoint(doc, currentLineNum, 1, currentLineNum, 100);
</pre></p>
<p>To make the debugging even more feasible I emit <code>System.Diagnostics.Debugger.Break()</code> call after the first sequence point (so even when starting with F5 the debugger should stop on the first slide).</p>
<h2>Compile and show:)</h2>
<p>By now we should have the presentation compiler and the presentation content (table of contents, slide files and slide title &lt;-&gt; slide file mapping file) ready. So it&#8217;s time to compile it and debug it:) If you are using my compiler run the following in the command window:</p>
<p><pre class="brush: plain;">
SlideCompiler.exe -files toc_slides.txt -o toc.exe toc.txt
</pre> </p>
<p>This should produce a <code>toc.exe</code> file (and <code>toc.pdb</code>) that you can now open in Visual Studio (<em>File-&gt;Open-&gt;Project/Solution&#8230;</em>). After pressing F5 you should see something like:</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/11/debugger-slideshow.png"><img src="http://lowleveldesign.files.wordpress.com/2011/11/debugger-slideshow.png?w=595&#038;h=480" alt="" title="Debugger Slideshow" width="595" height="480" class="aligncenter size-full wp-image-531" /></a></p>
<p>By pressing F11 or F10 you may advance the slides. To move back just select the line before the slide you want to show, press Ctrl+Shift+F10 and then F10. You may also place breakpoints on your slides:)</p>
<p>The code (and the sample presentation as well as my symbol presentation from WG.NET) can be found on <a href="http://lowleveldesign.codeplex.com/releases/view/77177" target="_blank">my blog samples site</a>.</p>
<p>Have fun and surprise you listeners on your next presentation! <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />Filed under: <a href='http://lowleveldesign.wordpress.com/category/codeproject/'>CodeProject</a>, <a href='http://lowleveldesign.wordpress.com/category/debugging/'>Debugging</a>, <a href='http://lowleveldesign.wordpress.com/category/tools/visual-studio/'>Visual Studio</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lowleveldesign.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lowleveldesign.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lowleveldesign.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lowleveldesign.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lowleveldesign.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lowleveldesign.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lowleveldesign.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lowleveldesign.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lowleveldesign.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lowleveldesign.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lowleveldesign.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lowleveldesign.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lowleveldesign.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lowleveldesign.wordpress.com/517/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=517&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lowleveldesign.wordpress.com/2011/11/20/slideshow-in-debugger/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e908dab390254580734da838f8050fba?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lowleveldesign</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/11/debugger-slideshow.png" medium="image">
			<media:title type="html">Debugger Slideshow</media:title>
		</media:content>
	</item>
		<item>
		<title>Debugging NHibernate: session management</title>
		<link>http://lowleveldesign.wordpress.com/2011/10/12/debugging-nhibernate-session/</link>
		<comments>http://lowleveldesign.wordpress.com/2011/10/12/debugging-nhibernate-session/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 20:46:58 +0000</pubDate>
		<dc:creator>Sebastian Solnica</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[debugger]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://lowleveldesign.wordpress.com/?p=481</guid>
		<description><![CDATA[Invalid session management is one of the common problems when using NHibernate and can lead to severe issues such as memory leaks or data inconsistency. In this post I am going to show you how to eliminate those pitfalls using the Visual Studio debugger. We will step through the process of opening and closing the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=481&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Invalid session management is one of the common problems when using NHibernate and can lead to severe issues such as memory leaks or data inconsistency. In this post I am going to show you how to eliminate those pitfalls using the Visual Studio debugger. We will step through the process of opening and closing the session. We will also have a look at its properties in order to check if entities are correctly persisted. Let&#8217;s start then from breaking into the session open event.</p>
<p><span id="more-481"></span></p>
<h2>Break into the session-open event</h2>
<p>The best place to break into the session creation process is the SessionImpl constructor. You just need to choose <em>New Breakpoint</em> from the Debug menu and then <em>Break at function&#8230;</em> (or Ctrl + B) and in the Function box type <strong>NHibernate.Impl.SessionImpl.SessionImpl</strong>. The debugger will probably complain that it can&#8217;t bind the breakpoint at this time &#8211; just ignore this message and confirm that you want to set your breakpoint. It&#8217;s confusing that CLR uses <em>.ctor</em> as a constructor name when VS prefers the class name (although sometimes after binding the breakpoint it shows locations such as <em>NHibernate.Impl.SessionImpl..ctor</em> so don&#8217;t worry &#8211; everything is fine;)). One more caveat &#8211; in Visual Studio when you create a function breakpoint it will be set on all functions which names match the pattern that you provided. In our case we will end up with three child breakpoints as there are three constructs of the SessionImpl object (have a look at the first screenshot). There is no rule on when to create the breakpoint, but if you want to trace all the sessions you probably want to set it before even starting the debugging process. </p>
<p>Now, let&#8217;s start the debugger and try to do some actions in the application that will require a new session. While starting have a look at the breakpoints dialog (<em>Debug</em> -&gt; <em>Windows</em> -&gt; <em>Breakpoints</em>) and see how magically our breakpoints become available. </p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/10/sessionimpl-breakpoint.png"><img src="http://lowleveldesign.files.wordpress.com/2011/10/sessionimpl-breakpoint.png?w=595&#038;h=147" alt="" title="sessionImpl-breakpoint" width="595" height="147" class="aligncenter size-full wp-image-492" /></a></p>
<p>If you correctly prepared your symbols and sources you should now become quite happy seeing:</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/10/breakpoint-hit.png"><img src="http://lowleveldesign.files.wordpress.com/2011/10/breakpoint-hit.png?w=595&#038;h=132" alt="" title="breakpoint-hit" width="595" height="132" class="aligncenter size-full wp-image-484" /></a></p>
<p>After the breakpoint was hit let&#8217;s examine the thread call stack:</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/10/call-stack.png"><img src="http://lowleveldesign.files.wordpress.com/2011/10/call-stack.png?w=595&#038;h=195" alt="" title="call-stack" width="595" height="195" class="aligncenter size-full wp-image-485" /></a></p>
<p>I marked with a red rectangle two frames that actually tell us everything. The session was opened on <em>Application</em>BeginRequest_ event by the default <em>ISessionFactory</em> implementation (<em>SessionFactoryImpl</em>). The great thing is that you can add <em>this</em> to the watch window and examine all the properties of the session. Also, you may set a breakpoint in the callstack and come back to <em>ISessionFactory</em> instance and check its properties too (like <em>currentSessionContext</em> that defines how long session will last and where it will be stored). </p>
<h2>Break into the session-close event</h2>
<p>In this paragraph we are going to step through the closing session process in order to find places where things may go off the rails. The closing process may be divided into two parts: flushing and actual closing. While flushing, NHibernate synchronizes the state of the session with the database, preparing an ordered collection of queries that must be then executed. We will start our analysis from placing an unresolved breakpoint on the <code>NHibernate.Impl.SessionImpl.Flush</code>. After firing the debugger (F5) our breakpoint should become alive and stop the execution at the following code:</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/10/cs1.png"><img src="http://lowleveldesign.files.wordpress.com/2011/10/cs1.png?w=595&#038;h=226" alt="" title="cs1" width="595" height="226" class="aligncenter size-full wp-image-486" /></a></p>
<p>The upper part of the picture contains the current call stack and the bottom part &#8211; the code. Normally you should first check if the <code>Flush</code> is called from where you planned it (in my case it was called while committing the transaction in response to the <code>Application_EndRequest</code> event &#8211; so no surprise here). We will be interested in the <code>flushEventListener[i].OnFlush(new FlushEvent(this))</code> line as this is where the hard work is done. If you didn&#8217;t provide any own <code>IFlushListener</code> implementations to NHibernate the default one (<code>DefaultFlushListener</code>) will be used:</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/10/cs2.png"><img src="http://lowleveldesign.files.wordpress.com/2011/10/cs2.png?w=595&#038;h=234" alt="" title="cs2" width="595" height="234" class="aligncenter size-full wp-image-487" /></a></p>
<p>The marked lines are the most interesting. <code>FlushEverythingToExecution</code> checks the session objects states and prepares the queries, when <code>PerformExecutions</code> (as its name suggests) executes the queries against the database. At this moment it might be interesting to check what objects are stored in the session entity dictionary and what are their properties. To accomplish that expand the <code>@event.Session</code> object and choose <code>PersistenceContext</code> property of the <code>SessionImpl</code> object or just add <code>((NHibernate.Impl.SessionImpl)(@event.Session)).PersistenceContext</code> expression to your watch window. Browse through the <code>EntitiesByKey</code> and <code>CollectionsByKey</code> properties.</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/10/cs3.png"><img src="http://lowleveldesign.files.wordpress.com/2011/10/cs3.png?w=595&#038;h=234" alt="" title="cs3" width="595" height="234" class="aligncenter size-full wp-image-488" /></a></p>
<p>The comment over <code>FlushEntities</code> explains exactly what this method does:</p>
<p><pre class="brush: csharp;">    
    // 1. detect any dirty entities
    // 2. schedule any entity updates
    // 3. search out any reachable collections
    private void FlushEntities(FlushEvent @event)
    {
    // other code goes here ...
</pre></p>
<p>In the code below you can see that it iterates through the <code>EntityEntries</code> collection firing <code>OnFlushEntity</code> event for each entity with the correct status:</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/10/cs4.png"><img src="http://lowleveldesign.files.wordpress.com/2011/10/cs4.png?w=595&#038;h=327" alt="" title="cs4" width="595" height="327" class="aligncenter size-full wp-image-489" /></a></p>
<p>The selected line above might be an interesting place for a conditional breakpoint filtering entries that we are interested in, like <code>entry.Id.Equals(1)</code> or <code>entry.EntityName.Equals("NHibernate.Example.Web.Models.Item")</code>. Our next place to visit will be <code>DefaultFlushEntityEventListener</code> and its <code>OnFlushEntity</code> handler:</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/10/cs5.png"><img src="http://lowleveldesign.files.wordpress.com/2011/10/cs5.png?w=595&#038;h=441" alt="" title="cs5" width="595" height="441" class="aligncenter size-full wp-image-490" /></a></p>
<p>The first red rectangle selects the code that checks the entity status &#8211; whether its properties had changed from loading or it was deleted or it&#8217;s a new entity. You may debug this code if you find that your object is not being updated, but before you get your hands dirty you may first check if the <code>SessionImpl.ActionQueues</code> is being updated by this method. <code>ActionQueues</code> as its name suggests contains actions that must be executed in order to synchronize the session with the database. They are grouped into queues based on their category: insertions, updated, deletions, collectionCreations, collectionUpdates, collectionRemovals. At this point you may wish to check if those collections contain a valid number of elements (or even the correct number of <em>dirty</em> properties). After filling the action queues there comes a time to translate them to SQL queries. This is done in the <code>PerformExecutions</code> method of the <code>DefaultFlushingEventListner</code> (or rather <code>AbstractFlushingEventListener</code>):</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/10/cs6.png"><img src="http://lowleveldesign.files.wordpress.com/2011/10/cs6.png?w=595&#038;h=195" alt="" title="cs6" width="595" height="195" class="aligncenter size-full wp-image-491" /></a></p>
<p>Internally <code>ExecuteActions</code> calls <code>NHibernate.Engine.ActionQueue.ExecuteActions</code> method which iterates through all the actions in all queues calling their <code>Execute</code> method, which internally prepares SQL queries (<code>Persister</code>&#8216;s <code>Update</code> method) and (if configured) puts them into batches or executes immediately.</p>
<p>This would be the end of the description of the session flushtprocess. There is one more thing that needs some explanation &#8211; session&#8217;s closing. Fortunately for you, probably already bored readers;), this method is fairly simple and it&#8217;s main role is to close all opened connections and dispose internal NHibernate objects (as batchers, transaction wrappers etc.).</p>
<p>I hope that this post revealed some of the mysteries behind NHibernate session management and will help you in your future struggles with NHibernate.</p>
<br />Filed under: <a href='http://lowleveldesign.wordpress.com/category/debugging/'>Debugging</a>, <a href='http://lowleveldesign.wordpress.com/category/nhibernate-2/'>NHibernate</a>, <a href='http://lowleveldesign.wordpress.com/category/tools/visual-studio/'>Visual Studio</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lowleveldesign.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lowleveldesign.wordpress.com/481/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lowleveldesign.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lowleveldesign.wordpress.com/481/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lowleveldesign.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lowleveldesign.wordpress.com/481/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lowleveldesign.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lowleveldesign.wordpress.com/481/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lowleveldesign.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lowleveldesign.wordpress.com/481/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lowleveldesign.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lowleveldesign.wordpress.com/481/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lowleveldesign.wordpress.com/481/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lowleveldesign.wordpress.com/481/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=481&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lowleveldesign.wordpress.com/2011/10/12/debugging-nhibernate-session/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e908dab390254580734da838f8050fba?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lowleveldesign</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/10/sessionimpl-breakpoint.png" medium="image">
			<media:title type="html">sessionImpl-breakpoint</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/10/breakpoint-hit.png" medium="image">
			<media:title type="html">breakpoint-hit</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/10/call-stack.png" medium="image">
			<media:title type="html">call-stack</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/10/cs1.png" medium="image">
			<media:title type="html">cs1</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/10/cs2.png" medium="image">
			<media:title type="html">cs2</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/10/cs3.png" medium="image">
			<media:title type="html">cs3</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/10/cs4.png" medium="image">
			<media:title type="html">cs4</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/10/cs5.png" medium="image">
			<media:title type="html">cs5</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/10/cs6.png" medium="image">
			<media:title type="html">cs6</media:title>
		</media:content>
	</item>
		<item>
		<title>Debugging NHibernate: prepare symbol files</title>
		<link>http://lowleveldesign.wordpress.com/2011/10/02/debugging-nhibernate-prepare-symbol-files/</link>
		<comments>http://lowleveldesign.wordpress.com/2011/10/02/debugging-nhibernate-prepare-symbol-files/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 20:37:21 +0000</pubDate>
		<dc:creator>Sebastian Solnica</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[pdb]]></category>
		<category><![CDATA[sourcepack]]></category>

		<guid isPermaLink="false">http://lowleveldesign.wordpress.com/?p=467</guid>
		<description><![CDATA[To be able to debug the NHibernate source code the debugger must know how to find it. If you are using the 3.0.0 version of NHibernate you may use http://www.symbolsource.org configuring Visual Studio to use their symbol store. If your NHibernate version is different you need to either compile NHibernate on your own and reference [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=467&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>To be able to debug the NHibernate source code the debugger must know how to find it. If you are using the 3.0.0 version of NHibernate you may use <a href="http://www.symbolsource.org">http://www.symbolsource.org</a> configuring Visual Studio to use their symbol store. If your NHibernate version is different you need to either compile NHibernate on your own and reference the produced binaries in your application build process or make use of the <strong><a href="http://sourcepack.codeplex.com">sourcepack</a></strong> script. Here I will describe the second approach (especially because I&#8217;m the author of the sourcepack and I need to advertise it somehow <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).<br />
<span id="more-467"></span><br />
 To use <strong>sourcepack</strong> you will need to install Debugging Tools for Windows (you may install them from the <a href="http://www.microsoft.com/download/en/details.aspx?id=11800">WDK image</a>) and powershell v2. Next step is to download NHibernate binaries (you should have them already in your application bin folder) and NHibernate sources from their <a href="http://sourceforge.net/projects/nhibernate/files/NHibernate/">sourceforge page</a>. </p>
<p>Now, we are ready to index the NHibernate symbol (pdb) files with the zipped sources. Open powershell console and type:</p>
<p><pre class="brush: plain;">
.\sourcepack.ps1 -sourcesRoot &quot;d:\CSharp\NH\NH\nhibernate\&quot; -sources C:\src\NHibernate-3.1.0.GA-src.zip -symbols C:\temp\sample-app\bin -archiverCommandPath C:\bin\7za\7za.exe -verbose
</pre></p>
<p>where:</p>
<ul>
<li><em>d:\CSharp\NH\NH\nhibernate</em> is a path to the source root on a computer where the NHibernate was built (you may check this path using <em>srctool.exe</em> or <em>dbh.exe</em> from the Debugging Tools for Windows &#8211; please have a look at my <a href="http://lowleveldesign.wordpress.com">blog</a> for usage examples)</li>
<li><em>C:\src\NHibernate-3.1.0.GA-src.zip</em> is a place where you put the downloaded source codes</li>
<li><em>C:\temp\sample-app\bin</em> is a place where you have your application binaries (dlls + pdbs)</li>
<li><em>C:\bin\7za\7za.exe</em> sourcepack requires a path to the 7za command that will be used by the debugger to extract the necessary source files (sourcepack release already contains the 7za.exe application so just copy it someplace)</li>
</ul>
<p>After running the command you should see some yellow (verbose) messages and NHibernate pdb files are now linked with the source code zip file. It&#8217;s time to test if the debugger will be able to successfully extract them. For this purpose you should again use <em>srctool.exe</em> (it&#8217;s located in the <em>srcsrv</em> folder of the Debugging Tools for Windows installation):</p>
<p><pre class="brush: plain;">
srctool -l:*AbstractSessionImpl.cs NHibernate.pdb -x -d:c:\temp\nh-test
</pre></p>
<p>The ouput of the upper command should be:</p>
<p><pre class="brush: plain;">
c:\temp\nh-test\src\NHibernate\Impl\AbstractSessionImpl.cs

NHibernate.pdb: 1 source files were extracted
</pre></p>
<p>If you saw something different you probably made some mistake in the indexing and you will need to rerun it (I know it&#8217;s tedious and I have plans to make sourcepack usage a little bit more pleasant). If the previous sentence does not apply to your situation you are ready to fire Visual Studio and start debugging NHibernate sources with your brand new symbol files <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<br />Filed under: <a href='http://lowleveldesign.wordpress.com/category/debugging/'>Debugging</a>, <a href='http://lowleveldesign.wordpress.com/category/nhibernate-2/'>NHibernate</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lowleveldesign.wordpress.com/467/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lowleveldesign.wordpress.com/467/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lowleveldesign.wordpress.com/467/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lowleveldesign.wordpress.com/467/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lowleveldesign.wordpress.com/467/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lowleveldesign.wordpress.com/467/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lowleveldesign.wordpress.com/467/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lowleveldesign.wordpress.com/467/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lowleveldesign.wordpress.com/467/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lowleveldesign.wordpress.com/467/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lowleveldesign.wordpress.com/467/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lowleveldesign.wordpress.com/467/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lowleveldesign.wordpress.com/467/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lowleveldesign.wordpress.com/467/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=467&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lowleveldesign.wordpress.com/2011/10/02/debugging-nhibernate-prepare-symbol-files/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e908dab390254580734da838f8050fba?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lowleveldesign</media:title>
		</media:content>
	</item>
		<item>
		<title>Sourcepack released</title>
		<link>http://lowleveldesign.wordpress.com/2011/08/26/sourcepack-released/</link>
		<comments>http://lowleveldesign.wordpress.com/2011/08/26/sourcepack-released/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 14:51:41 +0000</pubDate>
		<dc:creator>Sebastian Solnica</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[pdb]]></category>
		<category><![CDATA[powershell]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[source server]]></category>
		<category><![CDATA[symbol file]]></category>

		<guid isPermaLink="false">http://lowleveldesign.wordpress.com/?p=448</guid>
		<description><![CDATA[Yesterday I released a first version of sourcepack. The sourcepack is a powershell script which examines and then modifies the PDB files in the given directory to make them reference the source code archive file. It may be considered as just another tool for indexing the PDB files which uses the archive file (zip, 7z [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=448&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Yesterday I released a first version of sourcepack. The sourcepack is a powershell script which examines and then modifies the PDB files in the given directory to make them reference the source code archive file. It may be considered as just another tool for indexing the PDB files which uses the archive file (zip, 7z or any other) as a source code repository. So the extract operation will simply consists of calling one of the packer applications (currently 7za.exe) with correct arguments.The processed PDB files may be then copied to the symbols directory (configured in your debugger) and the debugger will seamlessly extract the source files that are needed for you to debug the library code. </p>
<p>I also added a new page to the blog entitled <a href="http://lowleveldesign.wordpress.com/my-projects/" title="My Projects" target="_blank">My Projects</a> and I hope that its content will grow as the time flies by:) Enough said, if you are interested in sourcepack please visit <a href="http://sourcepack.codeplex.com" title="http://sourcepack.codeplex.com" target="_blank">sourcepack.codeplex.com</a> and read <a href="https://docs.google.com/document/d/13VM59LEuNps66TK_vITqKd1TPlUtKDaOg9T2dLnFXnE/edit?hl=en_US" title="project documentation" target="_blank">some documentation</a>.</p>
<br />Filed under: <a href='http://lowleveldesign.wordpress.com/category/debugging/'>Debugging</a>, <a href='http://lowleveldesign.wordpress.com/category/scripts/'>Scripts</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lowleveldesign.wordpress.com/448/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lowleveldesign.wordpress.com/448/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lowleveldesign.wordpress.com/448/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lowleveldesign.wordpress.com/448/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lowleveldesign.wordpress.com/448/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lowleveldesign.wordpress.com/448/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lowleveldesign.wordpress.com/448/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lowleveldesign.wordpress.com/448/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lowleveldesign.wordpress.com/448/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lowleveldesign.wordpress.com/448/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lowleveldesign.wordpress.com/448/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lowleveldesign.wordpress.com/448/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lowleveldesign.wordpress.com/448/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lowleveldesign.wordpress.com/448/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=448&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lowleveldesign.wordpress.com/2011/08/26/sourcepack-released/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e908dab390254580734da838f8050fba?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lowleveldesign</media:title>
		</media:content>
	</item>
		<item>
		<title>Global.asax in ASP.NET</title>
		<link>http://lowleveldesign.wordpress.com/2011/07/20/global-asax-in-asp-net/</link>
		<comments>http://lowleveldesign.wordpress.com/2011/07/20/global-asax-in-asp-net/#comments</comments>
		<pubDate>Wed, 20 Jul 2011 19:18:09 +0000</pubDate>
		<dc:creator>Sebastian Solnica</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[global.asax]]></category>
		<category><![CDATA[howitworks]]></category>

		<guid isPermaLink="false">http://lowleveldesign.wordpress.com/?p=368</guid>
		<description><![CDATA[The Global.asax, also known as the ASP.NET application file, is used to handle application-level and session-level events. Although its structure is pretty simple and it&#8217;s easy to have one in the project, many developers don&#8217;t know exactly how it works. This post aims at revealing some of the mystery behind this file as well as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=368&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The Global.asax, also known as the ASP.NET application file, is used to handle application-level and session-level events. Although its structure is pretty simple and it&#8217;s easy to have one in the project, many developers don&#8217;t know exactly how it works. This post aims at revealing some of the mystery behind this file as well as providing you with some good usage examples.<br />
<span id="more-368"></span><br />
Let&#8217;s first have a look at a sample Global.asax file:<br />
<pre class="brush: csharp; wrap-lines: false;">
&lt;%@ Application Language=&quot;C#&quot; %&gt;
&lt;%@ Import Namespace=&quot;System.Diagnostics&quot; %&gt;

&lt;script runat=&quot;server&quot;&gt;
    public Guid AppId = Guid.NewGuid();

    public String TestMessage;

    public String GetAppDescription(String eventName)
    {
        StringBuilder builder = new StringBuilder();

        builder.AppendFormat(&quot;-------------------------------------------{0}&quot;, Environment.NewLine);
        builder.AppendFormat(&quot;Event: {0}{1}&quot;, eventName, Environment.NewLine);
        builder.AppendFormat(&quot;Guid: {0}{1}&quot;, AppId, Environment.NewLine);
        builder.AppendFormat(&quot;Thread Id: {0}{1}&quot;, System.Threading.Thread.CurrentThread.ManagedThreadId, Environment.NewLine);
        builder.AppendFormat(&quot;Appdomain: {0}{1}&quot;, AppDomain.CurrentDomain.FriendlyName, Environment.NewLine);
        builder.AppendFormat(&quot;TestMessage: {0}{1}&quot;, TestMessage, Environment.NewLine);
        builder.Append((System.Threading.Thread.CurrentThread.IsThreadPoolThread ? &quot;Pool Thread&quot; : &quot;No Thread&quot;) + Environment.NewLine);

        return builder.ToString();
    }

    void Application_Start(object sender, EventArgs e) 
    {
        TestMessage = &quot;not null&quot;;

        // Code that runs on application startup
        Trace.WriteLine(GetAppDescription(&quot;Application_Start&quot;));
    }

    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown
        Trace.WriteLine(GetAppDescription(&quot;Application_End&quot;));
    }

    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs
        Trace.WriteLine(GetAppDescription(&quot;Application_Error&quot;));
    }

    void Application_BeginRequest(object sender, EventArgs e)
    {
        Trace.WriteLine(GetAppDescription(&quot;Application_BeginRequest&quot;));
    }

    void Application_EndRequest(object sender, EventArgs e)
    {
        Trace.WriteLine(GetAppDescription(&quot;Application_EndRequest&quot;));
    } 
&lt;/script&gt;
</pre><br />
Global.asax is compiled to its own assembly &#8211; if you publish the web project from Visual Studio you can find App_global.asax.dll in the bin directory, otherwise it will go to c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\&lt;appname&gt;. After decompiling the produced assembly we will receive something like (methods are collapsed for clarity):<br />
<pre class="brush: csharp;">
namespace ASP
{
	[CompilerGlobalScope]
	public class global_asax : HttpApplication
	{
		private static bool __initialized;
		public Guid AppId = Guid.NewGuid();
		public String TestMessage;

		protected DefaultProfile Profile
		{
			get
			{
				return (DefaultProfile)base.Context.Profile;
			}
		}
		// events go here
		[DebuggerNonUserCode]
		public global_asax()
		{
			if (!global_asax.__initialized)
			{
				global_asax.__initialized = true;
			}
		}
	}
}
</pre><br />
From the above code we can see that a new class (<strong>global_asax</strong>) was created in ASP namespace which inherits from the <strong>HttpApplication</strong>. HttpApplication is an interesting class itself. It implements the ASP.NET request pipeline, invoking HttpModules, page event handlers etc. A quite common mistake is to think of the HttpApplication (global_asax) as a singleton shared by all the requests. The truth is that each request has its own instance of the HttpApplication class. To be more specific ASP.NET runtime keeps two pools of HttpApplication objects. First is a special pool with HttpApplication objects used for application level events (such as Application_Start, Application_End <del datetime="2011-08-18T09:10:30+00:00">and Application_Error</del><em>(Application_Error is served by normal HttpApplication instance &#8211; thanks Denis for spotting the mistake here!)</em>), second pool contains instances used in requests to serve all other types of events. Which class is then responsible for managing those pools? Here the <strong>HttpApplicationFactory</strong> comes into play. There is only one instance of this class per HttpRuntime and beside managing app pools it is also responsible for compiling Global.asax and ensuring that Application_Start/End events are called only once.</p>
<p>To prove what I described let&#8217;s use the above Global.asax file in a very simple web application. We will use the System.Diagnostics.Trace so some changes to the web.config file are required:<br />
<pre class="brush: xml; wrap-lines: false;">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;configuration&gt;
  &lt;system.diagnostics&gt;
    &lt;trace autoflush=&quot;true&quot;&gt;
      &lt;listeners&gt;
        &lt;add name=&quot;LogFile&quot; type=&quot;System.Diagnostics.TextWriterTraceListener&quot; initializeData=&quot;webapp.log&quot;/&gt;
      &lt;/listeners&gt;
    &lt;/trace&gt;
  &lt;/system.diagnostics&gt;
  &lt;system.codedom&gt;
    &lt;compilers&gt;
      &lt;compiler language=&quot;c#&quot; extension=&quot;.cs&quot; compilerOptions=&quot;/d:TRACE&quot; type=&quot;Microsoft.CSharp.CSharpCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&quot; warningLevel=&quot;1&quot;/&gt;
    &lt;/compilers&gt;
  &lt;/system.codedom&gt;
  &lt;system.web&gt;
    &lt;compilation debug=&quot;true&quot; targetFramework=&quot;4.0&quot;/&gt;
  &lt;/system.web&gt;
&lt;/configuration&gt;
</pre><br />
After the first client request your webapp.log file should cotain something similar to:<br />
<pre class="brush: plain;">
-------------------------------------------
Event: Application_Start
Guid: d8ab181d-b1f0-4733-83c1-04e6af5e6038
Thread Id: 1
Appdomain: /LM/W3SVC/3/ROOT-1-129556455331183204
TestMessage: not null
No Thread

-------------------------------------------
Event: Application_BeginRequest
Guid: 22089cce-f79a-4123-b455-e7f9e1091dd5
Thread Id: 5
Appdomain: /LM/W3SVC/3/ROOT-1-129556455331183204
TestMessage: 
Pool Thread

-------------------------------------------
Event: Page_Load
Guid: 22089cce-f79a-4123-b455-e7f9e1091dd5
Thread Id: 5
Appdomain: /LM/W3SVC/3/ROOT-1-129556455331183204
TestMessage: 
Pool Thread

-------------------------------------------
Event: Application_EndRequest
Guid: 22089cce-f79a-4123-b455-e7f9e1091dd5
Thread Id: 5
Appdomain: /LM/W3SVC/3/ROOT-1-129556455331183204
TestMessage: 
Pool Thread
</pre><br />
The different guids for Application_Start and Application_&#8230;Request events prove that there were two global_asax instances involved in processing the request. The first one is the <em>special</em> one and will be stored in the <em>special</em> pool (probably reused for Application_End/Application_Error event), the second one is a normal instance that will be reused in any further requests. Now look at the TestMessage property value &#8211; it was set only for the HttpApplication instance that was created as the first one. That assures us that the <strong>Application_Start is called only once in the web application lifetime</strong> (and not for every newly created HttpApplication instance).</p>
<p>So what&#8217;s the correct way of using <strong>global.asax</strong>? Firstly, <strong>remember</strong>:</p>
<ul>
<li><strong>It&#8217;s not a singleton.</strong></li>
<li><strong>Application_Start/End events are called only once.</strong></li>
<li><strong>There is one instance of global_asax per request and additionally there are instances for <em>special</em> events</strong></li>
</ul>
<p>Secondly, try to <strong>apply</strong> those guidelines to your Global.asax files:</p>
<ul>
<li><strong>All private fields should be initialized in the constructor.</strong></li>
<li><strong>Static fields may be initialized either in the Application_Start or static constructor.</strong></li>
<li><strong>Don&#8217;t use lock blocks &#8211; your request possesses this instance of the glboal_asax.</strong></li>
</ul>
<p>You can stop reading here if what I wrote is satisfactory for you. If you still have some doubts and would like to dig deeper keep on reading:) &#8211; I will show you how to look at the ASP.NET internals with the SOS debugger extension. Basically you start with attaching to the w3wp.exe process that your application is running in. Then load sos (replace clr with mscorwks if it&#8217;s .NET 2.0):<br />
<pre class="brush: plain;">
.loadby sos clr
</pre><br />
Then, let&#8217;s find the HttpApplicationFactory instance (highlighted):<br />
<pre class="brush: plain; highlight: [9];">
0:024&gt; !DumpHeap -type System.Web.HttpApplicationFactory
------------------------------
Heap 0
         Address               MT     Size
total 0 objects
------------------------------
Heap 1
         Address               MT     Size
000000013ff40e78 000007fee65c1900      136     
total 0 objects
------------------------------
total 0 objects
Statistics:
              MT    Count    TotalSize Class Name
000007fee65c1900        1          136 System.Web.HttpApplicationFactory
Total 1 objects
</pre><br />
Then dump its content &#8211; I highlighted the special and normal application pools (which are actually of type System.Collections.Stack):<br />
<pre class="brush: plain; highlight: [16,19]; wrap-lines: false;">
0:024&gt; !do 000000013ff40e78 
Name:        System.Web.HttpApplicationFactory
MethodTable: 000007fee65c1900
EEClass:     000007fee63147a8
Size:        136(0x88) bytes
File:        C:\Windows\Microsoft.Net\assembly\GAC_64\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll
Fields:
              MT    Field   Offset                 Type VT     Attr            Value Name
000007fee8b1d6e8  4000bf3       78       System.Boolean  1 instance                1 _inited
000007fee8b169d0  4000bf4        8        System.String  0 instance 000000013ff41070 _appFilename
000007fee8b1f8a0  4000bf5       10 ...tions.ICollection  0 instance 0000000000000000 _fileDependencies
000007fee8b1d6e8  4000bf6       79       System.Boolean  1 instance                1 _appOnStartCalled
000007fee8b1d6e8  4000bf7       7a       System.Boolean  1 instance                0 _appOnEndCalled
000007fee65c1988  4000bf8       18 ...pApplicationState  0 instance 000000013ff410c8 _state
000007fee8b18358  4000bf9       20          System.Type  0 instance 000000013ff40e48 _theApplicationType
000007fee8b2d360  4000bfa       28 ...Collections.Stack  0 instance 000000013ff40f00 _freeList
000007fee8b1c8b8  4000bfb       60         System.Int32  1 instance                1 _numFreeAppInstances
000007fee8b1c8b8  4000bfc       64         System.Int32  1 instance                1 _minFreeAppInstances
000007fee8b2d360  4000bfd       30 ...Collections.Stack  0 instance 000000013ff40f98 _specialFreeList
000007fee8b1c8b8  4000bfe       68         System.Int32  1 instance                1 _numFreeSpecialAppInstances
... continued ...
</pre><br />
To find out which HttpApplication instances are stored in the particular pool you need to dump the pool and then its internal array content:<br />
<pre class="brush: plain; highlight: [9,20]; wrap-lines: false;">
0:024&gt; !do 000000013ff40f00 
Name:        System.Collections.Stack
MethodTable: 000007fee8b2d360
EEClass:     000007fee87561c0
Size:        40(0x28) bytes
File:        C:\Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Fields:
              MT    Field   Offset                 Type VT     Attr            Value Name
000007fee8b1aed8  4000b9f        8      System.Object[]  0 instance 000000013ff40f28 _array
000007fee8b1c8b8  4000ba0       18         System.Int32  1 instance                1 _size
000007fee8b1c8b8  4000ba1       1c         System.Int32  1 instance                1 _version
000007fee8b15b28  4000ba2       10        System.Object  0 instance 0000000000000000 _syncRoot
0:024&gt; !da 000000013ff40f28 
Name:        System.Object[]
MethodTable: 000007fee8b1aed8
EEClass:     000007fee869fdb8
Size:        112(0x70) bytes
Array:       Rank 1, Number of elements 10, Type CLASS
Element Methodtable: 000007fee8b15b28
[0] 000000013ff76bc8
[1] null
[2] null
[3] null
[4] null
[5] null
[6] null
[7] null
[8] null
[9] null
</pre><br />
To check that this instance is the one that we got in the log file we need to look through its properties and compare for example the guid value:<br />
<pre class="brush: plain; highlight: [11,15]; wrap-lines: false;">
0:024&gt; !do 000000013ff76bc8
Name:        ASP.global_asax
MethodTable: 000007ff00147a80
EEClass:     000007ff001b25f0
Size:        240(0xf0) bytes
File:        C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\8fbb8387\1608fccf\assembly\dl3\7d155608\c7473357_d746cc01\App_global.asax.dll
Fields:
              MT    Field   Offset                 Type VT     Attr            Value Name
000007fee65c1988  4000b84        8 ...pApplicationState  0 instance 000000013ff410c8 _state
... some fields here ...
000007fee8b38738  4000002       d8          System.Guid  1 instance 000000013ff76ca0 AppId
000007fee8b169d0  4000003       d0        System.String  0 instance 0000000000000000 TestMessage
000007fee8b1d6e8  4000001       40       System.Boolean  1   static                1 __initialized
0:024&gt; dd 000000013ff76ca0 
00000001`3ff76ca0  22089cce 4123f79a f9e755b4 d51d09e1 // which is 22089cce-f79a-4123-b455-e7f9e1091dd5
00000001`3ff76cb0  00000000 00000000 e8b21c98 000007fe
00000001`3ff76cc0  3ff76d10 00000001 00000000 00000000
00000001`3ff76cd0  00000000 00000000 00000000 00000000
00000001`3ff76ce0  00000000 00000000 00000000 00000000
00000001`3ff76cf0  00000001 00000000 00000002 3f3851ec
00000001`3ff76d00  00000001 00000000 00000000 00000000
00000001`3ff76d10  e8b21f18 000007fe 00000003 00000000
</pre><br />
You may perform the same steps to examine the special application pool.</p>
<p>I hope that this post helped you better understand the Global.asax file and its role in the ASP.NET applications. The simple web project is available for download <a href="http://lowleveldesign.codeplex.com/releases" title="http://lowleveldesign.codeplex.com" target="_blank">here</a>.</p>
<br />Filed under: <a href='http://lowleveldesign.wordpress.com/category/asp-net/'>ASP.NET</a>, <a href='http://lowleveldesign.wordpress.com/category/codeproject/'>CodeProject</a>, <a href='http://lowleveldesign.wordpress.com/category/debugging/'>Debugging</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lowleveldesign.wordpress.com/368/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lowleveldesign.wordpress.com/368/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lowleveldesign.wordpress.com/368/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lowleveldesign.wordpress.com/368/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lowleveldesign.wordpress.com/368/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lowleveldesign.wordpress.com/368/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lowleveldesign.wordpress.com/368/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lowleveldesign.wordpress.com/368/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lowleveldesign.wordpress.com/368/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lowleveldesign.wordpress.com/368/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lowleveldesign.wordpress.com/368/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lowleveldesign.wordpress.com/368/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lowleveldesign.wordpress.com/368/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lowleveldesign.wordpress.com/368/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=368&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lowleveldesign.wordpress.com/2011/07/20/global-asax-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e908dab390254580734da838f8050fba?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lowleveldesign</media:title>
		</media:content>
	</item>
		<item>
		<title>Take advantage of Reference Paths in Visual Studio and debug locally referenced libraries</title>
		<link>http://lowleveldesign.wordpress.com/2011/04/20/take-advantage-of-referencepath-in-visual-studio-and-debug-locally-external-libraries/</link>
		<comments>http://lowleveldesign.wordpress.com/2011/04/20/take-advantage-of-referencepath-in-visual-studio-and-debug-locally-external-libraries/#comments</comments>
		<pubDate>Tue, 19 Apr 2011 23:39:05 +0000</pubDate>
		<dc:creator>Sebastian Solnica</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[debugger]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://lowleveldesign.wordpress.com/?p=311</guid>
		<description><![CDATA[Are you using NHibernate or other open-source library in your project? I&#8217;m pretty sure that you are. Have you ever wondered what&#8217;s happening &#8220;under the cover&#8221; when you call Session.Get or perform a query? You probably did. The problem is that usually all the external assemblies are stored in one directory (libs, packages, reflibs etc.) [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=311&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Are you using NHibernate or other open-source library in your project? I&#8217;m pretty sure that you are. Have you ever wondered what&#8217;s happening &#8220;under the cover&#8221; when you call Session.Get or perform a query? You probably did. The problem is that usually all the external assemblies are stored in one directory (libs, packages, reflibs etc.) with no symbol files or sources. In this post I would like to show you how you can benefit from project&#8217;s ReferencePath property and debug the source code of your libraries at any time you want.<br />
<span id="more-311"></span><br />
Let&#8217;s assume that our projects are using NHibernate 3.1. We ran nuget (<a href="http://nuget.codeplex.com">http://nuget.codeplex.com/</a>) to setup dependencies and NHibernate libraries are now in $(ProjectDir)\packages\NHibernate.3.1.0.4000\lib\Net35. In the project file (.csproj) we probably have a following section:</p>
<p><pre class="brush: xml;">
&lt;Reference Include=&quot;NHibernate&quot;&gt;
  &lt;HintPath&gt;packages\NHibernate.3.1.0.4000\lib\Net35\NHibernate.dll&lt;/HintPath&gt;
&lt;/Reference&gt;
</pre></p>
<p>We are also using code repository and our .csproj file is checked-in as well as the whole packages directory. One day we noticed that one repository (DAO) function is performing really badly. While debugging we found out that the problem lies in Session.Get method. Without knowledge of what&#8217;s happening inside we are not able to tell what causes this performance loss. But we also know that NHibernate library is open-source so let&#8217;s get the source code, debug it and have a grasp at what NHibernate gurus put in there. We download the source code (<a href="http://sourceforge.net/projects/nhibernate/files/NHibernate/3.1.0.GA/NHibernate-3.1.0.GA-src.zip/download">NHibernate-3.1.0.GA-src.zip</a>), save them to c:\NHibernate-src and run the compilation script (NHibernate is using nant script, we want pdb files that&#8217;s why project.config=debug, I skipped tests just to speed up the build process):</p>
<p><pre class="brush: bash;">
nant -t:net-3.5 -D:skip.tests=true -D:skip.manual=true -D:project.config=debug
</pre></p>
<p>You probably will need to download <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=22914587-b4ad-4eae-87cf-b14ae6a939b0&amp;displaylang=en">ILMerge</a> and place it in the c:\NHibernate-src\Tools\ILMerge. I also needed to remove c:\NHibernate-src\src\NHibernate.Test.build &#8211; somehow I was getting compilation errors and didn&#8217;t have time to check why (we won&#8217;t need the NHibernate.Test.dll anyhow).</p>
<p>The question now is how to bind the newly compiled assemblies (from c:\NHibernate-src\build\NHibernate-3.1.0.GA-debug\bin\net-3.5\) with our projects. There are two approaches: we can either replace NHibernate references in all projects and copy our debug-enabled binaries to packages\NHibernate.3.1.0.4000\lib\Net35 folder or use <strong>ReferencePath</strong> properties. First approach has many disadvantages &#8211; we are messing project files used by all developers (.csproj), source code is on our machine so other users won&#8217;t be able to debug NHibernate, on deployment we will need to restore all release-compiled binaries. When using <strong>ReferencePath</strong> we don&#8217;t have such problems. ReferencePath is your local project property and is stored in .csproj.user file which you usually don&#8217;t upload to the repository (and if you do, you shouldn&#8217;t <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ). Visual Studio considers ReferencePath in the first place (before HintPath) while looking for assemblies and so when you compile your project locally it will be bound with the debug-enabled assemblies. Just to finish the subject: you set the <strong>ReferencePath</strong> by right clicking your project in Solution Explorer, choosing Properties and then ReferencePaths tab:<br />
<a href="http://lowleveldesign.files.wordpress.com/2011/04/capture1.png"><img src="http://lowleveldesign.files.wordpress.com/2011/04/capture1.png?w=595" alt="" title="ReferencePath project property"   class="aligncenter size-full wp-image-330" /></a><br />
Click &#8220;Add Folder&#8221; and a new section should appear in your .csproj.user file:</p>
<p><pre class="brush: xml;">
&lt;PropertyGroup&gt;
  &lt;ReferencePath&gt;c:\NHibernate-src\build\NHibernate-3.1.0.GA-debug\bin\net-3.5\&lt;/ReferencePath&gt;
&lt;/PropertyGroup&gt;
</pre></p>
<p>Now, while debugging press F11 on Session.Get and you should be able to step NHibernate source code. Have fun!</p>
<br />Filed under: <a href='http://lowleveldesign.wordpress.com/category/codeproject/'>CodeProject</a>, <a href='http://lowleveldesign.wordpress.com/category/debugging/'>Debugging</a>, <a href='http://lowleveldesign.wordpress.com/category/nhibernate-2/'>NHibernate</a>, <a href='http://lowleveldesign.wordpress.com/category/tools/visual-studio/'>Visual Studio</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lowleveldesign.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lowleveldesign.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lowleveldesign.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lowleveldesign.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lowleveldesign.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lowleveldesign.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lowleveldesign.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lowleveldesign.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lowleveldesign.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lowleveldesign.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lowleveldesign.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lowleveldesign.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lowleveldesign.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lowleveldesign.wordpress.com/311/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=311&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lowleveldesign.wordpress.com/2011/04/20/take-advantage-of-referencepath-in-visual-studio-and-debug-locally-external-libraries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e908dab390254580734da838f8050fba?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lowleveldesign</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/04/capture1.png" medium="image">
			<media:title type="html">ReferencePath project property</media:title>
		</media:content>
	</item>
		<item>
		<title>Remote debugging with Visual Studio 2010</title>
		<link>http://lowleveldesign.wordpress.com/2011/01/16/remote-debugging-with-visual-studio-2010/</link>
		<comments>http://lowleveldesign.wordpress.com/2011/01/16/remote-debugging-with-visual-studio-2010/#comments</comments>
		<pubDate>Sun, 16 Jan 2011 16:41:17 +0000</pubDate>
		<dc:creator>Sebastian Solnica</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[debugger]]></category>
		<category><![CDATA[remote debugging]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://lowleveldesign.wordpress.com/?p=279</guid>
		<description><![CDATA[I&#8217;ve recently needed to remotely debug a .net desktop application with Visual Studio 2010. After having read the MSDN documentation on this subject I still missed some information. I hope that this post will fill some of these gaps and will help you configure and run the remote debugging tools. Let&#8217;s first start with a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=279&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently needed to remotely debug a .net desktop application with Visual Studio 2010. After having read the MSDN documentation on this subject I still missed some information. I hope that this post will fill some of these gaps and will help you configure and run the remote debugging tools.<br />
<span id="more-279"></span><br />
Let&#8217;s first start with a definition of parts involved in the debugging process:</p>
<ul>
<li><strong>host</strong> &#8211; is a machine on which Visual Studio is installed and on which you control the debugging process</li>
<li><strong>remote computer</strong> &#8211; is a machine on which the debuggee is ran</li>
</ul>
<p>Since the debugging process is wholly controlled from the host there must be a listener on the remote computer that executes commands sent from Visual Studio. This listener is called <strong>Remote Debugging Monitor (msvsmon.exe)</strong>. There are two possible ways to install it &#8211; you can either download and run the setup package from <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=60ec9d08-439b-4986-ae43-0487eb83c09e">microsoft</a> or copy all the necessary files from <em>C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Remote Debugger</em> (path on my 64-bit Win7). A caveat here: if your host is x86 machine than you have no choice but x86 package for your remote computer &#8211; there is no way you can debug a 64-bit process in a 32-bit debugger. Though you can debug 32-bit process in a 64-bit debugger.</p>
<p>Next step (the most boring and error prone in my opinion) is a network setup. Ideally Visual Studio and Remote Debugging Monitor should take care of the Windows Firewall settings after you run them with the elevated privileges but life is life and you might need to get your hands dirty. Fortunately the manual configuration process is pretty well explained on MSDN sites for <a href="http://msdn.microsoft.com/en-us/library/bb385683.aspx">WinXP</a>, <a href="http://msdn.microsoft.com/en-us/library/bb385831.aspx">Vista</a> and <a href="http://msdn.microsoft.com/en-us/library/ee126350.aspx">Win7</a>. Next important thing is security. You can either perform debugging in &#8220;NoAuthentication&#8221; mode (which is of course less secure) or in Windows Authentication mode. Unfortunately Windows Authentication mode requires the same account to be setup on the host and the remote computer &#8211; both usernames and passwords must be the same. If it&#8217;s a problem for you then you are left with the &#8220;NoAuthentication&#8221; mode in which you take a risk of allowing all people to access your debugging monitor. </p>
<p>Having finished the configuration part we may finally start the debugging process. Begin with starting msvsmon.exe (Remote Debugging Monitor) on the remote computer &#8211; it will communicate with Visual Studio running on the host. Let&#8217;s assume that our application is named RemoteControl.exe and is written in C#. First we need to deploy it on the remote computer, for example into the <em>C:\Users\consept\Dektop\RemoteControl</em> folder (<strong>remember to copy also all the pdb files and the assemblies required by the main application</strong>).  We can now either start the application under the debugger or attach the debugger to the already running process. Let&#8217;s start with the first scenario. If you have access to the application solution folder and to all the project files then you can start the remote debugging by modifying the start project properties page:</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/01/capture.png"><img src="http://lowleveldesign.files.wordpress.com/2011/01/capture.png?w=595" alt="" title="Starting the application under the debugger (from the solution)"   class="aligncenter size-full wp-image-288" /></a></p>
<p>If you don&#8217;t have access to the application solution then you need to use the application exe file. From <em>File</em> menu choose <em>Open-&gt;Project/Solution&#8230;</em> and find the exe file for your application. Select the newly opened project and choose properties. Fill the page with following values:</p>
<p><a href="http://lowleveldesign.files.wordpress.com/2011/01/capture1.png"><img src="http://lowleveldesign.files.wordpress.com/2011/01/capture1.png?w=595" alt="" title="Start the debugging process (from exe file)."   class="aligncenter size-full wp-image-291" /></a></p>
<p><strong>Attaching to the already started process</strong> is fairly simple: from the <em>Debug</em> menu choose <em>Attach to process&#8230;</em>. If you are debugging in the Windows Authentication mode set the Transport box to Default. In Qualifier field type name of your Remote Debugging Monitor session. Usually it is your user name + @ + the remote computer name, for example Sebastian@REMOTE-PC (the session name is also displayed in the listbox after you start the msvsmon.exe). </p>
<p>Finally few words about the debugging process. Unfortunately the debugging symbol configuration differs depending on the chosen debugging engine (native, managed, mixed). <strong>When using managed debugging engine symbols must be accessible on the remote computer</strong> (so you need to deploy your application with all pdb files and set _NT_SYMBOL_PATH variable on the remote computer for .NET Framework debugging symbols). <strong>When using native debugging engine symbols are loaded from the host machine</strong> (so you must include the directory with all pdb files for your application into the Visual Studio symbols search path &#8211; <em>Tools-&gt;Options-&gt;Debugging-&gt;Symbols</em>). Interestingly source files are always loaded from the host machine (in case that you don&#8217;t use any kind of source server). To summarize: remember to always choose the managed engine for your .net applications that don&#8217;t have any interop parts. The native engine requires much more information (like symbols for all native libraries) and provides you with capabilities that are usually not necessary in debugging pure .NET application.</p>
<p>I haven&#8217;t touched the subject of the web applications remote debugging and running Remote Debugging Monitor as a service. Leave a comment if you wish such a post to appear in the future:)</p>
<br />Filed under: <a href='http://lowleveldesign.wordpress.com/category/codeproject/'>CodeProject</a>, <a href='http://lowleveldesign.wordpress.com/category/debugging/'>Debugging</a>, <a href='http://lowleveldesign.wordpress.com/category/tools/visual-studio/'>Visual Studio</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lowleveldesign.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lowleveldesign.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lowleveldesign.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lowleveldesign.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lowleveldesign.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lowleveldesign.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lowleveldesign.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lowleveldesign.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lowleveldesign.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lowleveldesign.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lowleveldesign.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lowleveldesign.wordpress.com/279/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lowleveldesign.wordpress.com/279/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lowleveldesign.wordpress.com/279/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=279&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lowleveldesign.wordpress.com/2011/01/16/remote-debugging-with-visual-studio-2010/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e908dab390254580734da838f8050fba?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lowleveldesign</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/01/capture.png" medium="image">
			<media:title type="html">Starting the application under the debugger (from the solution)</media:title>
		</media:content>

		<media:content url="http://lowleveldesign.files.wordpress.com/2011/01/capture1.png" medium="image">
			<media:title type="html">Start the debugging process (from exe file).</media:title>
		</media:content>
	</item>
		<item>
		<title>Writing a .net debugger (part 4) &#8211; breakpoints</title>
		<link>http://lowleveldesign.wordpress.com/2010/12/01/writing-a-net-debugger-part-4-breakpoints/</link>
		<comments>http://lowleveldesign.wordpress.com/2010/12/01/writing-a-net-debugger-part-4-breakpoints/#comments</comments>
		<pubDate>Wed, 01 Dec 2010 20:26:22 +0000</pubDate>
		<dc:creator>Sebastian Solnica</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[clr]]></category>
		<category><![CDATA[debugger]]></category>

		<guid isPermaLink="false">http://lowleveldesign.wordpress.com/?p=251</guid>
		<description><![CDATA[After the last part the mindbg debugger stops at the application entry point, has module symbols loaded and displays source code that is being executed. Today we will gain some more control over the debugging process by using breakpoints. By the end of this post we will be able to stop the debugger on either [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=251&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>After <a href="http://lowleveldesign.wordpress.com/2010/11/08/writing-a-net-debugger-part-3-symbol-and-source-files/">the last part</a> the <a href="http://mindbg.codeplex.com">mindbg debugger</a> stops at the application entry point, has module symbols loaded and displays source code that is being executed. Today we will gain some more control over the debugging process by using breakpoints. By the end of this post we will be able to stop the debugger on either a function execution or at any source line.<br />
<span id="more-251"></span><br />
Setting a breakpoint on a function is quite straightforward &#8211; you only need to call <strong>CreateBreakpoint</strong> method on a <strong>ICorDebugFunction</strong> instance (that we want to have a stop on) and then activate the newly created breakpoint (with <strong>ICorDebugBreakpoint.Activate(1)</strong> function). The tricky part is how to find the ICorDebugFunction instance based on a string provided by the user. For this purpose we will write few helper methods that will use <strong>ICorMetadataImport</strong> interface. Let&#8217;s assume that we would like to set a breakpoint on a Test method of TestCmd class in testcmd.exe assembly. We will then use command &#8220;set-break mcmdtest.exe!TestCmd.Test&#8221;. After splitting the command string we will receive module path, class name and method name. We could easily find a module with a given path (we will iterate through the modules collection &#8211; for now it won&#8217;t be possible to create a breakpoint on a module that has not been loaded). Having found a module we may try to identify the type which &#8220;owns&#8221; the method. I really like the way how it is done in mdbg source code so we will copy their idea <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . We will add a new method to the CorModule class: </p>
<p><pre class="brush: csharp;">
// Brilliantly written taken from mdbg source code.
// returns a type token from name
// when the function fails, we return token TokenNotFound value.
public int GetTypeTokenFromName(string name)
{
    IMetadataImport importer = GetMetadataInterface&lt;IMetadataImport&gt;();

    int token = TokenNotFound;
    if (name.Length == 0)
        // this is special global type (we'll return token 0)
        token = TokenGlobalNamespace;
    else
    {
        try
        {
            importer.FindTypeDefByName(name, 0, out token);
        }
        catch (COMException e)
        {
            token = TokenNotFound;
            if ((HResult)e.ErrorCode == HResult.CLDB_E_RECORD_NOTFOUND)
            {
                int i = name.LastIndexOf('.');
                if (i &gt; 0)
                {
                    int parentToken = GetTypeTokenFromName(name.Substring(0, i));
                    if (parentToken != TokenNotFound)
                    {
                        try
                        {
                            importer.FindTypeDefByName(name.Substring(i + 1), parentToken, out token);
                        }
                        catch (COMException e2)
                        {
                            token = TokenNotFound;
                            if ((HResult)e2.ErrorCode != HResult.CLDB_E_RECORD_NOTFOUND)
                                throw;
                        }
                    }
                }
            }
            else
                throw;
        }
    }
    return token;
}
</pre><br />
Then, we will implement the <strong>MetadataType</strong> class that will inherit from <strong>Type</strong>. For clarity I will show you only the impelmented methods (others throw NotImplementedException):</p>
<p><pre class="brush: csharp;">
internal sealed class MetadataType : Type
{
    private readonly IMetadataImport p_importer;
    private readonly Int32 p_typeToken;

    internal MetadataType(IMetadataImport importer, Int32 typeToken)
    {
        this.p_importer = importer;
        this.p_typeToken = typeToken;
    }

    ...
    
    public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr)
    {
        IntPtr hEnum = new IntPtr();
        ArrayList methods = new ArrayList();

        Int32 methodToken;
        try
        {
            while (true)
            {
                Int32 size;
                p_importer.EnumMethods(ref hEnum, p_typeToken, out methodToken, 1, out size);
                if (size == 0)
                    break;
                methods.Add(new MetadataMethodInfo(p_importer, methodToken));
            }
        }
        finally
        {
            p_importer.CloseEnum(hEnum);
        }
        return (MethodInfo[])methods.ToArray(typeof(MethodInfo));
    }
    
    ...
}
</pre></p>
<p>As you could see in the listing we also used <strong>MetadataMethodInfo</strong>. The listing below presents body of this class:</p>
<p><pre class="brush: csharp;">
internal sealed class MetadataMethodInfo : MethodInfo
{
    private readonly Int32 p_methodToken;
    private readonly Int32 p_classToken;
    private readonly IMetadataImport p_importer;
    private readonly String p_name;


    internal MetadataMethodInfo(IMetadataImport importer, Int32 methodToken)
    {
        p_importer = importer;
        p_methodToken = methodToken;

        int size;
        uint pdwAttr;
        IntPtr ppvSigBlob;
        uint pulCodeRVA, pdwImplFlags;
        uint pcbSigBlob;

        p_importer.GetMethodProps((uint)methodToken,
                                  out p_classToken,
                                  null,
                                  0,
                                  out size,
                                  out pdwAttr,
                                  out ppvSigBlob,
                                  out pcbSigBlob,
                                  out pulCodeRVA,
                                  out pdwImplFlags);

        StringBuilder szMethodName = new StringBuilder(size);
        p_importer.GetMethodProps((uint)methodToken,
                                out p_classToken,
                                szMethodName,
                                szMethodName.Capacity,
                                out size,
                                out pdwAttr,
                                out ppvSigBlob,
                                out pcbSigBlob,
                                out pulCodeRVA,
                                out pdwImplFlags);

        p_name = szMethodName.ToString();
        //m_methodAttributes = (MethodAttributes)pdwAttr;
    }

    ...
    
    public override string Name
    {
        get { return p_name; }
    }
    
    public override int MetadataToken
    {
        get { return this.p_methodToken; }
    }
}
</pre></p>
<p>Finally we are ready to implement the method that will return <strong>CorFunction</strong> instance:</p>
<p><pre class="brush: csharp;">
public CorFunction ResolveFunctionName(CorModule module, String className, String functionName)
{
    Int32 typeToken = module.GetTypeTokenFromName(className);
    if (typeToken == CorModule.TokenNotFound)
        return null;

    Type t = new MetadataType(module.GetMetadataInterface&lt;IMetadataImport&gt;(), typeToken);
    CorFunction func = null;
    foreach (MethodInfo mi in t.GetMethods())
    {
        if (String.Equals(mi.Name, functionName, StringComparison.Ordinal))
        {
            func = module.GetFunctionFromToken(mi.MetadataToken);
            break;
        }
    }
    return func;
}
</pre></p>
<p>We will now concentrate on the second type of breakpoints: <strong>the code breakpoints</strong> which are set at a specific line of the source code file. Example of usage whould be &#8220;set-break mcmdtest.cs:23&#8243;. So how to set this type of breakpoint? First we need to find a module that was built from the given source file. We will iterate through all loaded modules and if a given module has symbols loaded (SymReader property != null) then we will check its documents URLS and compare them with the requested file name (snippet based on mdbg source code):</p>
<p><pre class="brush: csharp;">
if(managedModule.SymReader==null)
  // no symbols for current module, skip it.
  return false;

foreach(ISymbolDocument doc in managedModule.SymReader.GetDocuments())
{
  if(String.Compare(doc.URL,m_file,true,CultureInfo.InvariantCulture)==0 ||
    String.Compare(System.IO.Path.GetFileName(doc.URL),m_file,true,CultureInfo.InvariantCulture)==0)
  {
     // we will fill for body later
  }
}
</pre></p>
<p>Having found the module we need to find a class method that the given source line belongs to. So first let&#8217;s locate the line that is the nearest sequence point to the given line by calling <strong>ISymbolDocument.FindClosestLine</strong> method. Next, with the help of the module&#8217;s ISymbolReader we will find the <strong>ISymbolMethod</strong> instance that represents our wanted function. The last step is to get the CorFunction instance based on the method&#8217;s token:</p>
<p><pre class="brush: csharp;">
// the upper &quot;for&quot; body
Int32 line = 0;
try
{
  line = symdoc.FindClosestLine(lineNumber);
}
catch (System.Runtime.InteropServices.COMException ex)
{
  if (ex.ErrorCode == (Int32)HResult.E_FAIL)
      continue; // it's not this document
}
ISymbolMethod symmethod = symreader.GetMethodFromDocumentPosition(symdoc, line, 0);
CorFunction func = module.GetFunctionFromToken(symmethod.Token.GetToken());
</pre></p>
<p>Code breakpoints are created using <strong>ICorDebugCode.CreateBreakpoint</strong> method which takes as its parameter a code offset at which the breakpoint should be set. We will get an instance of the ICorDebugCode from the CorFunction instance (found in the last paragraph):</p>
<p><pre class="brush: csharp;">
// from CorFunction.cs
public CorCode GetILCode()
{
    ICorDebugCode cocode = null;
    p_cofunc.GetILCode(out cocode);
    return new CorCode(cocode);
}
</pre></p>
<p>Then we will find the IL offset in the function IL code that corresponds to the given source file line number:</p>
<p><pre class="brush: csharp;">
// from CorFunction.cs
internal int GetIPFromPosition(ISymbolDocument document, int lineNumber)
{
    SetupSymbolInformation();
    if (!p_hasSymbols)
        return -1;

    for (int i = 0; i &lt; p_SPcount; i++)
    {
        if (document.URL.Equals(p_SPdocuments[i].URL) &amp;&amp; lineNumber == p_SPstartLines[i])
            return p_SPoffsets[i];
    }
    return -1;
}
</pre></p>
<p>Finally we are ready to parse user&#8217;s input and set breakpoints accordingly. I used two simple regex expressions to check the breakpoint type and call process.ResolveFunctionName for function breakpoints and process.ResolveCodeLocation for code breakpoints:</p>
<p><pre class="brush: csharp;">
static Regex methodBreakpointRegex = new Regex(@&quot;^((?&lt;module&gt;[\.\w\d]*)!)?(?&lt;class&gt;[\w\d\.]+)\.(?&lt;method&gt;[\w\d]+)$&quot;);
static Regex codeBreakpointRegex = new Regex(@&quot;^(?&lt;filepath&gt;[\\\.\S]+)\:(?&lt;linenum&gt;\d+)$&quot;);

...

// try module!type.method location (simple regex used)
Match match = methodBreakpointRegex.Match(command);
if (match.Groups[&quot;method&quot;].Length &gt; 0)
{
    Console.Write(&quot;Setting method breakpoint... &quot;);

    CorFunction func = process.ResolveFunctionName(match.Groups[&quot;module&quot;].Value, match.Groups[&quot;class&quot;].Value,
                                                    match.Groups[&quot;method&quot;].Value);
    func.CreateBreakpoint().Activate(true);
    
    Console.WriteLine(&quot;done.&quot;);
    continue;
}
// try file code:line location
match = codeBreakpointRegex.Match(command);
if (match.Groups[&quot;filepath&quot;].Length &gt; 0)
{
    Console.Write(&quot;Setting code breakpoint...&quot;);

    int offset;
    CorCode code = process.ResolveCodeLocation(match.Groups[&quot;filepath&quot;].Value, 
                                               Int32.Parse(match.Groups[&quot;linenum&quot;].Value), 
                                               out offset);
    code.CreateBreakpoint(offset).Activate(true);

    Console.WriteLine(&quot;done.&quot;);
    continue;
}
</pre></p>
<p>I also corrected the main debugger loop so it is starting to look as a normal debugger command line <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . As always the source code is available under <a href="http://mindbg.codeplex.com">http://mindbg.codeplex.com</a> (revision  55832).</p>
<br />Filed under: <a href='http://lowleveldesign.wordpress.com/category/codeproject/'>CodeProject</a>, <a href='http://lowleveldesign.wordpress.com/category/debugging/'>Debugging</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lowleveldesign.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lowleveldesign.wordpress.com/251/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lowleveldesign.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lowleveldesign.wordpress.com/251/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lowleveldesign.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lowleveldesign.wordpress.com/251/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lowleveldesign.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lowleveldesign.wordpress.com/251/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lowleveldesign.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lowleveldesign.wordpress.com/251/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lowleveldesign.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lowleveldesign.wordpress.com/251/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lowleveldesign.wordpress.com/251/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lowleveldesign.wordpress.com/251/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lowleveldesign.wordpress.com&amp;blog=14936745&amp;post=251&amp;subd=lowleveldesign&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lowleveldesign.wordpress.com/2010/12/01/writing-a-net-debugger-part-4-breakpoints/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e908dab390254580734da838f8050fba?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lowleveldesign</media:title>
		</media:content>
	</item>
	</channel>
</rss>
