<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Rick Byers</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/rmbyers/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/rmbyers/feed.xml</link>
    <description>The CLR, diagnostics tool support and programming languages.</description>
    <lastBuildDate>Wed, 17 Apr 2019 03:25:13 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Leaving</title>
      <link>https://docs.microsoft.com/archive/blogs/rmbyers/leaving</link>
      <pubDate>Fri, 19 Nov 2010 19:40:00 GMT</pubDate>
      <dc:creator><![CDATA[Rick Byers - exMSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/rmbyers/2010/11/19/leaving/</guid>
      <description><![CDATA[After 6 great years at Microsoft, my wife and I have decided it's time to spend some time living...]]></description>
      <content:encoded><![CDATA[<p>After 6 great years at Microsoft, my wife and I have decided it's time to spend some time living near our family in Ontario, Canada (we've got two young kids, and they're going to love seeing their grandparents and cousins more than twice a year). &nbsp;I've been having a great time on the CLR (working on all sorts of cool secret stuff I haven't been able to blog about), so it was a very tough decision. &nbsp;But anyway, I will no longer be able to post to this blog or reply to comments. &nbsp;If you'd like to contact me, you can e-mail me at rick-msblog at rbyers daughtnet.</p>
<p>Thanks!<br />&nbsp;&nbsp; &nbsp;Rick&nbsp;</p>]]></content:encoded>
    </item>
    <item>
      <title>Sample Reflection.Emit code for using exception filters from C#</title>
      <link>https://docs.microsoft.com/archive/blogs/rmbyers/sample-reflection-emit-code-for-using-exception-filters-from-c</link>
      <pubDate>Sat, 30 Jan 2010 10:00:12 GMT</pubDate>
      <dc:creator><![CDATA[Rick Byers - exMSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/rmbyers/2010/01/30/sample-reflection-emit-code-for-using-exception-filters-from-c/</guid>
      <description><![CDATA[In this post, I mentioned that one way to use exception filters from C# code is to generate them...]]></description>
      <content:encoded><![CDATA[<p></p>  <p>In <a href="https://blogs.msdn.com/rmbyers/archive/2008/12/22/getting-good-dumps-when-an-exception-is-thrown.aspx">this post</a>, I mentioned that one way to use exception filters from C# code is to generate them with Reflection.Emit.&#160; Personally I usually prefer static compilation (even post-build assembly merging or rewriting) – there’s really nothing here that necessitates dynamic code generation, but I can understand the desire to avoid complicating the build process.&#160; I recently wrote up some code to do this and figured I’d share it here in case others find it useful.</p>  <p>   <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:fb83ef86-4bdd-432f-b5b1-afb0ec8c64d9" class="wlWriterEditableSmartContent"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div> <div style="background-color: #ffffff; max-height: 400px; overflow: auto; padding: 2px 5px; white-space: nowrap"><span style="color:#0000ff">using</span> System;<br> <span style="color:#0000ff">using</span> System.Reflection.Emit;<br> <span style="color:#0000ff">using</span> System.Reflection;<br> <span style="color:#0000ff">using</span> System.Diagnostics;<br> <span style="color:#0000ff">using</span> System.Runtime.CompilerServices;<br> <span style="color:#0000ff">using</span> System.Linq;<br> <br> <span style="color:#0000ff">namespace</span> FilterTest<br> {<br>     <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;summary&gt;</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> This class provides some utilities for working with exceptions and exception filters.</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;/summary&gt;</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;remarks&gt;</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> Code inside of exception filters runs before the stack has been logically unwound, and so the throw point </span><br>     <span style="color:#808080">///</span><span style="color:#008000"> is still visible in tools like debuggers, and backout code from finally blocks has not yet been run.</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> See https://blogs.msdn.com/rmbyers/archive/2008/12/22/getting-good-dumps-when-an-exception-is-thrown.aspx.</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> Filters can also be used to provide more fine-grained control over which exceptions are caught.  </span><br>     <span style="color:#808080">///</span><span style="color:#008000"> </span><br>     <span style="color:#808080">///</span><span style="color:#008000"> Be aware, however, that filters run at a surprising time - after an exception has occurred but before</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> any finally clause has been run to restore broken invariants for things lexically in scope.  This can lead to </span><br>     <span style="color:#808080">///</span><span style="color:#008000"> confusion if you access or manipulate program state from your filter.  See this blog entry for details</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> and more specific guidance: https://blogs.msdn.com/clrteam/archive/2009/08/25/the-good-and-the-bad-of-exception-filters.aspx.</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> </span><br>     <span style="color:#808080">///</span><span style="color:#008000"> This class relies on Reflection.Emit to generate code which can use filters.  If you are willing to add some</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> complexity to your build process, a static technique (like writing in VB and use ILMerge, or rewriting with CCI)</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> may be a better choice (eg. more performant and easier to specialize).  Again see</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> https://blogs.msdn.com/rmbyers/archive/2008/12/22/getting-good-dumps-when-an-exception-is-thrown.aspx for details.</span><br>     <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;/remarks&gt;</span><br>     <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">ExceptionUtils</span><br>     {<br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;summary&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> Execute the body with the specified filter.</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;/summary&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;param name=&quot;body&quot;&gt;</span><span style="color:#008000">The code to run inside the &quot;try&quot; block</span><span style="color:#808080">&lt;/param&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;param name=&quot;filter&quot;&gt;</span><span style="color:#008000">Called whenever an exception escapes body, passing the exeption object.  </span><br>         <span style="color:#808080">///</span><span style="color:#008000"> For exceptions that aren&#39;t derived from System.Exception, they&#39;ll show up as an instance of RuntimeWrappedException.</span><span style="color:#808080">&lt;/param&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;param name=&quot;handler&quot;&gt;</span><span style="color:#008000">Invoked (with the exception) whenever the filter returns true, causes the exception to be swallowed</span><span style="color:#808080">&lt;/param&gt;</span><br>         <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> ExecuteWithFilter(<span style="color:#2b91af">Action</span> body, <span style="color:#2b91af">Func</span>&lt;<span style="color:#2b91af">Exception</span>, <span style="color:#0000ff">bool</span>&gt; filter, <span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Exception</span>&gt; handler)<br>         {<br>             s_filter(body, filter, handler);<br>         }<br> <br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;summary&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> Execute the body with the specified filter with no handler ever being invoked</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;/summary&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;remarks&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> Note that this allocates a delegate and closure class, a small amount of overhead but something that may not be appropriate</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> for inside of a tight inner loop.  If you want to call this on a very hot path, you may want to consider a direct call</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> rather than using an anonymous method.</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;/remarks&gt;</span><br>         <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> ExecuteWithFilter(<span style="color:#2b91af">Action</span> body, <span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Exception</span>&gt; filter)<br>         {<br>             ExecuteWithFilter(body, (e) =&gt; { filter(e); <span style="color:#0000ff">return</span> <span style="color:#0000ff">false</span>; }, <span style="color:#0000ff">null</span>);<br>         }<br> <br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;summary&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> Execute the body which is not expected to ever throw any exceptions.</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> If an exception does escape body, stop in the debugger if one is attached and then fail-fast.</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;/summary&gt;</span><br>         <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> ExecuteWithFailfast(<span style="color:#2b91af">Action</span> body)<br>         {<br>             ExecuteWithFilter(body, (e) =&gt;<br>             {<br>                 System.Diagnostics.<span style="color:#2b91af">Debugger</span>.Log(<span style="color:#a52a2a">10</span>, <span style="color:#a31515">&quot;ExceptionFilter&quot;</span>, <span style="color:#a31515">&quot;Saw unexpected exception: &quot;</span> + e.ToString());<br> <br>                 <span style="color:#008000">// Terminate the process with this fatal error</span><br>                 <span style="color:#0000ff">if</span> (System.<span style="color:#2b91af">Environment</span>.Version.Major &gt;= <span style="color:#a52a2a">4</span>)<br>                 {<br>                     <span style="color:#008000">// .NET 4 adds a FailFast overload which takes the exception, usefull for getting good watson buckets</span><br>                     <span style="color:#008000">// This will also cause an attached debugger to stop at the throw point, just as if the exception went unhandled.</span><br>                     <span style="color:#008000">// Note that this code may be compiled against .NET 2.0 but running in CLR v4, so we want to take advantage of</span><br>                     <span style="color:#008000">// this API even if it&#39;s not available at compile time, so we use a late-bound call.</span><br>                     <span style="color:#0000ff">typeof</span>(System.<span style="color:#2b91af">Environment</span>).InvokeMember(<span style="color:#a31515">&quot;FailFast&quot;</span>,<br>                         <span style="color:#2b91af">BindingFlags</span>.Static | <span style="color:#2b91af">BindingFlags</span>.InvokeMethod,<br>                         <span style="color:#0000ff">null</span>, <span style="color:#0000ff">null</span>, <span style="color:#0000ff">new</span> <span style="color:#0000ff">object</span>[] { <span style="color:#a31515">&quot;Unexpected Exception&quot;</span>, e });<br>                 }<br>                 <span style="color:#0000ff">else</span><br>                 {<br>                     <span style="color:#008000">// The experience isn&#39;t quite as nice in CLR v2 and before (no good watson buckets, debugger shows a </span><br>                     <span style="color:#008000">// &#39;FatalExecutionEngineErrorException&#39; at this point), but still deubggable.</span><br>                     System.<span style="color:#2b91af">Environment</span>.FailFast(<span style="color:#a31515">&quot;Exception: &quot;</span> + e.GetType().FullName);<br>                 }<br> <br>                 <span style="color:#0000ff">return</span> <span style="color:#0000ff">false</span>;   <span style="color:#008000">// should never be reached</span><br>             }, <span style="color:#0000ff">null</span>);<br>         }<br> <br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;summary&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> Like a normal C# Try/Catch but allows one catch block to catch multiple different types of exceptions.</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;/summary&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;typeparam name=&quot;TExceptionBase&quot;&gt;</span><span style="color:#008000">The common base exception type to catch</span><span style="color:#808080">&lt;/typeparam&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;param name=&quot;body&quot;&gt;</span><span style="color:#008000">Code to execute inside the try</span><span style="color:#808080">&lt;/param&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;param name=&quot;typesToCatch&quot;&gt;</span><span style="color:#008000">All exception types to catch (each of which must be derived from or exactly TExceptionBase)</span><span style="color:#808080">&lt;/param&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;param name=&quot;handler&quot;&gt;</span><span style="color:#008000">The catch block to execute when one of the specified exceptions is caught</span><span style="color:#808080">&lt;/param&gt;</span><br>         <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> TryCatchMultiple&lt;TExceptionBase&gt;(<span style="color:#2b91af">Action</span> body, <span style="color:#2b91af">Type</span>[] typesToCatch, <span style="color:#2b91af">Action</span>&lt;TExceptionBase&gt; handler)<br>             <span style="color:#0000ff">where</span> TExceptionBase:<span style="color:#2b91af">Exception</span><br>         {<br>             <span style="color:#008000">// Verify that every type in typesToCatch is a sub-type of TExceptionBase</span><br> <span style="color:#0000ff">#if</span> DEBUG<br>             <span style="color:#0000ff">foreach</span>(<span style="color:#0000ff">var</span> tc <span style="color:#0000ff">in</span> typesToCatch)<br>                 <span style="color:#2b91af">Debug</span>.Assert(<span style="color:#0000ff">typeof</span>(TExceptionBase).IsAssignableFrom(tc), <span style="color:#2b91af">String</span>.Format(<span style="color:#a31515">&quot;Error: {0} is not a sub-class of {1}&quot;</span>,<br>                     tc.FullName, <span style="color:#0000ff">typeof</span>(TExceptionBase).FullName));<br> <span style="color:#0000ff">#endif</span><br> <br>             ExecuteWithFilter(body, (e) =&gt;<br>             {<br>                 <span style="color:#008000">// If the thrown exception is a sub-type (including the same time) of at least one of the provided types then</span><br>                 <span style="color:#008000">// catch it.</span><br>                 <span style="color:#0000ff">foreach</span> (<span style="color:#0000ff">var</span> catchType <span style="color:#0000ff">in</span> typesToCatch)<br>                     <span style="color:#0000ff">if</span> (catchType.IsAssignableFrom(e.GetType()))<br>                         <span style="color:#0000ff">return</span> <span style="color:#0000ff">true</span>;<br>                 <span style="color:#0000ff">return</span> <span style="color:#0000ff">false</span>;<br>             }, (e) =&gt;<br>             {<br>                 handler((TExceptionBase)e);<br>             });<br>         }<br> <br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;summary&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> A convenience method for when only the base type of &#39;Exception&#39; is needed.</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;/summary&gt;</span><br>         <span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> TryCatchMultiple(<span style="color:#2b91af">Action</span> body, <span style="color:#2b91af">Type</span>[] typesToCatch, <span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Exception</span>&gt; handler)<br>         {<br>             TryCatchMultiple&lt;<span style="color:#2b91af">Exception</span>&gt;(body, typesToCatch, handler);<br>         }<br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;summary&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> Set to true to write the generated assembly to disk for debugging purposes (eg. to run peverify and</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> ildasm on in the case of bad codegen).</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;/summary&gt;</span><br>         <span style="color:#0000ff">private</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">bool</span> k_debug = <span style="color:#0000ff">false</span>;<br> <br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;summary&gt;</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> Generate a function which has an EH filter</span><br>         <span style="color:#808080">///</span><span style="color:#008000"> </span><span style="color:#808080">&lt;/summary&gt;</span><br>         <span style="color:#0000ff">private</span> <span style="color:#0000ff">static</span> <span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Action</span>, <span style="color:#2b91af">Func</span>&lt;<span style="color:#2b91af">Exception</span> , <span style="color:#0000ff">bool</span>&gt;, <span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Exception</span>&gt;&gt; GenerateFilter()<br>         {<br>             <span style="color:#008000">// Create a dynamic assembly with reflection emit</span><br>             <span style="color:#0000ff">var</span> name = <span style="color:#0000ff">new</span> <span style="color:#2b91af">AssemblyName</span>(<span style="color:#a31515">&quot;DynamicFilter&quot;</span>);<br>             <span style="color:#2b91af">AssemblyBuilder</span> assembly = <span style="color:#2b91af">AppDomain</span>.CurrentDomain.DefineDynamicAssembly(name, k_debug ? <span style="color:#2b91af">AssemblyBuilderAccess</span>.RunAndSave : <span style="color:#2b91af">AssemblyBuilderAccess</span>.Run);<br>             <span style="color:#2b91af">ModuleBuilder</span> module;<br>             <span style="color:#0000ff">if</span> (k_debug)<br>                 module = assembly.DefineDynamicModule(<span style="color:#a31515">&quot;DynamicFilter&quot;</span>, <span style="color:#a31515">&quot;DynamicFilter.dll&quot;</span>);<br>             <span style="color:#0000ff">else</span><br>                 module = assembly.DefineDynamicModule(<span style="color:#a31515">&quot;DynamicFilter&quot;</span>);<br> <br>             <span style="color:#008000">// Add an assembly attribute that tells the CLR to wrap non-CLS-compliant exceptions in a RuntimeWrappedException object</span><br>             <span style="color:#008000">// (so the cast to Exception in the code will always succeed).  C# and VB always do this, C++/CLI doesn&#39;t.</span><br>             assembly.SetCustomAttribute(<span style="color:#0000ff">new</span> <span style="color:#2b91af">CustomAttributeBuilder</span>(<br>                 <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">RuntimeCompatibilityAttribute</span>).GetConstructor(<span style="color:#0000ff">new</span> <span style="color:#2b91af">Type</span>[] { }),<br>                 <span style="color:#0000ff">new</span> <span style="color:#0000ff">object</span>[] {},<br>                 <span style="color:#0000ff">new</span> <span style="color:#2b91af">PropertyInfo</span>[] { <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">RuntimeCompatibilityAttribute</span>).GetProperty(<span style="color:#a31515">&quot;WrapNonExceptionThrows&quot;</span>) },<br>                 <span style="color:#0000ff">new</span> <span style="color:#0000ff">object</span>[] { <span style="color:#0000ff">true</span> }));<br> <br>             <span style="color:#008000">// Add an assembly attribute that tells the CLR not to attempt to load PDBs when compiling this assembly </span><br>             assembly.SetCustomAttribute(<span style="color:#0000ff">new</span> <span style="color:#2b91af">CustomAttributeBuilder</span>(<br>                 <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">DebuggableAttribute</span>).GetConstructor(<span style="color:#0000ff">new</span> <span style="color:#2b91af">Type</span>[] { <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">DebuggableAttribute</span>.<span style="color:#2b91af">DebuggingModes</span>) }),<br>                 <span style="color:#0000ff">new</span> <span style="color:#0000ff">object</span>[] { <span style="color:#2b91af">DebuggableAttribute</span>.<span style="color:#2b91af">DebuggingModes</span>.IgnoreSymbolStoreSequencePoints } ));<br> <br>             <span style="color:#008000">// Create the type and method which will contain the filter</span><br>             <span style="color:#2b91af">TypeBuilder</span> type = module.DefineType(<span style="color:#a31515">&quot;Filter&quot;</span>, <span style="color:#2b91af">TypeAttributes</span>.Class | <span style="color:#2b91af">TypeAttributes</span>.Public);<br>             <span style="color:#0000ff">var</span> argTypes = <span style="color:#0000ff">new</span> <span style="color:#2b91af">Type</span>[] { <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">Action</span>), <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">Func</span>&lt;<span style="color:#2b91af">Exception</span>, <span style="color:#0000ff">bool</span>&gt;), <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Exception</span>&gt;) };<br>             <span style="color:#2b91af">MethodBuilder</span> meth = type.DefineMethod(<span style="color:#a31515">&quot;InvokeWithFilter&quot;</span>, <span style="color:#2b91af">MethodAttributes</span>.Public | <span style="color:#2b91af">MethodAttributes</span>.Static, <span style="color:#0000ff">typeof</span>(<span style="color:#0000ff">void</span>), argTypes);<br>             <br>             <span style="color:#0000ff">var</span> il = meth.GetILGenerator();<br>             <span style="color:#0000ff">var</span> exLoc = il.DeclareLocal(<span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">Exception</span>));<br> <br>             <span style="color:#008000">// Invoke the body delegate inside the try</span><br>             il.BeginExceptionBlock();<br>             il.Emit(<span style="color:#2b91af">OpCodes</span>.Ldarg_0);<br>             il.EmitCall(<span style="color:#2b91af">OpCodes</span>.Callvirt, <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">Action</span>).GetMethod(<span style="color:#a31515">&quot;Invoke&quot;</span>), <span style="color:#0000ff">null</span>);<br> <br>             <span style="color:#008000">// Invoke the filter delegate inside the filter block</span><br>             il.BeginExceptFilterBlock();<br>             il.Emit(<span style="color:#2b91af">OpCodes</span>.Castclass, <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">Exception</span>));<br>             il.Emit(<span style="color:#2b91af">OpCodes</span>.Stloc_0);<br>             il.Emit(<span style="color:#2b91af">OpCodes</span>.Ldarg_1);<br>             il.Emit(<span style="color:#2b91af">OpCodes</span>.Ldloc_0);<br>             il.EmitCall(<span style="color:#2b91af">OpCodes</span>.Callvirt, <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">Func</span>&lt;<span style="color:#2b91af">Exception</span>, <span style="color:#0000ff">bool</span>&gt;).GetMethod(<span style="color:#a31515">&quot;Invoke&quot;</span>), <span style="color:#0000ff">null</span>);<br> <br>             <span style="color:#008000">// Invoke the handler delegate inside the catch block</span><br>             il.BeginCatchBlock(<span style="color:#0000ff">null</span>);<br>             il.Emit(<span style="color:#2b91af">OpCodes</span>.Castclass, <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">Exception</span>));<br>             il.Emit(<span style="color:#2b91af">OpCodes</span>.Stloc_0);<br>             il.Emit(<span style="color:#2b91af">OpCodes</span>.Ldarg_2);<br>             il.Emit(<span style="color:#2b91af">OpCodes</span>.Ldloc_0);<br>             il.EmitCall(<span style="color:#2b91af">OpCodes</span>.Callvirt, <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Exception</span>&gt;).GetMethod(<span style="color:#a31515">&quot;Invoke&quot;</span>), <span style="color:#0000ff">null</span>);<br> <br>             il.EndExceptionBlock();<br>             il.Emit(<span style="color:#2b91af">OpCodes</span>.Ret);<br> <br>             <span style="color:#0000ff">var</span> bakedType = type.CreateType();<br>             <span style="color:#0000ff">if</span> (k_debug)<br>                 assembly.Save(<span style="color:#a31515">&quot;DynamicFilter.dll&quot;</span>);<br> <br>             <span style="color:#008000">// Construct a delegate to the filter function and return it</span><br>             <span style="color:#0000ff">var</span> bakedMeth = bakedType.GetMethod(<span style="color:#a31515">&quot;InvokeWithFilter&quot;</span>);<br>             <span style="color:#0000ff">var</span> del = <span style="color:#2b91af">Delegate</span>.CreateDelegate(<span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Action</span>, <span style="color:#2b91af">Func</span>&lt;<span style="color:#2b91af">Exception</span>, <span style="color:#0000ff">bool</span>&gt;, <span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Exception</span>&gt;&gt;), bakedMeth);<br>             <span style="color:#0000ff">return</span> (<span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Action</span>, <span style="color:#2b91af">Func</span>&lt;<span style="color:#2b91af">Exception</span>, <span style="color:#0000ff">bool</span>&gt;, <span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Exception</span>&gt;&gt;)del;<br>         }<br> <br>         <span style="color:#008000">// Will get generated (with automatic locking) on first use of this class</span><br>         <span style="color:#0000ff">private</span> <span style="color:#0000ff">static</span> <span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Action</span>, <span style="color:#2b91af">Func</span>&lt;<span style="color:#2b91af">Exception</span>, <span style="color:#0000ff">bool</span>&gt;, <span style="color:#2b91af">Action</span>&lt;<span style="color:#2b91af">Exception</span>&gt;&gt; s_filter = GenerateFilter();<br>     }<br> }</div> </div> </div> </p>  <p>&#160;</p>  <p>There’s also a few helper methods there for common uses of exception filters.&#160; For example, to call code that you don’t expect to ever throw an exception you can just wrap it with ExecuteWithFailFast.&#160; If any exceptions escape it’ll immediately fail fast with a watson report and minidump (at the point of throw), or if a debugger is attached break at the throw point.&#160; The experience is better if running on CLR v4 – it makes use of the new FailFast API that takes an exception (eg. this will cause the debugger to break with the exception assistant, just as if the exception had gone unhandled).&#160; For example you can use this as follows:</p>  <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:07dbc0d7-0b0a-4aec-9169-ca521c3722ec" class="wlWriterEditableSmartContent"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background-color: #ffffff; max-height: 300px; overflow: auto; padding: 2px 5px; white-space: nowrap"><span style="color:#008000">// FailFast on throw</span><br> <span style="color:#2b91af">ExceptionUtils</span>.ExecuteWithFailfast(() =&gt;<br> {<br>     <span style="color:#008000">// Code you don&#39;t expect to throw exceptions</span><br>     <span style="color:#0000ff">throw</span> <span style="color:#0000ff">new</span> <span style="color:#2b91af">ApplicationException</span>(<span style="color:#a31515">&quot;Test unexpected exception&quot;</span>);<br> });</div> </div> </div>  <p>&#160;</p>  <p>Sometimes it’s useful to be able to catch multiple distinct exception types with the same catch block (without unwinding the stack for other exceptions, so unexpected exceptions are easier to debug live or in a dump file).&#160; Here are two examples:</p>  <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:f8799221-a313-4aeb-87f9-329f6beaec06" class="wlWriterEditableSmartContent"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background-color: #ffffff; max-height: 300px; overflow: auto; padding: 2px 5px; white-space: nowrap"><span style="color:#008000">// Catching multiple exception types at once as SystemException</span><br> <span style="color:#2b91af">ExceptionUtils</span>.TryCatchMultiple&lt;<span style="color:#2b91af">SystemException</span>&gt;(() =&gt;<br> {<br>     <span style="color:#0000ff">throw</span> <span style="color:#0000ff">new</span> <span style="color:#2b91af">ArgumentNullException</span>();<br> },<br> <span style="color:#0000ff">new</span> <span style="color:#2b91af">Type</span>[] { <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">InvalidCastException</span>), <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">ArgumentException</span>), <span style="color:#0000ff">typeof</span>(System.IO.<span style="color:#2b91af">FileNotFoundException</span>) },<br> (e) =&gt;<br> {<br>     <span style="color:#2b91af">Console</span>.WriteLine(<span style="color:#a31515">&quot;Caught: &quot;</span> + e.Message);<br> });<br> <br> <span style="color:#008000">// Catching multiple exception types at once as System.Exception</span><br> <span style="color:#2b91af">ExceptionUtils</span>.TryCatchMultiple(() =&gt;<br> {<br>     <span style="color:#0000ff">throw</span> <span style="color:#0000ff">new</span> <span style="color:#2b91af">ArgumentNullException</span>();<br> },<br> <span style="color:#0000ff">new</span> <span style="color:#2b91af">Type</span>[] { <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">InvalidCastException</span>), <span style="color:#0000ff">typeof</span>(<span style="color:#2b91af">ArgumentException</span>), <span style="color:#0000ff">typeof</span>(System.IO.<span style="color:#2b91af">FileNotFoundException</span>) },<br> (e) =&gt;<br> {<br>     <span style="color:#2b91af">Console</span>.WriteLine(<span style="color:#a31515">&quot;Caught: &quot;</span> + e.Message);<br> });</div> </div> </div>  <p>&#160;</p>  <p>And here’s an example of a general-purpose exception filter:</p>  <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:1c00458f-e740-4f79-bf21-fb7048efceb4" class="wlWriterEditableSmartContent"> <div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt"> <div style="background-color: #ffffff; max-height: 300px; overflow: auto; padding: 2px 5px; white-space: nowrap"><span style="color:#008000">// General-purpose filter</span><br> <span style="color:#2b91af">ExceptionUtils</span>.ExecuteWithFilter( () =&gt; {<br>     <span style="color:#2b91af">Console</span>.WriteLine(<span style="color:#a31515">&quot;In body&quot;</span>);<br>     <span style="color:#0000ff">throw</span> <span style="color:#0000ff">new</span> <span style="color:#2b91af">ApplicationException</span>(<span style="color:#a31515">&quot;test&quot;</span>);<br> }, (e) =&gt; {<br>     <span style="color:#2b91af">Console</span>.WriteLine(<span style="color:#a31515">&quot;In filter, exception type: {0}&quot;</span>, e.GetType().FullName);<br>     <span style="color:#0000ff">return</span> <span style="color:#0000ff">true</span>;<br> }, (e) =&gt; {<br>     <span style="color:#2b91af">Console</span>.WriteLine(<span style="color:#a31515">&quot;In catch, exception type: {0}&quot;</span>, e.GetType().FullName);<br> });</div> </div> </div>  <p>&#160;</p>  <p>Again, there are <a href="https://blogs.msdn.com/clrteam/archive/2009/08/25/the-good-and-the-bad-of-exception-filters.aspx">good reasons</a> why C# doesn’t support exception filters directly.&#160; But there are a few cases where they can be really invaluable.&#160; I hope you find this useful.</p>]]></content:encoded>
    </item>
    <item>
      <title>Quickly seeing where an exception may land in the debugger</title>
      <link>https://docs.microsoft.com/archive/blogs/rmbyers/quickly-seeing-where-an-exception-may-land-in-the-debugger</link>
      <pubDate>Tue, 01 Sep 2009 01:08:52 GMT</pubDate>
      <dc:creator><![CDATA[Rick Byers - exMSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/rmbyers/2009/09/01/quickly-seeing-where-an-exception-may-land-in-the-debugger/</guid>
      <description><![CDATA[A co-worker asked me recently how he could predict where an exception that was about to be thrown...]]></description>
      <content:encoded><![CDATA[<p>A co-worker asked me recently how he could predict where an exception that was about to be thrown would land while debugging a managed application.&#160; The real answer to this question is “you can’t – step into the throw and see”.&#160; The EH system in the CLR has lots of complicated algorithms for determining this, and it needs to interact with other code on the stack (eg. there may be some native code with it’s own SEH filter that can do arbitrary logic).&#160; Luckily, unlike for native debugging, managed debugging can generally “step into” exception throws and reliably land in the handler.&#160; </p>  <p>But occasionally people still find themselves looking up the callstack, searching the code for ‘try’ blocks that are active.&#160; Surely there’s a way to automate that?&#160; Of course the debugger has all the information necessary to automate that, but unfortunately the VS debugger is not easily extensible in this way, so there’s not a lot you can do from the debugger process.&#160; However, as usual, func-eval offers a nice work-around for the lack of easy extensibility.&#160; Using the technique in my “<a href="https://blogs.msdn.com/rmbyers/archive/2005/04/30/413752.aspx">Run-time exception checking</a>” post, we can func-eval code which gets the EH handler info for the current stack and displays it nicely in the watch window.&#160; I’ve posted a sample (source and binary) which does that <a href="https://code.msdn.microsoft.com/ExceptionHandlerInfo">here</a>.&#160; To use it, download <a href="https://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=ExceptionHandlerInfo&amp;DownloadId=7093">ExceptionHandlerInfo.dll</a>, and then while stopped in the debugger enter Assembly.LoadFrom(@&quot;c:\mypath\ExceptionHandlerInfo.dll&quot;) into the immediate window to get it loaded into the debuggee process.&#160; Now, whenever you want to quickly see what handlers are active on the current stack, you can enter “Microsoft.Samples.ExceptionHandlerInfo.EHInfoCollector.GetActiveEHClauses()” into the watch window:</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GetActiveEHClauses1_2.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GetActiveEHClauses1_2.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="GetActiveEHClauses1" border="0" alt="GetActiveEHClauses1" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GetActiveEHClauses1_thumb.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GetActiveEHClauses1_thumb.png" width="783" height="168" /></a> </p>  <p>In this example, we can see that there is first a “catch System.ArgumentException” at Program.cs line 35 in method '”Program.Catcher” which is the 2nd (#1) frame on the current stack.&#160; Above that on the stack there is a “catch Exception” and a “Finally” block in the “Program.Main” method, and then a “Finally” block inside the VS hosting process code (for which we don’t have PDBs to provide a source location).</p>  <p>You can drill info EHInfo objects further if you want more details on a particular frame:</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GetActiveEHClauses2_2.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GetActiveEHClauses2_2.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="GetActiveEHClauses2" border="0" alt="GetActiveEHClauses2" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GetActiveEHClauses2_thumb.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GetActiveEHClauses2_thumb.png" width="781" height="406" /></a> </p>  <p></p>  <p>And if you want to automate scanning all the active EH clauses for the one most likely to catch the currently active exception (eg. when stopping on first-chance exceptions), you can enter “Microsoft.Samples.ExceptionHandlerInfo.EHInfoCollector.GuessCatchHander($exception.GetType())”:</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GuessCatchHandler_2.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GuessCatchHandler_2.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="GuessCatchHandler" border="0" alt="GuessCatchHandler" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GuessCatchHandler_thumb.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/Quicklyseeingwhereanexceptionmaylandinth_1329B/GuessCatchHandler_thumb.png" width="783" height="160" /></a> </p>  <p>Now someone just needs to integrate this with a VS macro so I can jump to the most likely catcher with a single keypress ;-)</p>]]></content:encoded>
    </item>
    <item>
      <title>My school assignment required parsing PDB files</title>
      <link>https://docs.microsoft.com/archive/blogs/rmbyers/my-school-assignment-required-parsing-pdb-files</link>
      <pubDate>Tue, 09 Jun 2009 13:15:00 GMT</pubDate>
      <dc:creator><![CDATA[Rick Byers - exMSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/rmbyers/2009/06/09/my-school-assignment-required-parsing-pdb-files/</guid>
      <description><![CDATA[I'm just finishing up my Masters in Computer Science, and was surprised when I recently got an...]]></description>
      <content:encoded><![CDATA[<P>I'm just finishing up my Masters in Computer Science, and was surprised when I recently got an <A href="https://pbradley.fhcrc.org/genome541/" mce_href="https://pbradley.fhcrc.org/genome541/">assignment</A> that involved parsing PDB files.&nbsp; Over the years I've been involved in many discussions about why the Microsoft PDB format isn't public.&nbsp; John Robbins recently went as far as to say "<A href="https://www.wintellect.com/CS/blogs/jrobbins/archive/2009/05/11/pdb-files-what-every-developer-must-know.aspx" mce_href="https://www.wintellect.com/CS/blogs/jrobbins/archive/2009/05/11/pdb-files-what-every-developer-must-know.aspx">The actual file format of a PDB file is a closely guarded secret</A>", but that's probably and overstatement given that the <A href="https://ccimetadata.codeplex.com/" mce_href="https://ccimetadata.codeplex.com/">CCI</A> code which contains a C# managed-PDB reader has now been released on CodePlex.&nbsp; So needless to say, I didn't expect to be having to parse PDB files for school ... especially in a computational biology class.</P>
<P>Ok, so if you do a web-search now for "<A href="https://www.bing.com/search?q=PDB+file+format&amp;form=QBRE" mce_href="https://www.bing.com/search?q=PDB+file+format&amp;form=QBRE">PDB file format</A>", the first hit you get isn't for <A href="https://en.wikipedia.org/wiki/Program_database" mce_href="https://en.wikipedia.org/wiki/Program_database">Microsoft's Program Database file format</A>, but for the <A href="https://www.wwpdb.org/docs.html" mce_href="https://www.wwpdb.org/docs.html">Protein Data Bank file format</A>.&nbsp; Who ever came up with the idea that file types should be uniquely determined by a 3-letter extension that isn't coordinated by any central registry anyway?&nbsp; Now I've got to decide which way I want windows to treat PDB files (and both have been pretty important to me lately):</P>
<P><A href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/UniversityofWashingtonclassassignmentreq_9918/pdb1_2.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/UniversityofWashingtonclassassignmentreq_9918/pdb1_2.png"><IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=pdb1 border=0 alt=pdb1 src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/UniversityofWashingtonclassassignmentreq_9918/pdb1_thumb.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/UniversityofWashingtonclassassignmentreq_9918/pdb1_thumb.png" width=206 height=54></A>&nbsp;</P><A href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/UniversityofWashingtonclassassignmentreq_9918/pdb2_2.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/UniversityofWashingtonclassassignmentreq_9918/pdb2_2.png"><IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=pdb2 border=0 alt=pdb2 src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/UniversityofWashingtonclassassignmentreq_9918/pdb2_thumb.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/UniversityofWashingtonclassassignmentreq_9918/pdb2_thumb.png" width=244 height=224></A>]]></content:encoded>
    </item>
    <item>
      <title>New interviews with my CLR team members up on Channel9</title>
      <link>https://docs.microsoft.com/archive/blogs/rmbyers/new-interviews-with-my-clr-team-members-up-on-channel9</link>
      <pubDate>Tue, 09 Jun 2009 00:19:00 GMT</pubDate>
      <dc:creator><![CDATA[Rick Byers - exMSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/rmbyers/2009/06/09/new-interviews-with-my-clr-team-members-up-on-channel9/</guid>
      <description><![CDATA[There are a bunch of great new CLR v4-related video interviews&nbsp;up on Channel9.&nbsp; In...]]></description>
      <content:encoded><![CDATA[<P>There are a bunch of great new <A href="https://channel9.msdn.com/tags/CLR+4/" mce_href="https://channel9.msdn.com/tags/CLR+4/">CLR v4-related video interviews</A>&nbsp;up on Channel9.&nbsp; In particular:</P>
<UL>
<LI><A href="https://channel9.msdn.com/posts/Charles/CLR-4-Debugging-and-Profiling-Enhancements/" mce_href="https://channel9.msdn.com/posts/Charles/CLR-4-Debugging-and-Profiling-Enhancements/">Jon, Thomas and Dave from my team</A> (CLR diagnostics) discuss the advancements in debugging and profiling APIs in v4</LI>
<LI><A href="https://channel9.msdn.com/shows/Going+Deep/CLR-4-Side-by-Side-In-Process-What-How-Why/" mce_href="https://channel9.msdn.com/shows/Going+Deep/CLR-4-Side-by-Side-In-Process-What-How-Why/">Simon and I</A> discuss in-process SxS (ability to have multiple CLRs loaded in the same process).&nbsp; You may have noticed the lack of diagnostics blog entries from me lately - that's because I've mostly been spending my time helping out with this important feature.</LI></UL>
<P>There are a bunch of other ones that look good (eg. "Type equivalence" and "No-PIAs" are closely related and an interesting discussion), but I haven't gotten a chance to watch them yet.</P>]]></content:encoded>
    </item>
    <item>
      <title>AnyCPU Exes are usually more trouble than they're worth</title>
      <link>https://docs.microsoft.com/archive/blogs/rmbyers/anycpu-exes-are-usually-more-trouble-than-theyre-worth</link>
      <pubDate>Tue, 09 Jun 2009 00:13:00 GMT</pubDate>
      <dc:creator><![CDATA[Rick Byers - exMSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/rmbyers/2009/06/09/anycpu-exes-are-usually-more-trouble-than-theyre-worth/</guid>
      <description><![CDATA[Over the past few months I've had some interesting debates with folks here (and some customers)...]]></description>
      <content:encoded><![CDATA[<p>Over the past few months I've had some interesting debates with folks here (and some customers) about the cost/benefit trade-off of "AnyCPU" (architecture-neutral)&nbsp;managed EXEs.&nbsp; I think we've converged on a consensus that most of the time they're not what you want and so shouldn't be the default in Visual Studio.&nbsp; I suspect this topic may interest (and even shock) some folks, so I thought I'd share the rationale with you here.</p>
<p><strong>Background - .NET and 64-bit<br /></strong>With the introduction of Win64 (64-bit versions of Windows), PE files (EXEs and DLLs) can be marked either as 32-bit OR 64-bit.&nbsp; When a 32-bit EXE is launched on Win64, it runs in "the WOW" (Windows-32 on Windows-64) to present an illusion of a 32-bit operating system to the process.&nbsp; Generally only 32-bit DLLs can be loaded into a 32-bit process, and only 64-bit DLLs can be loaded into a 64-bit process.&nbsp; When the CLR added 64-bit support in version 2.0, we had an interesting decision to make.&nbsp; Should we mark our binaries as 32-bit or 64-bit by default?&nbsp; Techncally managed binaries had no hard CPU dependency, so they could be either (actually there is a small loader thunk, but that's unused on any newer OS including all the 64-bit ones since the OS loader knows about managed EXEs explicitly).&nbsp; Since we wanted people to be able to write .NET libraries that they could re-use from both 32-bit and 64-bit processes, we worked with Windows to extend the OS loader support to enable architecture-neutral ("AnyCPU") PE files.</p>
<p>Managed architecture-neutral DLLs are fairly straight-forward - they can be loaded into either 32-bit or 64-bit processes, and the (32-bit or 64-bit) CLR in the process will do the right thing with them.&nbsp; AnyCPU EXEs are a little more complicated since the OS loader needs to decide how to initialze the process. On 64-bit OSes they are run as 64-bit processes (unless the 'ldr64' master OS switch says otherwise), and on 32-bit OSes they are run as 32-bit processes.&nbsp; In Visual Studio 2008, AnyCPU is the default platform for C# and VB projects.&nbsp; This means that by default, applications you compile will run in 64-bit processes on 64-bit OSes and 32-bit processes on 32-bit OSes.&nbsp; This is fine and does often work alright, but there are a number of minor downsides.</p>
<p><strong>The costs of architecture-neutral EXEs</strong><br />There are a number of reasons to think that AnyCPU should not be the default for EXEs.&nbsp; Don't get me wrong, 64-bit hardware and OSes are definitely the way to go (in fact all 4 of my development machines have 64-bit OSes on them - I stopped bothering to install 32-bit OSes years ago).&nbsp; But that doesn't necessarily mean that most processes should be 64-bit.&nbsp; Here's the list I've been using in our discussions to justify making x86 the default for EXE projects in Visual Studio:</p>
<ol>
<li>Running in two very different modes increases product complexity and the cost of testing<br />Often people don't realize the implications on native-interop of architecture-neutral assemblies.&nbsp; It means you need to ensure that equivalent 32-bit and 64-bit versions of the native DLLs you depend on are available, and (most significantly) the appropriate one is selected automatically.&nbsp; This is fairly easy when calling OS APIs due to the OS re-mapping of c:\windows\system32 to c:\windows\syswow64 when running in the WOW and extensive testing the OS team does.&nbsp; But many people who ship native DLLs alongside their managed app get this wrong at first and are surprised then their application blows up on 64-bit systems with an exception about their 32-bit DLL being in a bad format.&nbsp; Also, although it's much rarer than for native-code, pointer-size bugs&nbsp;can still manifest in .NET (eg. assuming IntPtr is the same as Int32, or incorrect marshalling declarations when interopping with native code).<br />Also, in addition to the rules you need to know to follow, there's just the issue that you've now really got twice as much code to test.&nbsp; Eg., there could easily be (and certainly have been many) CLR bugs that reproduce only on one architecture of the CLR, and this applies all the way across the stack (from OS, framework, 3rd-party libraries, to your code).&nbsp; Of course in an ideal world everyone has done a great job testing both 32-bit and 64-bit and you won't see any differences, but in practice for any large application that tends not to be the case, and (at Microsoft at least) we end up duplicating our entire test system for 32 and 64-bit and paying a significant ongoing cost to testing and supporting all platforms.<br />[Edit: Rico - of CLR and VS performance architect fame - just posted <a href="https://blogs.msdn.com/ricom/archive/2009/06/10/visual-studio-why-is-there-no-64-bit-version.aspx">a great blog entry</a> on why Visual Studio will not be a pure 64-bit application anytmie soon]</li>
<li>32-bit tends to be faster anyway<br />When an application can run fine either in 32-bit or 64-bit mode, the 32-bit mode tends to be a little faster.&nbsp; Larger pointers means more memory and cache consumption, and the number of bytes of CPU cache available is the same for both 32-bit and 64-bit processes.&nbsp; Of course the WOW layer does add some overhead, but the performance numbers I've seen indicate that in most real-world scenarios running in the WOW is faster than running as a native 64-bit process</li>
<li>Some features aren't avaiable in 64-bit<br />Although we all want to have perfect parity between 32-bit and 64-bit, the reality is that we're not quite there yet.&nbsp; CLR v2 only supported mixed-mode debugging on x86, and although we've finally added x64 support in CLR V4, edit-and-continue still doesn't support x64.&nbsp; On the CLR team, we consider x64 to be a first-class citizen whenever we add new functionality, but the reality is that we've got a complicated code-base (eg. completely separate 32-bit and 64-bit JIT compilers) and we sometimes have to make trade-offs (for example, adding 64-bit EnC would have been a very significant cost to the JIT team, and we decided that their time was better spent on higher priority features).&nbsp; There are other cool features outside of the CLR that are also specific to x86 - like historical debugging in VS 2010.&nbsp; Complicating matters here is that we haven't always done a great job with the error messages, and so sometimes people "upgrade" to a 64-bit OS and are then disgusted to see that some of their features no longer appear to work (without realizing that if they just re-targetted the WOW they'd work fine).&nbsp; For example, the EnC error in VS isn't very clear ("Changes to 64-bit applications are not allowed"), and has lead to <a href="https://social.msdn.microsoft.com/Forums/en-US/csharpide/thread/132512e0-bd07-49c1-9837-121a4151e226/">some confusion in practice</a>.&nbsp; I believe we're doing the right thing in VS2010 and fixing that dialog to make it clear that switching your project to x86 can resolve the issue, but still there's no getting back the time people have wasted on errors like this.</li>
</ol>
<p><strong>When do 64-bit processes make sense?<br /></strong>The biggest benefit of 64-bit processes is obivously the increased address-space.&nbsp; Many programs are bumping up against the 2GB limit of traditional 32-bit processes (even though they may not be using anywhere near 2GB of RAM).&nbsp; One thing that can be done for such programs is to have them <a href="https://social.msdn.microsoft.com/Forums/en-US/clr/thread/c50ea343-b41b-467d-a457-c5a735e4dfff/">opt-into 4GB mode</a> so that they can get a full 4GB of address space when running in the WOW on a 64-bit OS [Edit: softened wording here due to some <a href="https://connect.microsoft.com/VisualStudio/feedback/details/93771/net-compilers-should-support-a-largeaddressaware-flag">guidance to the contrary</a>].&nbsp; If more address space would be useful, than sometimes the right thing to do is to decide to target JUST x64 and avoid the cost of supporting two platforms (Exchange Server has done this for example).&nbsp; But often the right trade-off is to support both 32-bit and 64-bit processes, so that you can still run on 32-bit OSes, but take advantage of the large address space when running on 64-bit OSes.&nbsp; <br /><br />This is where architecture-neutral assemblies make a lot of sense.&nbsp; If you're a library vendor, then building as AnyCPU and testing on all supported architectures absolutely makes sense.&nbsp; If you are producing an application EXE and have reason to believe your application may need more than 4GB of address space, then switching to AnyCPU may be a good idea.&nbsp; But, as for native, really needing this much address space is still pretty rare and usually only necessary for large complex applications, and so opting-in to AnyCPU should really not be a burden.&nbsp; You've got to think about what you want your testing strategy to be anyway, so making this step explicit seems to make sense.</p>
<p>Another argument for AnyCPU being the default which I think deserves serious thought is the impact on the Windows ecosystem and desire to move to a pure 64-bit world someday.&nbsp; No doubt the WOW adds extra complexity and confusion and it would be great to just kill it as quickly as we can.&nbsp; I definitely agree with that sentiment, and we should work to get to that place.&nbsp; But realistically, we're a long way from being able to seriously consider killing the WOW from Client OSes (it is already optional on Server Core - but how many EXE projects are really server apps?).&nbsp; Here are some things that need to happen before we can seriously consider killing the WOW: Windows needs to stop shipping new 32-bit-only client OSes, most new native applications need to fully support 64-bit, all popular existing apps need to move to 64-bit (including VS), etc.&nbsp; I'm sure we'll get there some day (as we did with the 16-bit to 32-bit transition), but I don't think defaulting to x86 in Visual Studio is going to be a major barrier here.&nbsp; When it starts looking like killing the WOW may be a feasible option in the near-future, then perhaps we should probably just switch the default to be x64-only, and let people opt-in to supporting 'legacy' 32-bit platforms.</p>
<p><strong>So how is Visual Studio 2010 and .NET 4.0 changing?<br /></strong>We are not changing anything here in the CLR or compilers - they continue to support both modes.&nbsp; However, after discussing these issues, VS project system team has agreed to make EXE projects default to the x86 platform in VS 2010.&nbsp; Unfortunately there is a bug in Beta1 where ALL managed project types default to x86 (I take the blame for this - I didn't think to check DLL projects when validating the changes were in).&nbsp; AnyCPU is still incredibly valuable for DLLs (you may not always know what processes it will be loaded into), and since it just enables a DLL to be used in more places without actually affecting the bitness of the process, there isn't sufficient justification to disable AnyCPU by default.&nbsp; This bug has been fixed, and so the plan is to ship Beta2 with just the EXE projects defaulting to x86, and all DLL projects remaining as AnyCPU.</p>
<p>That said, there's still time to get customer feedback and so this could change for VS2010 RTM.&nbsp; We've already heard a lot of surprised reactions where people seem to think we're treating x64 as second-class, or otherwise resisting the natural evolution to 64-bit systems.&nbsp; Many people have mentioned that 32-bit hardware and 32-bit OSes are quickly becoming a thing of the past.&nbsp; I agree completely and this is a good trend, but it's completely orthogonal.&nbsp; 64-bit hardware and OSes give us the ability to run processes with 64-bit address spaces, but they by no means make using them a requirement or necessarily even preferable to using the WOW.&nbsp; The Windows folks did such a good job building the WOW, and the CPU designers did a good job supporting 32-bit modes (for x64 at least, ia64 is a different story), so&nbsp;there aren't a lot of downsides to relying on them.&nbsp; Someday I'm sure we'll decide the WOW has outlived it's useful lifetime and Windows should kill it rather than maintain it, but I'm sure that day is a LONG way off (eg. when did Windows finally remove support for 16-bit processes, and did anyone really notice?).&nbsp; <br /><br />When I actually get into debating this issue on it's merrits, almost everyone I've talked to has agreed that making x86 the default seems to be the best choice - at least for the next several years.&nbsp; This, by no means signifies decreased support for 64-bit OSes and frameworks.&nbsp; I can tell you that most CLR developers work almost exclusiviely on x64 OSes, and do much of their testing and development with 64-bit processes.&nbsp; Our testing (like most teams at Microsoft) treats x86 and x64 as first-class and generally equal-priority (except for products like Silverlight of course that are still x86-only).&nbsp; But when we put ourselves in the shoes of our users and study this issue on it's merrits, it just makes practical sense for x86 to be the default for EXE projects.</p>
<p>Let me know if you agree or disagree.&nbsp; Regardless, I hope you enjoy using VS2010 - it's really shaping up to be a great release!</p>
<p>[Edit - added section about helping the ecosystem move to all 64-bit]</p>]]></content:encoded>
    </item>
    <item>
      <title>CCI is public on Codeplex</title>
      <link>https://docs.microsoft.com/archive/blogs/rmbyers/cci-is-public-on-codeplex</link>
      <pubDate>Wed, 15 Apr 2009 12:07:00 GMT</pubDate>
      <dc:creator><![CDATA[Rick Byers - exMSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/rmbyers/2009/04/15/cci-is-public-on-codeplex/</guid>
      <description><![CDATA[Herman Venter has just released his Common Compiler Infrastructure as an OpenSource project on...]]></description>
      <content:encoded><![CDATA[<P>Herman Venter <A href="https://blogs.msdn.com/hermanventer/archive/2009/04/14/a-bit-of-help-compiling-your-next-net-hosted-programming-language.aspx" mce_href="https://blogs.msdn.com/hermanventer/archive/2009/04/14/a-bit-of-help-compiling-your-next-net-hosted-programming-language.aspx">has just released</A> his Common Compiler Infrastructure as an <A href="https://ccimetadata.codeplex.com/" mce_href="https://ccimetadata.codeplex.com/">OpenSource project on Codeplex</A>.&nbsp; CCI is a GREAT set of libraries for building, analyzing, and modifying .NET assemblies and PDB files - written entirely in C#.&nbsp; Several Microsoft projects have been using it internally for years.&nbsp; Most notably, it's the engine behind <A href="https://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx" mce_href="https://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx">FxCop</A>.&nbsp; If you've written your own <A href="https://www.binarycoder.net/fxcop/" mce_href="https://www.binarycoder.net/fxcop/">custom rule for FxCop</A>, you've used an earlier genreation of CCI.&nbsp; I'm thrilled that the latest CCI is finally public in full source form.&nbsp; This makes it easy to write all sorts of cool .NET tools.&nbsp; </P>
<P>I've been playing with custom FxCop rules for awhile.&nbsp; I'm getting close to releasing an FxCop rule that warns about invalid format strings (rather than waiting until runtime to get an annoying&nbsp;FormatException), and I've got a half-finished prototype of adding C++-style 'const' to C# (not that I think it's the best solution for adding immutability - just that it's a model lots of C# developers are already familiar with, and so a good one to experiment with).&nbsp; Now that the full CCI is out there, my mind is racing with all the cool tools I could release.&nbsp; I can't wait too see what else the community uses CCI for!</P>]]></content:encoded>
    </item>
    <item>
      <title>Getting good dumps when an exception is thrown</title>
      <link>https://docs.microsoft.com/archive/blogs/rmbyers/getting-good-dumps-when-an-exception-is-thrown</link>
      <pubDate>Mon, 22 Dec 2008 22:03:00 GMT</pubDate>
      <dc:creator><![CDATA[Rick Byers - exMSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/rmbyers/2008/12/22/getting-good-dumps-when-an-exception-is-thrown/</guid>
      <description><![CDATA[Often, when an unexpected exception occurs in production code, applications want to generate (and...]]></description>
      <content:encoded><![CDATA[<P>Often, when an unexpected exception occurs in production code, applications want to generate (and potentially report) some sort of diagnostics information.&nbsp; Sometimes people just want to write to a log file (and perhaps pop some error dialog) for support purposes, but more sophisticated applications will want to have a mechanism to save a minidump of the crash (and perhaps report it back to the author of the software) so their developers can debug the problem.&nbsp; <A href="https://msdn.microsoft.com/en-us/isv/bb190483.aspx" mce_href="https://msdn.microsoft.com/en-us/isv/bb190483.aspx">Windows Error Reporting</A> is usually the best way to do this (the CLR v2 and above <A href="https://msdn.microsoft.com/en-us/library/bb219076.aspx#MicrosoftErrorReporting_ManagedCode" mce_href="https://msdn.microsoft.com/en-us/library/bb219076.aspx#MicrosoftErrorReporting_ManagedCode">integrates with WER</A> for all managed apps), but people also like to build their own custom solutions.&nbsp; By the way, if you want to build your own error-reporting mechanism that captures dump files, I suggest you use a helper process to suspend all your threads and call MiniDumpWriteDump, rather than calling it directly in-process (see <A href="https://www.eggheadcafe.com/software/aspnet/29825284/loader-lock-deadlock-in-m.aspx">this discussion</A> for example).</P>
<P>As a very simple example, you may want to use the FailFast API to say "exceptions should never escape here, if it does present an error to the user and let them report the problem back through WER":</P>
<BLOCKQUOTE><PRE class=code><SPAN style="COLOR: blue">try
</SPAN>{
    MyCode();
}
<SPAN style="COLOR: blue">catch </SPAN>(<SPAN style="COLOR: #2b91af">Exception </SPAN>ex)
{
    <SPAN style="COLOR: green">// We don't expect any exceptions - generate an error-report if we see one
    </SPAN>System.<SPAN style="COLOR: #2b91af">Environment</SPAN>.FailFast(<SPAN style="COLOR: #a31515">"Unexpected exception: " </SPAN>+ ex.Message);
}</PRE></BLOCKQUOTE><A href="https://11011.net/software/vspaste"></A>
<P>Unfortunately, this won’t give you a very useful dump in your error-report.&nbsp; The problem is that by the time the catch block has been started, the stack frames showing how the exception occurred are no longer available (see below for details).&nbsp; Managed exceptions are built on <A href="https://www.microsoft.com/msj/0197/exception/exception.aspx">Windows Structured Exception Handling</A>, and so have the same two-pass model.&nbsp; ‘catch’ blocks are executed on the second pass, but really what we want here is to generate our error-report on the first-pass (before EBP gets reset).&nbsp; You are probably used to seeing this when debugging your code.&nbsp; If you really want to see what caused an exception, you have to tell Visual Studio to <A href="https://msdn.microsoft.com/en-us/library/h22dk1y6.aspx">stop on first-chance exceptions</A> – by the time you stop in the catch block, the code that threw the exception is no longer visible on the callstack:</P>
<BLOCKQUOTE>
<P><A href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/Gettinggooddumpswhenanexceptionisthrown_141E6/image_2.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/Gettinggooddumpswhenanexceptionisthrown_141E6/image_2.png"><IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=image border=0 alt=image src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/Gettinggooddumpswhenanexceptionisthrown_141E6/image_thumb.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/Gettinggooddumpswhenanexceptionisthrown_141E6/image_thumb.png" width=607 height=316></A> </P></BLOCKQUOTE>
<P>Luckily the CLR provides a way to do this called managed exception filters.&nbsp; Unfortunately C# doesn’t expose a way to use them.&nbsp; The simplest way to use a filter from C# code is to write a simple helper function in VB.Net.&nbsp; The ‘When’ portion of a ‘Catch’ clause in VB.Net is an exception filter.&nbsp; Here’s a simple helper I wrote for this that I can easily call from C#:</P>
<BLOCKQUOTE><PRE class=code><SPAN style="COLOR: blue">Public Class </SPAN>ExceptionUtils
    <SPAN style="COLOR: blue">Public Shared Sub </SPAN>Filter(<SPAN style="COLOR: blue">ByVal </SPAN>body <SPAN style="COLOR: blue">As </SPAN>Action, <SPAN style="COLOR: blue">ByVal </SPAN>filter <SPAN style="COLOR: blue">As </SPAN>Func(<SPAN style="COLOR: blue">Of </SPAN>Exception, <SPAN style="COLOR: blue">Boolean</SPAN>), <SPAN style="COLOR: blue">ByVal </SPAN>handler <SPAN style="COLOR: blue">As </SPAN>Action(<SPAN style="COLOR: blue">Of </SPAN>Exception))
        <SPAN style="COLOR: blue">Try
            </SPAN>body()
        <SPAN style="COLOR: blue">Catch </SPAN>ex <SPAN style="COLOR: blue">As </SPAN>Exception <SPAN style="COLOR: blue">When </SPAN>filter(ex)
            handler(ex)
        <SPAN style="COLOR: blue">End Try
    End Sub
End Class</SPAN></PRE></BLOCKQUOTE>
<P>Now I can re-write my code that triggers error-reporting on exceptions as follows (referencing the VB assembly with the above code):</P>
<BLOCKQUOTE><PRE class=code><SPAN style="COLOR: #2b91af">ExceptionUtils</SPAN>.Filter(() =&gt;
{
    <SPAN style="COLOR: green">// This is the body of the 'try'
    </SPAN>MyCode();
}, (ex) =&gt;
{
    <SPAN style="COLOR: green">// This is the body of the filter
    </SPAN>System.<SPAN style="COLOR: #2b91af">Environment</SPAN>.FailFast(<SPAN style="COLOR: #a31515">"Unexpected exception: " </SPAN>+ ex.Message);
    <SPAN style="COLOR: blue">return false</SPAN>; <SPAN style="COLOR: green">// don't catch - this code isn't reached
</SPAN>}, <SPAN style="COLOR: blue">null</SPAN>); <SPAN style="COLOR: green">// no catch block needed</SPAN></PRE><A href="https://11011.net/software/vspaste"></A></BLOCKQUOTE>
<P>Now, running under the debugger I can see the original call-stack, and even inspect locals/args on it (note the ‘Throw’ frame in the callstack, and the visible arg value for a – I can also click on this frame and poke around as normal):</P>
<BLOCKQUOTE>
<P><A href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/Gettinggooddumpswhenanexceptionisthrown_141E6/image_4.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/Gettinggooddumpswhenanexceptionisthrown_141E6/image_4.png"><IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=image border=0 alt=image src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/rmbyers/WindowsLiveWriter/Gettinggooddumpswhenanexceptionisthrown_141E6/image_thumb_1.png" original-url="https://blogs.msdn.com/blogfiles/rmbyers/WindowsLiveWriter/Gettinggooddumpswhenanexceptionisthrown_141E6/image_thumb_1.png" width=783 height=470></A> </P></BLOCKQUOTE>
<P>So that’s basically it.&nbsp; Now debugging at the point of the FailFast (whether live, or with a dump file) will let you see all the data on the stack leading up to the cause of the exception.&nbsp; Note that if exceptions are thrown and <EM>caught within</EM> the body they don’t trigger the filter, the filter is just like a catch block in that it cares about exceptions that “reach” it – which is usually what you want (eg. it’s not normally any of your concern if the implementation of some external API you call happens to throw and catch an exception – as long as it doesn’t propagate back to your code).</P>
<H3></H3>
<H2>Additional Details</H2>
<P>It might be a bit of a pain to have to deploy this extra assembly with your application, but there are other options for using an exception filter in your C# app:</P>
<OL>
<LI>Statically link the C# and VB code together into a single (single-file) assembly (eg. using <A href="https://www.hanselman.com/blog/MixingLanguagesInASingleAssemblyInVisualStudioSeamlesslyWithILMergeAndMSBuild.aspx">ILMerge</A>, Link.EXE, or a <A href="https://blogs.msdn.com/greggm/archive/2006/03/23/559155.aspx">ILDasm/ILAsm round-trip</A>)</LI>
<LI>Use a tool to re-write your assembly after it’s built to inject the filter.&nbsp; Gregg on the VS debugger team <A href="https://blogs.msdn.com/greggm/archive/2008/04/21/exception-filter-inject.aspx">posted such a tool awhile back</A>.</LI>
<LI>Use Reflection.Emit to dynamically generate the IL code for the filter at run-time.&nbsp; Update: I posted some sample code to do this <A href="https://blogs.msdn.com/rmbyers/archive/2010/01/30/sample-reflection-emit-code-for-using-exception-filters-from-c.aspx" mce_href="https://blogs.msdn.com/rmbyers/archive/2010/01/30/sample-reflection-emit-code-for-using-exception-filters-from-c.aspx">here</A>.</LI></OL>
<P>Also, one note about using FailFast with managed error-reporting.&nbsp; Error-reports are grouped by their ‘bucket parameters’.&nbsp; The buckets generated for System.Environment.FailFast(string) are always the same for any given call-site (basically just the address of the call, and a the string ‘FatalError’ for the exception type.&nbsp; Ideally what you’d like to do here is use the buckets for the original exception (so that two different exceptions that trigger the same call to FailFast will show up as two different problems).&nbsp; We’ve added a FailFast overload that takes an Exception object in .NET 4.0 that does this.</P>
<P>All I’ve talked about so far are simple single exceptions.&nbsp; Exceptions can also be caught and re-thrown ('”throw;” in C#) or wrapped in an outer exception which is thrown (“nested exceptions”).&nbsp; Unfortunately if that happens within the body you pass to ExceptionUtils.Filter, by the time the filter is invoked, the first exception has already been thrown and caught and so the stack you see is at the point of rethrow.&nbsp; There’s no good way that I’m aware of to get the stack from the original throw point in this case (although it’s something I’d like to get added to the CLR in a future version).&nbsp; This is particularly troublesome when using .NET APIs that catch-and-rethrow like Reflection (which wraps all exceptions in a TargetInvocationException).&nbsp; The best thing I can suggest is to put filters inside any such point, so you filter sees the exception before it’s caught.&nbsp; </P>
<P>If you want to be really hard-core about exceptions, you could use some sort of exception monitoring solution that notices as soon as an exception is thrown.&nbsp; For example, you could generate a dump from a <A href="https://msdn.microsoft.com/en-us/library/ms679274.aspx">vectored exception handler</A>, but you won’t have access to the managed System.Exception object here.&nbsp; Better yet, you could write a tool that uses the debugging APIs to watch for first-chance exceptions and log details about them (perhaps including dump files) such as <A href="https://blogs.msdn.com/jmstall/archive/2005/07/28/print_exceptions.aspx">Mike Stall’s MDbg exception harness</A>.</P>
<P>Above I said that in a catch block the frames leading up to the throw are no longer available on the stack.&nbsp; Technically, they’re still on the stack (the stack isn’t really “unwound” until you leave the catch block), but <A href="https://blogs.msdn.com/cbrumme/archive/2003/10/01/51524.aspx">the frame pointer has been reset</A> to point to the frame of the catch block (so that locals are available, etc.).&nbsp; This is true for native code as well, but powerful low-level debuggers like WinDbg allow you to switch the current context to that where an exception was thrown (.cxr command in windbg) if you have the CONTEXT pointer (which might even be saved into the dump for you – which you can access with .ecxr).&nbsp; An additional complication with managed code is that once the frame pointer has been reset, we no longer report any “roots”on the stack to the GC, so if a collection occurs there may actually be garbage pointers on (or available from) that masked portion of the stack.&nbsp; So it’s not a simple feature to expose some way to see the callstack starting from the throw site (unless we disabled inspection all locals and arguments, or allowed it to fail unpredictably).&nbsp; We’ve toyed with ideas for relaxing this in the CLR, but there won’t be any improvements here in CLR v4.</P>
<P>[Update] One other detail to be aware of with this approach is that the StackTrace in the Exception object is filled in by the CLR on the first pass, and so when your filter is hit the Exception's stack trace will only contain the frames above the function with the try block on the stack (just as if the exception had been caught at that point).&nbsp; If you're replacing catch blocks with filters then this shouldn't be surprising.&nbsp; But if you're sprinking filters in places that used to just let exceptions bubble up, then you might be surprised that there's not more details in the Exception's StackTrace.&nbsp; But the most important thing is that the full stack trace (with access to locals, etc.) is available on the thread, so in most situations what's stored inside the Exception object in a dump shouldn't really matter.</P>
<P mce_keep="true">At the PDC this year I learned that this general class of problems (error reporting / logging in the face of exceptions) is something that many customers are very interested in.&nbsp; I don’t think we’ve got a ton of great documentation on this today.&nbsp; Going forward, you should expect to see more documentation, blog entries and new features from the CLR team in this area.&nbsp; Feel free to let me know if there’s anything in particular you’d like to know more about.</P>]]></content:encoded>
    </item>
    <item>
      <title>CLR 4.0 advancements in diagnostics</title>
      <link>https://docs.microsoft.com/archive/blogs/rmbyers/clr-4-0-advancements-in-diagnostics</link>
      <pubDate>Thu, 30 Oct 2008 17:30:00 GMT</pubDate>
      <dc:creator><![CDATA[Rick Byers - exMSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/rmbyers/2008/10/30/clr-4-0-advancements-in-diagnostics/</guid>
      <description><![CDATA[We announced at PDC today that we're making some significant advances in diagnostics tool support...]]></description>
      <content:encoded><![CDATA[<P>We announced at PDC today that we're making some significant advances in diagnostics tool support for CLR v4!&nbsp; In particular, we've been investing heavily in improving our support for production diagnostics scenarios over the past couple years.&nbsp; I'm excited that we're finally able to&nbsp;start talking about it!</P>
<P>Here's a quick list of some of the things we're doing - stay tuned here,&nbsp;<A class="" href="https://blogs.msdn.com/davbr/" mce_href="https://blogs.msdn.com/davbr/">Dave's blog</A> and <A class="" href="https://blogs.msdn.com/jmstall" mce_href="https://blogs.msdn.com/jmstall">Mike's blog</A> for more details.&nbsp; Also feel free to ask questions about our strategy and specific plans for new features on <A class="" href="https://social.msdn.microsoft.com/Forums/en-US/netfxtoolsdev/threads/" mce_href="https://social.msdn.microsoft.com/Forums/en-US/netfxtoolsdev/threads/">our forum</A>&nbsp;(of course we still have a few things we're not ready to talk about yet).&nbsp; Of course, all of the features below are only available when targetting a process that is running inside version 4 of the CLR.</P>
<OL>
<LI><STRONG>Managed dump debugging<BR></STRONG>Finally you'll be able to open crash dump files in Visual Studio and see managed state (stacks, locals, etc.) without using SOS.&nbsp; The key scenario we want to enable here is taking a dump of an app/server in production (perhaps in an automated way like Windows Error Reporting) and opening that dump in Visual Studio on another machine at some point in the future.&nbsp;&nbsp;We have a big piece of this working in the VS 2010 CTP, but we still have some work to do before beta (eg. the CTP supports&nbsp;dumps with full heap memory).&nbsp; The experience in VS is very much like being stopped at a breakpoint in a live process, except you can't say "go".&nbsp; Of course production code tends to&nbsp;have JIT-optimizations enabled, so the normal caveats about debugging optimized code&nbsp;apply here too (eg. may not see all locals).&nbsp;&nbsp;Also, you can't evaluate arbitrary expressions since there is no target process to call functions in (but we have some ideas for how we might compensate for this).&nbsp; But despite the caveats, this is still a huge feature that should really help improve production diagnostics scenarios.&nbsp; This work is actually the main visible piece of a much larger "out-of-process debugging" re-architecture we've been working on for years.&nbsp; This re-arch deserves a post of it's own so stay tuned.<BR><BR></LI>
<LI><STRONG>Profiler attach (and detach) for memory diagnostics and sampling<BR></STRONG>One of the most common feature requests we hear from profiling tools is to be able to attach to a target process (today you have to set some environment variables at process start which cause your profiler to be loaded).&nbsp; Before you get too excited - this doesn't have everything you want.&nbsp; In particular, the CLR still doesn't have the ability to change the code of a method once it's been JIT-compiled (EnC is a <EM>very</EM> special case - not really applicable here).&nbsp; This means that IL instrumentation isn't available on attach, as well as a few other features (like object allocated callbacks).&nbsp; But basic memory diagnostics scenarios where the profiler inspects the heap, and simple sampling-based CPU profiling&nbsp;will now work on attach.&nbsp; We anticipate this will be useful in production scenarios - you can walk up to a server behaving badly and attach a profiler, collect some data, and detach - leaving the process in basically the same state it was before you attached.<BR>[Update: See Dave's blog entry <A class="" href="https://blogs.msdn.com/davbr/archive/2008/11/10/new-stuff-in-profiling-api-for-upcoming-clr-4-0.aspx" mce_href="https://blogs.msdn.com/davbr/archive/2008/11/10/new-stuff-in-profiling-api-for-upcoming-clr-4-0.aspx">here</A> for additional details on profiling API improvements]<BR></LI>
<LI><STRONG>Registry-free profiler activation<BR></STRONG>One major impediment to the sort of production scenario I described above is that today you have to register your profiler in the registry.&nbsp; In many production scenarios, making some change to the machine-wide system registry is very unappealing (will the dev remember to undo the change when he's done with the server, etc?).&nbsp; So to really enable production scenarios, we've also supplied a mechanism for running a process under a managed profiler (or attaching) without having to make any changes to the registry.<BR><BR></LI>
<LI><STRONG>x64 mixed-mode debugging<BR></STRONG>This isn't really a production diagnostics scenario (although you can do x64 mixed-mode dump debugging), but is one of the main debugging feature requests we've gotten.&nbsp; With this feature, "mixed-mode" (native+managed) debugging will work for x64 processes in basically the same way&nbsp;it works for&nbsp;x86 today.&nbsp; <BR><BR></LI>
<LI><STRONG>lock inspection</STRONG><BR>We're adding some simple APIs to ICorDebug which allow you to explore managed locks (Monitors).&nbsp; For example, if a thread is blocked waiting for a lock, you can find what other thread is currently holding the lock (and if there is a time-out).<BR><BR></LI>
<LI><STRONG>Corrupted-state exceptions<BR></STRONG>This feature doesn't come from our team (it's part of the core exception-handling sub-system in the CLR), but in my opinion it's a huge improvement for diagnostics scenarios.&nbsp; Basically it means that "bad" exceptions (like access violations) that propagate up the stack into manage code no longer (by default) get converted into normal .NET exceptions (System.AccessViolation) which you can accidentally catch in a "catch(Exception)" clause.&nbsp; Basically, haivng a catch(Exception) which swallows AVs coming from native code is a bad thing because you're unlikely to be able to reason about the consistency of your process after the AV.&nbsp; The default behavior for such "corrupted-state exceptions" is now to fail-fast and send an error-report (just like in normal C++ programming).&nbsp; Of course, you can override this if you REALLY need to catch such an exception.</LI></OL>
<P>That's the overview of the main CLR v4 features that affect diagnostics.&nbsp; Of course there are also lots of other great things coming in CLR v4 and the rest of .NET Fx 4.0.<BR></P>]]></content:encoded>
    </item>
    <item>
      <title>ICorDebug re-architecture in CLR 4.0</title>
      <link>https://docs.microsoft.com/archive/blogs/rmbyers/icordebug-re-architecture-in-clr-4-0</link>
      <pubDate>Mon, 27 Oct 2008 15:08:00 GMT</pubDate>
      <dc:creator><![CDATA[Rick Byers - exMSFT]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/rmbyers/2008/10/27/icordebug-re-architecture-in-clr-4-0/</guid>
      <description><![CDATA[In my previous post I mentioned that CLR 4.0 will support managed dump debugging through ICorDebug,...]]></description>
      <content:encoded><![CDATA[<P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'">In <A class="" href="https://blogs.msdn.com/rmbyers/archive/2008/10/26/clr-4-0-advancements-in-diagnostics.aspx" mce_href="https://blogs.msdn.com/rmbyers/archive/2008/10/26/clr-4-0-advancements-in-diagnostics.aspx">my previous post</A> I mentioned that CLR 4.0 will support managed dump debugging through ICorDebug, and that to do this we had to re-architect the debugging support in the CLR.&nbsp; I want to give you a little more detail about what we've been doing here.&nbsp; I'm sure I (and others) will be discussing more details in the time leading up to CLR 4.0 RTM, so stay tuned and also feel free to ask questions on this in our forum.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p></SPAN></P>
<P><STRONG><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'">History and background</SPAN></STRONG><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'"><BR>First, if you haven't already, read <A href="https://blogs.msdn.com/jmstall/archive/2005/02/09/370178.aspx">Mike's blog entry</A> describing the difference between "hard-mode" and "soft-mode" debugging, and his <A href="https://blogs.msdn.com/jmstall/archive/2004/10/13/241828.aspx"><FONT color=#0000ff>related entry</FONT></A> describing the implication of relying on a helper thread. Mike has clearly been thinking about this for a long time, and the successes we announced at PDC are due in large part to Mike's dedication, vision, and hard-work on this project for the past several years.&nbsp; In fact, after reading this post, if you go back and read other ICorDebug-related entries on Mike’s blog you’ll find a lot of great details on the thinking that lead to the design points I discuss below.&nbsp; Drew Bliss (while he was on the WinDbg team)&nbsp;was also instrumental to the early vision, design and implementation of our re-architecture.<o:p></o:p></SPAN></P>
<P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'">As you know from Mike's blog, there are clearly a number of advantages to being able to debug from out-of-process (not the least of which is support for dump debugging).&nbsp; The big challenge is how to implement this in a maintainable way for a complex system with lots of fancy data structures and algorithms for accessing them.&nbsp; We've actually been experimenting with prototypes for doing this for many years (since nearly the start of the CLR), and this is exactly what <A href="https://msdn.microsoft.com/en-us/magazine/cc164138.aspx"><FONT color=#0000ff>SOS</FONT></A> relies on.&nbsp; But it's really only been in the past few years that we've developed the confidence to move ALL managed debugging towards an out-of-process model.&nbsp; A power-user tool like SOS has somewhat different requirements&nbsp;from a production-grade API used by millions of developers every day in their Visual Studio debugging sessions.&nbsp; <o:p></o:p></SPAN></P>
<P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'">The way we attempt to address the maintenance issue is to build both the normal in-process CLR code (mscorwks.dll) and the out-of-process code (mscordacwks.dll) from the same code base.&nbsp; We use some fancy C++ templates to instrument all pointer dereferences so that we can read memory from the target process instead of the process in which the code is executing ("host process").&nbsp; We call this, and it's related infrastructure, our "DAC" (data access component) technology.&nbsp; There are still a lot of challenges associated with DAC (eg. trying to help CLR developers reason about their code when there are two separate address spaces involved), but we've taken it far enough that we're willing to trust the approach.&nbsp; If people are interested, I'd be happy to go into more detail on this in the future, but let's move on now to what we're actually delivering in CLR v4.<o:p></o:p></SPAN></P>
<P><STRONG><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'">Design points for ICorDebug v4.0</SPAN></STRONG><B><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'"><BR></SPAN></B><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'">Here's a list of principles we followed in the design for debugging in CLR v4.0.&nbsp; There’s a lot of overlap here since these design points are all part of a single coherent vision.&nbsp; Just skimming this list should give you a pretty good idea of what our new architecture is all about.&nbsp; I’ll save going into the concrete details of the new API here (although you can grab the new cordebug.idl from the CTP VPC image and explore it yourself if you're really curious).</P>
<OL type=1>
<LI>Debugging a 4.0 managed app requires a 4.0-aware debugger (i.e. we <EM>are</EM> making breaking changes)<BR>It has always been our policy that a debugger needs to be designed to understand the&nbsp;major features of the run-time, and so with a major new release of the runtime (like 4.0) we will require updates to the debugger.&nbsp;&nbsp;This means that VS 2008 will not be able to debug code running in the V4 CLR (exaclty like VS 2003 couldn't debug code running in CLR v2) - but see below.<BR>&nbsp;</LI>
<LI>Migrating a 2.0 debugger to support 4.0 should be very easy<BR>Although we want to hold a hard line on our compat policy above, we are working very hard to make it easy for debuggers to update their code to support CLR v4.&nbsp; In almost all cases, we're not removing / disabling or drastically changing the semantics of any existing APIs.&nbsp;&nbsp; We are adding a bunch of new APIs and re-implementing the existing APIs on top of them, thus giving you the choice of which to use (the new APIs tend to have a lower level of abstraction).&nbsp; In fact, you could install VS 2008 on the <A href="https://www.microsoft.com/downloads/details.aspx?FamilyId=922B4655-93D0-4476-BDA4-94CF5F8D4814&amp;displaylang=en">.NET 4.0 CTP image</A> and debug code running in the 4.0 CLR.&nbsp; In adition to wanting to make it easy for debugger writers to migrate, we also didn't want to force everyone inside Microsoft using early CLR v4 builds to also use VS 2010 as their debugger until it reaches beta quality.&nbsp; By the time we ship the beta, we'll explicitly break this to ensure we're not setting any unrealistic expectations.<BR>&nbsp;</LI>
<LI>Re-architecture is incremental instead of a complete rewrite<BR>We (mainly, to his credit, Mike) decided early on that we should transition to this new architecture incrementally while keeping our system working throughout.&nbsp; This was done partly for pragmatic reasons, for example that we wanted to always have a working Visual Studio without having to wait for them to update to our new architecture in lock-step with us.&nbsp; This also enabled us to react to changes in the business plan.&nbsp; For example, when we decided to ship Silverlight 2 based on the latest CLR code base (i.e. the V4 branch) rather than based on the CLR v2 codebase, we were pretty-much prepared to ship the current state of our re-architecture even though we weren't yet "done" (we did have to spend a month or so adding Mac support to our new architecture - but that was a relatively isolated new feature, as opposed to a race to productize an unfinished codebase).<BR>&nbsp;</LI>
<LI>Maintain a single, self-consistent debugging API based on ICorDebug<BR>Despite the huge fundamental changes we needed to make, we decided we needed to maintain consistency with the existing ICorDebug APis as much as possible.&nbsp; Again, this helps ensure that existing managed debuggers can take advantage of our new functionality as easily as possible.&nbsp; In fact, the VS debugger team spent only a few weeks adding the initial dump debugging support to VS 2010 because we made all the inspection operations behave exactly the same as for live debugging (we even had a hacked-up demo of dump-debugging working with VS 2008 without ANY VS changes at all!).<BR>&nbsp;</LI>
<LI>All access to the target is abstracted through a callback interface<BR>In V2, ICorDebug used a number of different Win32 APIs to interact with the target process (eg. using ReadProcessMemory, GetThreadContext, shared-memory blocks, and named events).&nbsp; In V4, the core of ICorDebug uses a simple abstraction we call the "data target" (ICorDebugDataTarget) that a debugger implements.&nbsp; This basically just has methods like 'ReadVirtual' (read some memory) and 'GetThreadContext' (get CPU state).<BR>&nbsp;</LI>
<LI>ICorDebug can operate in two difference modes - "pure out-of-process v4" and "v2 compatibility" <BR>Again, this is related to everything we've been discussing above.&nbsp; In v2 compat mode, you create an ICorDebug instance in a similar way to V2, and use that to, for example, attach to a process given a PID to get an ICorDebugProcess that can do everything the one in V2 could do.&nbsp; In this case, we implement the ICDDataTarget object ourselves.&nbsp; In pure v4 mode, you use an alternate "open virtual process" creation API that basically just takes an ICDDataTarget and returns an ICorDebugProcess whose connection to the target is completely abstracted.&nbsp; Today, a pure v4 ICDProcess only has the ability to do inspection operations (i.e. mainly just dump debugging), but we'll be enabling more out-of-process functionality (like stepping) in future releases.<BR>&nbsp;</LI>
<LI>In v4-mode, ICorDebug acts just as a utility library for existing native debuggers<BR>In V2 and before, ICorDebug really behaves as if it owns the target process.&nbsp; This has a lot of negative implications, most significantly that it makes mixed-mode debugging <A href="https://blogs.msdn.com/jmstall/archive/2007/01/10/dont-write-an-interop-debugger.aspx">extremely difficult</A> and brittle.&nbsp; It also means that when debuggers want to add features, they often need to come to us (this is especially problematic for us given that the Visual Studio debugger team has a lot more people than the CLR debugger team &lt;grin&gt;).&nbsp; Really we want to enable debuggers to implement their own policy and control of the target process rather than imposing a lot of policy ourselves.&nbsp; This means we're lowering the level of abstraction of ICorDebug in some places.&nbsp; SOS, as an extension that runs on top of a native debugger like WinDbg, &nbsp;clearly already follows this principle.&nbsp; An example benefit is that native debuggers like Visual Studio and WinDbg already have some policy and mechanism for skipping over breakpoints, and now in v4-mode we no longer have to have a completely different policy and mechanism for managed breakpoints.&nbsp; This principle leads directly to the following design decision.<BR>&nbsp;</LI>
<LI>Under the hood we're built on the native debugging pipeline<BR>In v2-compat mode, ICD continues to own the pipeline to the target process (since that was the V2 model), but that pipeline is no longer a collection of shared IPC objects with the target process, but is instead the same pipeline a native debugger uses.&nbsp; Specifically, we attach to a process by calling kernel32!DebugActiveProcess, and get our managed events (things that result in calls to ICorDebugManagedCallback) using kernel32!WaitForDebugEvent.&nbsp; This also means that kernel32!IsDebuggerPresent now returns true when doing managed-only debugging.&nbsp; This also has the nice side-effect of avoiding the problem with doing managed-only debugging when a kernel debugger is enabled (the OS assumes any breakpoint instructions that occur when a debugger isn't attached should cause a break in the kernel debugger).<BR>&nbsp;</LI></OL>
<P>&nbsp;Ok, I think those are the most important design points.&nbsp; Sometime later I'll start going into more of the concrete details. &nbsp;&nbsp;Post a comment if you have any specific things you'd like to hear about.</P></SPAN>]]></content:encoded>
    </item>
  </channel>
</rss>