<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>voyce &#187; .NET</title>
	<atom:link href="http://www.voyce.com/index.php/tag/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.voyce.com</link>
	<description>Programming and debugging tidbits</description>
	<lastBuildDate>Sat, 03 Jul 2010 12:40:51 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Minilight renderer in F#</title>
		<link>http://www.voyce.com/index.php/2010/06/30/minilight-renderer-in-fsharp/</link>
		<comments>http://www.voyce.com/index.php/2010/06/30/minilight-renderer-in-fsharp/#comments</comments>
		<pubDate>Wed, 30 Jun 2010 17:19:43 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[monte carlo]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=938</guid>
		<description><![CDATA[Porting the Minilight global illumination renderer to F#.]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_961" class="wp-caption alignleft" style="width: 150px"><a href="http://www.voyce.com/wp-content/uploads/2010/06/cornellbox-e.png"><img src="http://www.voyce.com/wp-content/uploads/2010/06/cornellbox-e.png" alt="Cornell Box in the evening" title="cornellbox-e" width="140" height="140" class="size-full wp-image-961" /></a><p class="wp-caption-text">Cornell Box in the evening</p></div>I&#8217;m a sucker for eye-candy, and the other day I came across the beautifully lit renders produced by <a href="http://www.hxa.name/minilight/">Minilight</a>. It&#8217;s a nice, minimal implementation of a global illumination renderer that&#8217;s been ported to a wide variety of different languages from C to ActionScript. So of course, I couldn&#8217;t resist trying to implement it in F#.<br />
<span id="more-938"></span></p>
<h3>What is a &#8220;global illumination renderer&#8221;?</h3>
<p>In short; a global illumination renderer attempts to simulate the way that light behaves in the real world. It bounces rays of light around the scene, noting which surfaces are hit, and how each of them affects the ray. Of course real light travels fast &#8211; at about the speed of light, in fact &#8211; and our simulated rays can&#8217;t match that, so although the resulting effect looks natural, it&#8217;s not a very efficient way of getting there. Graphics systems that need to be near real-time (i.e. games), use a variety of short-cuts to try and get the same effect without requiring the same amount of number crunching.</p>
<p>Even this implementation is forced to use a couple of techniques to improve performance, I won&#8217;t go into them here, as they&#8217;re explained pretty thoroughly on the Minilight site. </p>
<p>Interestingly the algorithm uses a Monte Carlo technique to simulate the random path of the ray through the scene and the same technique is used in finance to model how the price of an asset will change through time. </p>
<h3>Translating to F#</h3>
<p><div id="attachment_970" class="wp-caption alignright" style="width: 160px"><a href="http://www.voyce.com/wp-content/uploads/2010/06/roomfront.sun.ml.png"><img src="http://www.voyce.com/wp-content/uploads/2010/06/roomfront.sun.ml-150x150.png" alt="Room with sun and light, 800 paths per pixel" title="roomfront.sun.ml" width="150" height="150" class="size-thumbnail wp-image-970" /></a><p class="wp-caption-text">Room with sun and light, 800 paths per pixel</p></div>Luckily, the existing OCaml version is considered one of the reference implementations, and as ML is the spiritual predecessor of F# I didn&#8217;t expect it to be too difficult to port. It wasn&#8217;t. I&#8217;m no ML expert, so some of the language features were a bit of a surprise; things like the use of a dot on all of the operators, but these are pretty minimal syntactic differences.</p>
<p>Some of the ML constructs caused warnings from the F# compiler as I didn&#8217;t use the explicit ML compatibility mode. For instance, the use of the <code>^</code> operator to concatenate strings:<br />
<code><br />
warning FS0062: This construct is for ML compatibility. Consider using the '+' operator instead. This may require a type annotation to indicate it acts on strings.<br />
</code><br />
Some other changes included:</p>
<ul>
<li>Using dot rather than # notation to access class members</li>
<li>Using square bracket for array element access (<code>array.[n]</code> rather than <code>array.(n)</code>)</li>
<li>Removing <code>let...and</code> for non-recursive bindings</li>
</ul>
<p>There was also the opportunity to make use of some of the .NET framework classes, things like <code>System.Drawing.Bitmap</code> to write pixels directly into a bitmap and then save it into a .PNG file. Much easier than trying to find something to read the .PPM file that the original version emits.    </p>
<h3>Potential improvements</h3>
<p>One of the most obvious improvements that could be made is to make use of the parallelism support in F# and .NET. The algorithm itself is easily (if not embarrassingly) parallelisable, given that it iterates over the pixels in the output image, and performs independent operations on each of them. Unfortunately I haven&#8217;t had a chance to look at this yet &#8211; and the Windows VM I&#8217;m using only has a single processor anyway, so on a purely selfish note, I wouldn&#8217;t see any immediate performance improvements.  It should be as simple as changing the pixel loop to use <code>Parallel.For</code>, or creating an <code>async</code> computation expression.</p>
<p>Something else to note: I err&#8217;d on the side of caution when it comes to saving intermediate images, so every iteration it creates and writes the file. This will be doing lots of allocation and strictly unnecessary work, especially for simple scenes.</p>
<p>Given this approach is so completely compute bound it would be interesting to see how moving some of the calculations to a GPU would affect it. It might even be possible to use quotations for some of the inner loops and then generate Nvidia intermediate language (PTX) from them &#8211; that&#8217;s something I&#8217;ve been wanting to do for a while. </p>
<p>I did run the code through the Visual Studio 2010 profiler to get a rough idea of where the time was being spent; it looked like the majority was in the leaf of the calculations where numerical operations where being performed on the vectors, which is consistent with what we&#8217;d expect.</p>
<h3>Use the source</h3>
<p>So, here&#8217;s the source. No warranties implied, use at your own risk, your mileage may vary, all errors are mine etc, etc.<br />
<a href='http://www.voyce.com/wp-content/uploads/2010/06/minilight_fsharp.zip'>minilight_fsharp</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/06/30/minilight-renderer-in-fsharp/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>.NET 4.0 Type Equivalence causes BadImageFormatException</title>
		<link>http://www.voyce.com/index.php/2010/04/23/net-4-0-type-equivalence-causes-badimageformatexception/</link>
		<comments>http://www.voyce.com/index.php/2010/04/23/net-4-0-type-equivalence-causes-badimageformatexception/#comments</comments>
		<pubDate>Fri, 23 Apr 2010 10:53:33 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[WinDbg]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[.NET4]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[IL]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=840</guid>
		<description><![CDATA[Interop assemblies containing certain constructs will cause a BadImageFormatException in .NET 4.0]]></description>
			<content:encoded><![CDATA[<p>I recently discovered a nasty backward compatibility problem with the new type equivalence feature in .NET 4.0. Luckily it&#8217;s relatively difficult to hit it if you&#8217;re in a pure-C# environment, but if you happen to generate any assemblies directly using IL, you should watch out. Read on for all the gory details.<br />
<span id="more-840"></span></p>
<h2>What is .NET type equivalence?</h2>
<p>Described at a high level <a href="http://msdn.microsoft.com/en-us/library/dd997297.aspx">here</a>, .NET 4.0 type equivalence essentially gives you a way of indicating that different .NET types represent the same underlying COM type and is most commonly used in COM interop scenarios. One of the reasons for its introduction is to save developers from having to ship large interop DLLs with their software, e.g. the multi-megabyte Microsoft.Office.Interop. Instead the compiler can inline the definition of any types used, and mark them appropriately as representing the original COM types. </p>
<h2>The error</h2>
<p>We noticed that whenever we built and ran an application that referenced a DLL using .NET 2.0, it worked. Doing the same thing with .NET 4.0 caused a <a href="http://msdn.microsoft.com/en-us/library/system.badimageformatexception.aspx">BadImageFormatException</a>.<br />
<code><br />
Unhandled Exception: System.BadImageFormatException: Could not load file or assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. An attempt was made to load a program with an incorrect format.<br />
   at X.Main()<br />
</code> </p>
<h2>Let&#8217;s dig!</h2>
<p>So, the BadImageFormatException doesn&#8217;t actually tell us much. Let&#8217;s break out WinDbg and see what we can find. Running the faulting app we can see several C++ exceptions before the CLR exception is thrown:<br />
<code><br />
(178c.790): C++ EH exception - code e06d7363 (first chance)<br />
...<br />
(178c.790): C++ EH exception - code e06d7363 (first chance)<br />
(178c.790): CLR exception - code e0434352 (first chance)<br />
</code><br />
I changed the exception handling settings to stop on C++ exceptions (<code>sxe eh</code>) then ran again to see where things were going wrong. It stopped here:<br />
<code><br />
0:000> kp<br />
ChildEBP RetAddr<br />
0012d15c 79084c0f KERNEL32!RaiseException+0x53<br />
0012d194 793371be MSVCR100_CLR0400!_CxxThrowException+0x48<br />
0012d5e4 79455cae clr!EEFileLoadException::Throw+0x1a8<br />
0012d634 794558d2 clr!CompareTypeTokens+0x200<br />
0012d6b0 791b5c00 clr!IsTypeDefEquivalent+0x102<br />
0012d6d4 791b2ca8 <b>clr!MethodTableBuilder::CheckForTypeEquivalence</b>+0x94<br />
0012d7ac 791b27c9 clr!MethodTableBuilder::BuildMethodTableThrowing+0x60d<br />
0012d9a4 791a4578 clr!ClassLoader::CreateTypeHandleForTypeDefThrowing+0x88e<br />
</code><br />
Interesting. Notice how the call stack contains some .NET 4.0 specific methods relating to the new type equivalence feature. We&#8217;re hitting a new code path, which is consistent with the fact that running against a down-level CLR works.</p>
<p>After a bit more toing-and-froing, I discovered that the C++ exception is thrown when <code>clr!MDInternalRO::IsValidToken</code> returns an error. By disassembling the function we can see it&#8217;s just looking at various bits in the token value, and it decides that the value passed (0&#215;02000000) isn&#8217;t valid. Looking at the output from ildasm that token doesn&#8217;t appear anywhere. And if we add a dump of the value, we can see that it indeed doesn&#8217;t look like the other tokens: </p>
<pre>
0:000> bu clr!MDInternalRO::IsValidToken "dd esp+8 L1; g"
...
0012f5a8  02000001
0012f31c  06000001
0012f2c0  02000002
0012f0f4  02000002
0012ebe4  01000001
0012e944  23000001
...
0012d5f4  02000000
(18ec.1ec8): C++ EH exception - code e06d7363 (first chance)
</pre>
<h2>What&#8217;s the culprit?</h2>
<p>So it looks pretty conclusive; the DLL contains something that the CLR isn&#8217;t expecting. But what? It&#8217;s time to break out the oldest tool in the troubleshooting box: the binary chop!</p>
<p>Eventually I got the referenced DLL down to only a single simple construct. Can you guess what it is? A global literal value. A <em>real</em> global value, one that isn&#8217;t even part of a type. Crazy huh? In IL it looks like this:<br />
<code><br />
.field public static literal valuetype Test.MyEnum LiteralValue = int32(0x00000001)<br />
</code><br />
It&#8217;s a literal value of an enumerated type. That&#8217;s important: using a value of a simple type (say int32) does not provoke the error.</p>
<p>Now, I wasn&#8217;t even sure that this is a valid IL construct, but according to the ECMA IL spec, specifically <a href="http://jilc.sourceforge.net/ecma_p2_cil.shtml#_Toc524940530">partition II, section 15</a>, it is:</p>
<blockquote><p>The CLI also supports global fields, which are fields declared outside of any type definition. Global fields shall be static.</p></blockquote>
<p>So it looks like we&#8217;re not doing anything illegal, backed up by the fact that the .NET 2.0 CLR can make use of it without a problem.</p>
<p>Interestingly, there&#8217;s another aspect that influences whether this code path is hit. As mentioned above, type equivalence is intended for use with interop libraries. As such, it only kicks in if your referenced assembly is marked with the PrimaryInteropAssembly attribute, e.g.:</p>
<p><code><br />
  .custom instance void [mscorlib]System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute::.ctor(int32,int32) = ( 01 00 01 00 00 00 00 00 00 00 00 00 )<br />
</code></p>
<h2>The Fix?</h2>
<p>The issue is currently with Microsoft product support. Let&#8217;s see what they come up with; is it too esoteric for a hotfix&#8230;?</p>
<h2>The Repro</h2>
<p>Here&#8217;s some code and instructions on how to repro the problem.</p>
<ol>
<li>Build the IL into a DLL using ilasm.<br />
<code>"c:\WINNT\Microsoft.NET\Framework\v2.0.50727\ilasm.exe" /dll Test.il /output=Test.dll</code>
</li>
<li>Build the application into a .NET 4.0 EXE that references the DLL<br />
<code>"c:\winnt\Microsoft.NET\Framework\v4.0.30319\csc.exe" TestConsumer.cs /reference:Test.dll</code>
</li>
<li>Run the resulting <code>TestConsumer.exe</code> application and you&#8217;ll get the exception</li>
</ol>
<p><b>Test.il</b><br />
<code><br />
.assembly extern mscorlib<br />
{<br />
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )<br />
  .ver 2:0:0:0<br />
}<br />
.assembly Test<br />
{<br />
  .custom instance void [mscorlib]System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute::.ctor(int32,int32) = ( 01 00 01 00 00 00 00 00 00 00 00 00 )<br />
  .hash algorithm 0x00008004<br />
  .ver 1:0:0:0<br />
}<br />
.module Test.dll<br />
.imagebase 0x00400000<br />
.file alignment 0x00000200<br />
.stackreserve 0x00100000<br />
.subsystem 0x0003<br />
.corflags 0x00000001 </p>
<p>.field public static literal valuetype Test.MyEnum LiteralValue = int32(0x00000001)</p>
<p>.class public auto ansi sealed Test.MyEnum<br />
       extends [mscorlib]System.Enum<br />
{<br />
  .field public specialname rtspecialname int32 value__<br />
  .field public static literal valuetype Test.MyEnum Zero = int32(0x00000000)<br />
  .field public static literal valuetype Test.MyEnum One = int32(0x00000001)<br />
}<br />
</code><br />
<b>TestConsumer.cs</b></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">class</span> X
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        var v <span style="color: #008000;">=</span> Test.<span style="color: #0000FF;">MyEnum</span>.<span style="color: #0000FF;">Zero</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/04/23/net-4-0-type-equivalence-causes-badimageformatexception/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Beware of using stack-based COM objects from .NET</title>
		<link>http://www.voyce.com/index.php/2010/01/21/beware-of-using-stack-based-com-objects-from-net/</link>
		<comments>http://www.voyce.com/index.php/2010/01/21/beware-of-using-stack-based-com-objects-from-net/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 17:16:57 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WinDbg]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[mscorwks]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=618</guid>
		<description><![CDATA[COM objects that don't have the expected lifetime can cause chaos when combined with .NETs garbage collection system.]]></description>
			<content:encoded><![CDATA[<p>There are all sorts of nasty things to be aware of if you&#8217;re mixing reference-counted COM objects with garbage-collected .NET. For instance, if you&#8217;re implementing COM objects in C++ then you&#8217;re free to allocate them anywhere you like; on the heap or perhaps on the stack if you know they&#8217;re only used in some specific scope.</p>
<p>But what happens if during the lifetime of that stack based COM object, it gets used from .NET? A runtime callable wrapper (RCW) will be created around the object. And this RCW expects to be able to keep the underlying object alive by incrementing its reference count. Of course, the stack-based object will soon go out of scope, and regardless of its reference count the object will be destroyed and the pointer that the RCW contains will no longer be valid. It points into the stack, so when the RCW gets cleaned-up, the CLR will call via this pointer into memory that contains garbage and you&#8217;ll get something nasty like an access violation or illegal instruction exception. </p>
<p><span id="more-618"></span></p>
<p>It&#8217;s fairly easy to reproduce this to see where things go wrong. It can be useful to see where the CLR blows up, and how we can identify this as the cause.</p>
<p>Lets start by creating a simple pseudo-COM object that implements just the bare minimum to be usable:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">class</span> MyClass <span style="color: #008080;">:</span> <span style="color: #0000ff;">public</span> IUnknown
<span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span>
	MyClass<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">:</span>l<span style="color: #008000;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span>
	STDMETHOD_<span style="color: #008000;">&#40;</span>ULONG, AddRef<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> InterlockedIncrement<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>l<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
	STDMETHOD_<span style="color: #008000;">&#40;</span>ULONG, Release<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> InterlockedDecrement<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>l<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
	STDMETHOD<span style="color: #008000;">&#40;</span>QueryInterface<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>REFIID iid, <span style="color: #0000ff;">void</span> <span style="color: #000040;">**</span> ppvObject<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>iid <span style="color: #000080;">==</span> IID_IUnknown<span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			<span style="color: #000040;">*</span>ppvObject <span style="color: #000080;">=</span> <span style="color: #0000dd;">this</span><span style="color: #008080;">;</span>
			AddRef<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
                        <span style="color: #0000ff;">return</span> S_OK<span style="color: #008080;">;</span>
		<span style="color: #008000;">&#125;</span>
		<span style="color: #0000ff;">return</span> E_NOINTERFACE<span style="color: #008080;">;</span>
	<span style="color: #008000;">&#125;</span>
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span>
	<span style="color: #0000ff;">long</span> l<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>We&#8217;ll also need a COM visible .NET object that will use the object. It doesn&#8217;t actually need to be COM visible, but that&#8217;s the easiest way to access it from C++, in my opinion.</p>
<p>I&#8217;ve created the COM object in F#. It&#8217;s a trivial class that has a single interface, with a single method that takes the object we pass to it and prints its type. This is enough for the RCW to be created.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">open</span> System
<span style="color: #06c; font-weight: bold;">open</span> System<span style="color: #000080;">.</span><span style="color: #505090;">Runtime</span><span style="color: #000080;">.</span><span style="color: #505090;">InteropServices</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">module</span> Module1 <span style="color: #000080;">=</span>
&nbsp;
    <span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>ComVisible<span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">true</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">;</span> InterfaceType<span style="color: #000080;">&#40;</span>ComInterfaceType<span style="color: #000080;">.</span><span style="color: #505090;">InterfaceIsIUnknown</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">public</span> IConsumer <span style="color: #000080;">=</span> 
        <span style="color: #06c; font-weight: bold;">abstract</span> <span style="color: #06c; font-weight: bold;">member</span> UseObject <span style="color: #000080;">:</span> o<span style="color: #000080;">:</span>obj <span style="color: #000080;">-&gt;</span> unit
&nbsp;
    <span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>ComVisible<span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">true</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">;</span> ClassInterface<span style="color: #000080;">&#40;</span>ClassInterfaceType<span style="color: #000080;">.</span><span style="color: #505090;">None</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">public</span> Consumer<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">interface</span> IConsumer <span style="color: #06c; font-weight: bold;">with</span>
            <span style="color: #06c; font-weight: bold;">member</span> this<span style="color: #000080;">.</span><span style="color: #505090;">UseObject</span> <span style="color: #000080;">&#40;</span>o<span style="color: #000080;">:</span>obj<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
                Console<span style="color: #000080;">.</span><span style="color: #505090;">WriteLine</span> <span style="color: #000080;">&#40;</span>sprintf <span style="color: #008080;">&quot;%A&quot;</span> <span style="color: #000080;">&#40;</span>o<span style="color: #000080;">.</span><span style="color: #505090;">GetType</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>We can compile this into a DLL, then run regasm with the /tlb switch to generate a type library (TLB):</p>
<pre>
fsc -o:obj\Debug\testStackObjectsFs.dll Module1.fs
regasm /tlb:testStackObjectsFs.tlb testStackObjectsFs.dll
</pre>
<p>That can be #imported back into our test harness:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#import &quot;testStackObjectsFs.tlb&quot;</span></pre></div></div>

<p>Now we&#8217;re ready to put together some code that creates an instance of our object on the stack and passes it to our .NET component:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> Foo<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #666666;">// Create an instance of our &quot;COM object&quot; on the stack</span>
	MyClass obj<span style="color: #008080;">;</span>
&nbsp;
	<span style="color: #666666;">// Create a managed object</span>
	testStackObjectsFs<span style="color: #008080;">::</span><span style="color: #007788;">IConsumerPtr</span> mgd<span style="color: #008000;">&#40;</span>__uuidof<span style="color: #008000;">&#40;</span>testStackObjectsFs<span style="color: #008080;">::</span><span style="color: #007788;">Consumer</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
	<span style="color: #666666;">// and pass our COM object to it</span>
	mgd<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>UseObject<span style="color: #008000;">&#40;</span>_variant_t<span style="color: #008000;">&#40;</span><span style="color: #000040;">&amp;</span>obj<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">int</span> _tmain<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> argc, _TCHAR<span style="color: #000040;">*</span> argv<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #666666;">// Initialise the COM runtime, for our purposes it doesn't</span>
	<span style="color: #666666;">// matter which threading model we use</span>
	CoInitializeEx<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">NULL</span>, COINIT_MULTITHREADED<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
	<span style="color: #666666;">// Call a separate function, to ensure stack-based objects</span>
	<span style="color: #666666;">// are out-of-scope on return.</span>
	Foo<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
	<span style="color: #666666;">// Wait for some input</span>
	_getch<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Now, if you run this from within Visual Studio, if you&#8217;re vigilant (and you haven&#8217;t got your debugger set to stop on access violations), then you&#8217;ll notice this in the output window after the return statement executes:<br />
<code><br />
...<br />
The thread 'Win32 Thread' (0x15b0) has exited with code 11001 (0x2af9).<br />
The thread 'Win32 Thread' (0x1110) has exited with code 0 (0x0).<br />
<b>First-chance exception at 0x00850a2b in testStackObjects.exe: 0xC0000005: Access violation reading location 0x00850a2b.</b><br />
The thread 'DebuggerRCThread::ThreadProcStatic' (0x1534) has exited with code 0 (0x0).<br />
The thread 'RPC Callback Thread' (0x12b8) has exited with code 0 (0x0).<br />
...<br />
</code><br />
Lets ramp up WinDbg, attach to the process (that _getch comes in useful here) and find out what&#8217;s going on in a bit more detail.</p>
<p>If we let the app run to the point of failure in WinDbg, we can see that the CLR was in the act of shutting down when it caused the exception:<br />
<code><br />
0:002> kp<br />
ChildEBP RetAddr<br />
WARNING: Frame IP not in any known module. Following frames may be wrong.<br />
00dae3fc 79f4c1b5 0xe06ff8<br />
00dae450 79f4c26c mscorwks!ReleaseTransitionHelper+0x5f<br />
00dae494 79f4c2d0 mscorwks!SafeReleaseHelper+0x8c<br />
00dae4c8 79faaa01 mscorwks!SafeRelease+0x2f<br />
00dae4fc 79faa7c8 mscorwks!IUnkEntry::Free+0x68<br />
00dae510 79faa91d mscorwks!RCW::ReleaseAllInterfaces+0x18<br />
00dae540 79faa949 mscorwks!RCW::ReleaseAllInterfacesCallBack+0xbd<br />
00dae570 7a0792ac mscorwks!RCW::Cleanup+0x22<br />
00dae57c 7a079714 mscorwks!RCWCleanupList::ReleaseRCWListRaw+0x16<br />
00dae5ac 7a0797df mscorwks!RCWCleanupList::ReleaseRCWListInCorrectCtx+0xdf<br />
00dae5fc 79fdc140 mscorwks!RCWCleanupList::CleanupAllWrappers+0x77<br />
00dafe90 79fdc7aa mscorwks!RCWCache::ReleaseWrappersWorker+0x103<br />
00dafed8 79fd9f95 mscorwks!ReleaseRCWsInCaches+0x27<br />
00dafee0 79f3c76a mscorwks!InnerCoEEShutDownCOM+0x1e<br />
00daff14 79f92015 mscorwks!WKS::GCHeap::FinalizerThreadStart+0x1fc<br />
00daffb4 7c80b683 mscorwks!Thread::intermediateThreadProc+0x49<br />
00daffec 00000000 kernel32!BaseThreadStart+0x37<br />
</code><br />
Essentially it&#8217;s cleaning up the currently unused RCWs &#8211; including our malformed one &#8211; and as part of doing this, it&#8217;s calling Release on the underlying COM object, via the mscorwks!SafeRelease function. SafeRelease wraps the call to potentially (and definitely, in this case) dangerous unmanaged code with various exception handlers, enabling it to silently handle access violations. </p>
<p>If we run the app again, and this time break while it&#8217;s waiting for the keypress, before it attempts to clean up the RCWs, then we can examine the wrapper ourselves, using the approach I set out in <a href="http://www.voyce.com/index.php/2009/09/03/getting-iunknown-from-__comobject/">this post</a>.</p>
<p>List all of the untyped COM object wrappers:</p>
<pre>
0:002> !dumpheap -type System.__ComObject
 Address       MT     Size
<font color="blue"><b>01418628</b></font> 79306e60       16
total 1 objects
Statistics:
      MT    Count    TotalSize Class Name
79306e60        1           16 System.__ComObject
Total 1 objects
</pre>
<p>Use the address of the object to obtain its object header:<br />
<code><br />
0:002> dd <font color="blue">1418628</font>-4 L1<br />
01418624  0800<font color="red"><b>0002</b></font><br />
</code><br />
Use the syncblk identifier in the header to get the syncblk:</p>
<pre>
0:002> !syncblk <font color="red">2</font>
Index SyncBlock MonitorHeld Recursion Owning Thread Info  SyncBlock Owner
    2 <font color="darkgreen"><b>001e4d9c</b></font>            0         0 00000000     none    01418628 System.__ComObject
-----------------------------
Total           2
CCW             0
RCW             0
ComClassFactory 0
Free            0
</pre>
<p>Get the address of the RCW from the sync block:<br />
<code><br />
0:008> dd <font color="darkgreen">001e4d9c</font>+1c L1<br />
001e4db8  001e7dc8<br />
0:008> dd 001e7dc8+c L1<br />
001e7dd4  <font color="purple"><b>001de828</b></font><br />
</code><br />
And dump out the relevant bits of the RCW, the vtable of the object, at offset 0&#215;88, and the IUnknown pointer, at offset 0&#215;64:<br />
<code><br />
0:008> dds <font color="purple">001de828</font>+88 L1<br />
001de8b0  0041ac78 testStackObjects!MyClass::`vftable'<br />
0:008> dds <font color="purple">001de828</font>+64 L1<br />
001de88c  0012fe7c<br />
</code><br />
We can use <code>!address</code> to do a quick sanity check on the pointer and verify what we know to be the case; it&#8217;s stack memory:</p>
<pre>
0:008> !address 0012fe7c
    00030000 : 00124000 - 0000c000
                    Type     00020000 MEM_PRIVATE
                    Protect  00000004 PAGE_READWRITE
                    State    00001000 MEM_COMMIT
                    Usage    <b>RegionUsageStack</b>
                    Pid.Tid  490.13dc
</pre>
<p>If we run the app on again to the point that it fails, we can clearly see the address of the object being passed as an argument to <code>mscorwks!IUnkEntry::Free</code>.</p>
<p>So the moral of the story is; don&#8217;t pretend some arbitrary piece of stack memory is a real, reference counted COM object. You may be saving the cost of a heap allocation, but even if your app works OK today, it may not tomorrow when someone introduces a piece of .NET code somewhere in your object graph.</p>
<h4>Bonus Extra Content</h4>
<p>As a bonus tip, here are a couple of WinDbg breakpoints that can be used to dump each RCW as it&#8217;s created and destroyed.<br />
<code><br />
bu 79faa974 "dds @ecx L23; g"<br />
bu 79faa538 "dd @esp+20 L1; dds poi(@esp+20)+88 L1; g"<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/01/21/beware-of-using-stack-based-com-objects-from-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A WPF custom control in F#</title>
		<link>http://www.voyce.com/index.php/2009/12/14/a-wpf-custom-control-in-fsharp/</link>
		<comments>http://www.voyce.com/index.php/2009/12/14/a-wpf-custom-control-in-fsharp/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 11:05:02 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[guidattribute fsharp]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=459</guid>
		<description><![CDATA[What F# language and syntax features are required to implement a fundamentally object-oriented WPF custom control?]]></description>
			<content:encoded><![CDATA[<p>In the world of WPF with its powerful templating support, you&#8217;re much less likely to need to build a custom control from scratch than you are with legacy Windows GUI frameworks. For the vast majority of scenarios it&#8217;s possible to take an existing control and modify its appearance and behaviour to get what you need. However it is still possible and sometimes necessary to build something in code. The other day I was looking at creating one &#8211; using F# of course &#8211; and realised that a skeleton control serves as a good example of the kind of cross-paradigm features the language offers. They&#8217;re the kind of things that make it possible to use functional F# with inherently imperative .NET languages and frameworks like WPF.<br />
<span id="more-459"></span><br />
Let&#8217;s start by looking at the code for the control in its entirety, and then we&#8217;ll break it down bit-by-bit:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">public</span> MyControl<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
    <span style="color: #06c; font-weight: bold;">inherit</span> ItemsControl<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>defaultValue<span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">val</span> <span style="color: #06c; font-weight: bold;">mutable</span> FooProperty <span style="color: #000080;">:</span> DependencyProperty
&nbsp;
    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">member</span> OnFooChanged <span style="color: #000080;">&#40;</span>dob<span style="color: #000080;">:</span>DependencyObject<span style="color: #000080;">&#41;</span> args <span style="color: #000080;">=</span>
        <span style="color: #000080;">&#40;</span>dob <span style="color: #000080;">:</span>?<span style="color: #000080;">&gt;</span> MyControl<span style="color: #000080;">&#41;</span><span style="color: #000080;">.</span><span style="color: #505090;">Update</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>system<span style="color: #000080;">.</span><span style="color: #505090;">ComponentModel</span><span style="color: #000080;">.</span><span style="color: #505090;">Bindable</span><span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">true</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">member</span> <span style="color: #06c; font-weight: bold;">public</span> this<span style="color: #000080;">.</span><span style="color: #505090;">Foo</span>
        <span style="color: #06c; font-weight: bold;">with</span> get<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">:</span> string  <span style="color: #000080;">=</span> string <span style="color: #000080;">&#40;</span>base<span style="color: #000080;">.</span><span style="color: #505090;">GetValue</span><span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
        <span style="color: #06c; font-weight: bold;">and</span>  set<span style="color: #000080;">&#40;</span>r <span style="color: #000080;">:</span> string<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span> base<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span>, r<span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #06c; font-weight: bold;">override</span> this<span style="color: #000080;">.</span><span style="color: #505090;">OnPropertyChanged</span> <span style="color: #000080;">&#40;</span>args<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">match</span> args<span style="color: #000080;">.</span><span style="color: #505090;">Property</span><span style="color: #000080;">.</span><span style="color: #505090;">Name</span> <span style="color: #06c; font-weight: bold;">with</span>
        <span style="color: #000080;">|</span> <span style="color: #008080;">&quot;Foo&quot;</span> <span style="color: #000080;">-&gt;</span> this<span style="color: #000080;">.</span><span style="color: #505090;">Update</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
        <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">_</span>          <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #06c; font-weight: bold;">member</span> <span style="color: #06c; font-weight: bold;">internal</span> this<span style="color: #000080;">.</span><span style="color: #505090;">Update</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        System<span style="color: #000080;">.</span><span style="color: #505090;">Diagnostics</span><span style="color: #000080;">.</span><span style="color: #505090;">Debug</span><span style="color: #000080;">.</span><span style="color: #505090;">WriteLine</span> <span style="color: #000080;">&#40;</span>sprintf <span style="color: #008080;">&quot;Updating %A&quot;</span> <span style="color: #000080;">&#40;</span>base<span style="color: #000080;">.</span><span style="color: #505090;">GetValue</span><span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
&nbsp;
    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">do</span>
        <span style="color: #06c; font-weight: bold;">let</span> metadata <span style="color: #000080;">=</span> PropertyMetadata<span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">null</span>, PropertyChangedCallback <span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">OnFooChanged</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#41;</span>
        MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span> <span style="color: #000080;">&lt;-</span> DependencyProperty<span style="color: #000080;">.</span><span style="color: #505090;">Register</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Foo&quot;</span>, typeof<span style="color: #000080;">&lt;</span>string<span style="color: #000080;">&gt;</span>, typeof<span style="color: #000080;">&lt;</span>MyControl<span style="color: #000080;">&gt;</span>, metadata<span style="color: #000080;">&#41;</span></pre></div></div>

<h2>Constructor</h2>
<p>We don&#8217;t have one! Well, that&#8217;s not strictly true. There&#8217;s no per-instance set-up that we need to do here, so instead we have a default, parameter-less constructor implied by the &#8220;empty brackets&#8221; syntax in the type declaration. If we wanted to execute some code in the constructor, we could add the following:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">do</span>
        Debug<span style="color: #000080;">.</span><span style="color: #505090;">WriteLine</span> <span style="color: #008080;">&quot;Constructing.&quot;</span></pre></div></div>

<p>It&#8217;s also possible to add further constructors (perhaps parameterised differently) but when using WPF bear in mind that instances of your class will often be created from a XAML declaration, which generally uses the default constructor and then sets properties as required. Mutable objects: ug.</p>
<h2>Inheritance</h2>
<p>Our type derives from the WPF <code>ItemsControl</code> class using the <code>inherit</code> keyword. Of course, we&#8217;re still subject to the single-inheritance limit of .NET (not a bad thing, if you ask me &#8211; no more tortured object hierarchies):</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">public</span> MyControl<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
    <span style="color: #06c; font-weight: bold;">inherit</span> ItemsControl<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>Note that we have to include the empty brackets on the inherited type name, as this will be constructed implicitly when our derived class is constructed. We can access the inherited class from elsewhere in the code using the <code>base</code> keyword.</p>
<h2>Static members</h2>
<p>Dependency properties are a WPF construct that provide external storage of property values. They allow deep trees of objects to efficiently use lots of properties where they often have the default value, which is commonly the case in WPF. In order to use them with your class you have to do a few things, including creating a static value to hold the property and its metadata. We create a mutable static member for this:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #000080;">&#91;</span><span style="color: #000080;">&lt;</span>defaultValue<span style="color: #000080;">&gt;</span><span style="color: #000080;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">val</span> <span style="color: #06c; font-weight: bold;">mutable</span> FooProperty <span style="color: #000080;">:</span> DependencyProperty</pre></div></div>

<p>Why a mutable static value? If you&#8217;ve used F# already you might be aware that it&#8217;s also possible to declare an immutable static variable and its initial value in one shot with a <code>let</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">let</span> FooProperty <span style="color: #000080;">=</span> DependencyProperty<span style="color: #000080;">.</span><span style="color: #505090;">RegisterProperty</span> <span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Foo&quot;</span>, typeof<span style="color: #000080;">&lt;</span>string<span style="color: #000080;">&gt;</span>, typeof<span style="color: #000080;">&lt;</span>MyControl<span style="color: #000080;">&gt;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>Unfortunately, this results in your DP being private. Although the CLR property is still accessible, anything that attempts to access the DP directly &#8211; for instance, code within the WPF libraries &#8211; won&#8217;t see it. This means you have to use the mutable style, which is unfortunate.</p>
<h2>Static methods</h2>
<p>We&#8217;ve declared a static member function that is used to receive notifications when our DP is changed (although it&#8217;s complete overkill in this example, because we&#8217;ve already declared our DP with metadata that tells it to notify us when it changes):</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">member</span> OnFooChanged <span style="color: #000080;">&#40;</span>dob<span style="color: #000080;">:</span>DependencyObject<span style="color: #000080;">&#41;</span> args <span style="color: #000080;">=</span>
        <span style="color: #000080;">&#40;</span>dob <span style="color: #000080;">:</span>?<span style="color: #000080;">&gt;</span> MyControl<span style="color: #000080;">&#41;</span><span style="color: #000080;">.</span><span style="color: #505090;">Update</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>As you&#8217;d expect, there&#8217;s no <code>this</code> parameter on the signature, a static member doesn&#8217;t have any implicit object instance to work on. Luckily the arguments to most event functions include the DependencyObject that raised the notification. That means we can downcast dynamically to our expected type (with <code>: ?&gt;</code>) and use it. Bear in mind that this is more like casting than <code>as</code> in C#, as it will throw an <code>InvalidCastException</code> at runtime rather than returning null.</p>
<h2>Properties</h2>
<p>In order for our dependency property to be easily accessible we can expose it as a plain old CLR property. The implementation of the getter and setter simply defers all of the actual work of storing and retrieving the value to the underlying dependency property.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">member</span> <span style="color: #06c; font-weight: bold;">public</span> this<span style="color: #000080;">.</span><span style="color: #505090;">Foo</span>
        <span style="color: #06c; font-weight: bold;">with</span> get<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">:</span> string  <span style="color: #000080;">=</span> string <span style="color: #000080;">&#40;</span>base<span style="color: #000080;">.</span><span style="color: #505090;">GetValue</span><span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
        <span style="color: #06c; font-weight: bold;">and</span>  set<span style="color: #000080;">&#40;</span>r <span style="color: #000080;">:</span> string<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span> base<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">FooProperty</span>, r<span style="color: #000080;">&#41;</span></pre></div></div>

<p>Notice how we have to cast the <code>obj</code> returned from <code>GetValue</code> into the correct type. This is another example of having to bridge the gap between the dynamically typed WPF property system and F#&#8217;s static typing.</p>
<h2>Overridden members</h2>
<p>As well as providing new member functions and properties, we may need to override existing ones. Member functions marked <code>abstract</code> in the base class can be overridden using the <code>override</code> keyword:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">override</span> this<span style="color: #000080;">.</span><span style="color: #505090;">OnPropertyChanged</span> <span style="color: #000080;">&#40;</span>args<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
        <span style="color: #06c; font-weight: bold;">match</span> args<span style="color: #000080;">.</span><span style="color: #505090;">Property</span><span style="color: #000080;">.</span><span style="color: #505090;">Name</span> <span style="color: #06c; font-weight: bold;">with</span>
        <span style="color: #000080;">|</span> <span style="color: #008080;">&quot;Foo&quot;</span> <span style="color: #000080;">-&gt;</span> this<span style="color: #000080;">.</span><span style="color: #505090;">Update</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
        <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">_</span>          <span style="color: #000080;">-&gt;</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>The F# compiler provides the same kind of checking that the C# compiler does, warning you if you inadvertantly hide a base class function by creating an override with the same name but not marking it with <code>override</code>.</p>
<h2>Static constructor</h2>
<p>As mentioned before, we use the static constructor to initialise our mutable static variables. The syntax is similar to the <code>do</code> syntax of a normal constructor, with the addition of the <code>static</code> keyword:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">static</span> <span style="color: #06c; font-weight: bold;">do</span>
        <span style="color: #06c; font-weight: bold;">let</span> metadata <span style="color: #000080;">=</span> PropertyMetadata<span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">null</span>, PropertyChangedCallback <span style="color: #000080;">&#40;</span>MyControl<span style="color: #000080;">.</span><span style="color: #505090;">OnFooChanged</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#41;</span>
        <span style="color: #000080;">...</span></pre></div></div>

<p>Static constructors are run once per class, regardless of how many instances of the class you have. WPF relies quite heavily on static, class-based functionality; mostly because a lot of what&#8217;s set-up is per-class configuration &#8211; it&#8217;s not going to change during the lifetime of the application &#8211; so you may find yourself doing a fair amount of work in a static constructor. </p>
<p>So, there&#8217;s a quick run around some of the object-oriented features of the F# language: classes, inheritance, instance constructors, overridden member functions, static member functions and constructors. You can see how using WPF means you lose some of the benefits of the F# language; notably immutability and static typing. If you&#8217;re an experienced functional programmer getting deep into creating WPF or Silverlight custom controls you may find yourself using these OO constructs more than you&#8217;d like. Although F# makes it relatively painless in practice, mixing this heavily object oriented style of programming with a functional approach can still be a little hard to stomach at times.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/12/14/a-wpf-custom-control-in-fsharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Generating and plotting random numbers</title>
		<link>http://www.voyce.com/index.php/2009/11/24/generating-and-plotting-random-numbers/</link>
		<comments>http://www.voyce.com/index.php/2009/11/24/generating-and-plotting-random-numbers/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 23:44:55 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=562</guid>
		<description><![CDATA[An example of generating random numbers in F# and visualising their distribution using the WPF charting control.]]></description>
			<content:encoded><![CDATA[<p>For a while now I&#8217;ve been planning to write a blog post about pricing financial instruments using Monte Carlo techniques in F#. As part of this I needed to generate normally distributed random numbers, and while putting together the code to do it I realised it was interesting enough to warrant its own post.</p>
<p>I&#8217;m making use of a few F#/.NET idioms to make the process easier. For instance, sequences (.NET&#8217;s <code>IEnumerable</code>) are used as the source of uniformly distributed random numbers. Also, to verify that the resulting numbers are actually normally distributed, we can easily use existing WPF/silverlight controls to visualise the values direct from within Visual Studio, in a manner similar to <a href="http://www.voyce.com/index.php/2009/06/26/black-scholes-option-pricing-using-fsharp-and-wpf/">this previous post</a> &#8211; but without having to write the plotting code ourselves.<br />
<span id="more-562"></span></p>
<h3>Implementation</h3>
<p>So firstly, we create the random number stream:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> rr <span style="color: #000080;">=</span> System<span style="color: #000080;">.</span><span style="color: #505090;">Random</span><span style="color: #000080;">&#40;</span>System<span style="color: #000080;">.</span><span style="color: #505090;">DateTime</span><span style="color: #000080;">.</span><span style="color: #505090;">Now</span><span style="color: #000080;">.</span><span style="color: #505090;">Minute</span><span style="color: #000080;">&#41;</span>
<span style="color: #06c; font-weight: bold;">let</span> rands <span style="color: #000080;">=</span> seq <span style="color: #000080;">&#123;</span> <span style="color: #06c; font-weight: bold;">while</span> <span style="color: #06c; font-weight: bold;">true</span> <span style="color: #06c; font-weight: bold;">do</span> <span style="color: #06c; font-weight: bold;">yield</span> rr<span style="color: #000080;">.</span><span style="color: #505090;">NextDouble</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#125;</span></pre></div></div>

<p>As you can see <code>rands</code> is an infinite sequence. As such, you should be wary of the &#8220;eager&#8221; functions from the Seq module that attempt to consume the entire sequence at once, they&#8217;ll obviously cause a problem here. Also notice that I&#8217;ve picked a somewhat dubious seed for the random number generator, as this is only for demonstration purposes.</p>
<p>In order to obtain normally distributed random numbers I&#8217;m using the <a href="http://en.wikipedia.org/wiki/Box–Muller_transform">Box-Muller</a> transform. I started off with an implementation transcribed from VBA (from <a href="http://www.amazon.com/gp/product/0470319585?ie=UTF8&#038;tag=wwwvoycecom-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0470319585">Wilmott</a><img src="http://www.assoc-amazon.com/e/ir?t=wwwvoycecom-20&#038;l=as2&#038;o=1&#038;a=0470319585" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> et al) &#8211; yes, yes, I know &#8211; but of course this used mutable references. Not nice. So I reworked it a little to use <code>Seq.pick</code>, which takes items from the sequence while a predicate returns <code>None</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> boxMuller <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span>
    <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #000080;">&#40;</span>x,dist<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span> 
        rands
        <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">pick</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> x <span style="color: #000080;">-&gt;</span>
            <span style="color: #06c; font-weight: bold;">let</span> x <span style="color: #000080;">=</span> <span style="color: #c6c;">2.0</span> <span style="color: #000080;">*</span> x <span style="color: #000080;">-</span> <span style="color: #c6c;">1.0</span>
            <span style="color: #06c; font-weight: bold;">let</span> y <span style="color: #000080;">=</span> <span style="color: #c6c;">2.0</span> <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#40;</span>Seq<span style="color: #000080;">.</span><span style="color: #505090;">take</span> <span style="color: #c6c;">1</span> rands<span style="color: #000080;">&#41;</span> <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">hd</span><span style="color: #000080;">&#41;</span> <span style="color: #000080;">-</span> <span style="color: #c6c;">1.0</span>
            <span style="color: #06c; font-weight: bold;">match</span> <span style="color: #000080;">&#40;</span>x <span style="color: #000080;">*</span> x <span style="color: #000080;">+</span> y <span style="color: #000080;">*</span> y<span style="color: #000080;">&#41;</span> <span style="color: #06c; font-weight: bold;">with</span>
                <span style="color: #000080;">|</span> dist <span style="color: #06c; font-weight: bold;">when</span> dist <span style="color: #000080;">&lt;</span> <span style="color: #c6c;">1.0</span> <span style="color: #000080;">-&gt;</span> Some <span style="color: #000080;">&#40;</span>x,dist<span style="color: #000080;">&#41;</span>
                <span style="color: #000080;">|</span> dist <span style="color: #000080;">-&gt;</span> None
            <span style="color: #000080;">&#41;</span> 
    x <span style="color: #000080;">*</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Sqrt</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">-</span><span style="color: #c6c;">2.0</span> <span style="color: #000080;">*</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Log</span><span style="color: #000080;">&#40;</span>dist<span style="color: #000080;">&#41;</span> <span style="color: #000080;">/</span> dist<span style="color: #000080;">&#41;</span></pre></div></div>

<p>It&#8217;s not particularly efficient as we&#8217;re consuming two uniform numbers to generate one normal one &#8211; hence the additional Seq.take within the pick. Of course we could change the function to return the 2 generated numbers as an extra element in the tuple.</p>
<p>Next, let&#8217;s generate some numbers, and get them in a suitable form to display:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> makeData <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span>
    Seq<span style="color: #000080;">.</span><span style="color: #505090;">init</span> <span style="color: #c6c;">100000</span> boxMuller
    <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">countBy</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> d <span style="color: #000080;">-&gt;</span> 
        <span style="color: #06c; font-weight: bold;">let</span> d <span style="color: #000080;">=</span> decimal d
        Math<span style="color: #000080;">.</span><span style="color: #505090;">Round</span><span style="color: #000080;">&#40;</span>d, <span style="color: #c6c;">1</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #000080;">|&gt;</span> Seq<span style="color: #000080;">.</span><span style="color: #505090;">sortBy</span> fst</pre></div></div>

<p>We initialise a sequence with an arbitrary amount of numbers (100000, enough to get a good distribution, hopefully), then use <code>Seq.countBy</code> to do a naive grouping that allows us to see how the numbers are distributed, i.e. counting how many numbers fit in each 0.10 bucket. We then sort the output by bucket. </p>
<h3>Visualisation</h3>
<p>Now we can display what we&#8217;ve got. We can create a simple WPF object-model using imperative code, including the very useful chart control from the WpfToolkit. The chart control enables us to add a series and set our <code>seq&lt;decimal * float&gt;</code> directly as the series ItemsSource, which is the standard way to specify the items for a collection control. If you specify the tuple <code>Item1</code> and <code>Item2</code> properties for the bindings, WPF will be able to access the data from each element, and that&#8217;s all you need.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> series <span style="color: #000080;">=</span> 
        ColumnSeries<span style="color: #000080;">&#40;</span>
            IndependentValueBinding <span style="color: #000080;">=</span> Data<span style="color: #000080;">.</span><span style="color: #505090;">Binding</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Item1&quot;</span><span style="color: #000080;">&#41;</span>,
            DependentValueBinding <span style="color: #000080;">=</span> Data<span style="color: #000080;">.</span><span style="color: #505090;">Binding</span><span style="color: #000080;">&#40;</span><span style="color: #008080;">&quot;Item2&quot;</span><span style="color: #000080;">&#41;</span>,
            ItemsSource <span style="color: #000080;">=</span> makeData <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> chart <span style="color: #000080;">=</span> Chart<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    chart<span style="color: #000080;">.</span><span style="color: #505090;">Series</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> series
    Window<span style="color: #000080;">&#40;</span>
        Name<span style="color: #000080;">=</span><span style="color: #008080;">&quot;Plot&quot;</span>,
        Title<span style="color: #000080;">=</span><span style="color: #008080;">&quot;Normally distributed random numbers&quot;</span>,
        Width<span style="color: #000080;">=</span><span style="color: #c6c;">900.0</span>,
        Height<span style="color: #000080;">=</span><span style="color: #c6c;">700.0</span>,
        Content<span style="color: #000080;">=</span>chart,
        Visibility<span style="color: #000080;">=</span>Visibility<span style="color: #000080;">.</span><span style="color: #505090;">Visible</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>Here&#8217;s the resulting output:<br />
<img src="http://www.voyce.com/wp-content/uploads/2009/11/dist-300x233.png" alt="dist" title="dist" width="300" height="233" class="alignleft size-medium wp-image-576" />As I&#8217;ve mentioned before, this is a fantastically immediate way of doing numerical development in Visual Studio. You can enter all of this code directly into F# interactive within VS, iterate, and quickly see the effect that your changes have. It&#8217;s just as interactive as using the graph features in Excel, and the resulting code is much more easily reusable.</p>
<p><span style="visibility:hidden"> XD5RRV3XDNHN </span><br />
<script type="text/javascript" src="http://www.assoc-amazon.com/s/link-enhancer?tag=wwwvoycecom-20&#038;o=1">
</script><br />
<noscript><br />
    <img src="http://www.assoc-amazon.com/s/noscript?tag=wwwvoycecom-20" alt="" /><br />
</noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/11/24/generating-and-plotting-random-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FormatException in WPF DataBinding</title>
		<link>http://www.voyce.com/index.php/2009/10/14/formatexception-in-wpf-databinding/</link>
		<comments>http://www.voyce.com/index.php/2009/10/14/formatexception-in-wpf-databinding/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 11:09:26 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[DataBinding]]></category>
		<category><![CDATA[FormatException]]></category>
		<category><![CDATA[visualstudio]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=446</guid>
		<description><![CDATA[A FormatException is generated by the WPF DataBinding diagnostics if the original exception text contains curly brackets.]]></description>
			<content:encoded><![CDATA[<p>While working on some F#/C# WPF code the other day, I kept hitting a fatal FormatException when running under the debugger. Annoyingly, the app would quit with:<br />
<code><br />
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll<br />
Additional information: Input string was not in a correct format.<br />
</code><br />
But it worked fine when started from Expression Blend, or when run using Start Without Debugging in Visual Studio. Let&#8217;s take a closer look&#8230;<br />
<span id="more-446"></span><br />
Looking at the output window, there seemed to be an intial exception before the FormatException, and from the stack trace the second one seemed to be generated as WPF was trying to log the first one:</p>
<p><a href="http://72.47.193.211/wp-content/uploads/2009/10/callstack.png"><img src="http://www.voyce.com/wp-content/uploads/2009/10/callstack-300x113.png" alt="callstack" title="callstack" width="300" height="113" class="size-medium wp-image-449" /></a></p>
<p>I had a look at the text of the first exception, and from that it was obvious:</p>
<p><code><br />
Unable to cast COM object of type 'System.__ComObject' to interface type 'IWhatever'. This operation failed because the QueryInterface call on the COM component for the interface with IID '<b>{</b>CAD939D0-5E5D-11D7-AA0B-0002B33FE9DX<b>}</b>' failed due to the following error: Bad variable type. (Exception from HRESULT: 0x80020008 (DISP_E_BADVARTYPE)).<br />
</code></p>
<p>The message contains curly brackets around the IID, and they&#8217;re being intrepreted as insertion points by a call to String.Format!</p>
<h2>Workaround</h2>
<p>So that explained why it only happens in debugger runs; as <a href="http://blogs.msdn.com/mikehillberg/archive/2006/09/14/WpfTraceSources.aspx">this post</a> helpfully points out the WPF databinding is enabled by default in that case. To workaround it, you can disable logging programmatically or using the App.config file to only display <code>Critical</code> output. So if your app is named foo.exe, create a file foo.exe.config that contains:</p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">configuration</span><span style="color: blue;">&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">&nbsp; &lt;</span><span style="color: #a31515;">system.diagnostics</span><span style="color: blue;">&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;</span><span style="color: #a31515;">sources</span><span style="color: blue;">&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span style="color: #a31515;">source</span><span style="color: blue;"> </span><span style="color: red;">name</span><span style="color: blue;">=</span>"<span style="color: blue;">System.Windows.Data</span>"<span style="color: blue;"> </span><span style="color: red;">switchName</span><span style="color: blue;">=</span>"<span style="color: blue;">SourceSwitch</span>"<span style="color: blue;">/&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;/</span><span style="color: #a31515;">sources</span><span style="color: blue;">&gt;</span></pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;</span><span style="color: #a31515;">switches</span><span style="color: blue;">&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &nbsp; &lt;</span><span style="color: #a31515;">add</span><span style="color: blue;"> </span><span style="color: red;">name</span><span style="color: blue;">=</span>"<span style="color: blue;">SourceSwitch</span>"<span style="color: blue;"> </span><span style="color: red;">value</span><span style="color: blue;">=</span>"<span style="color: blue;">Critical</span>"<span style="color: blue;"> /&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">&nbsp; &nbsp; &lt;/</span><span style="color: #a31515;">switches</span><span style="color: blue;">&gt;</span></pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;"><span style="color: blue;">&nbsp; &lt;/</span><span style="color: #a31515;">system.diagnostics</span><span style="color: blue;">&gt;</span></pre>
<pre style="margin: 0px;"><span style="color: blue;">&lt;/</span><span style="color: #a31515;">configuration</span><span style="color: blue;">&gt;</span></pre>
</div>
<h2>Fix&#8230;?</h2>
<p>Hopefully there&#8217;ll be a fix for this at some point soon, as disabling the logging is a pretty large hammer to crack this small nut.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/10/14/formatexception-in-wpf-databinding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting IUnknown from __ComObject</title>
		<link>http://www.voyce.com/index.php/2009/09/03/getting-iunknown-from-__comobject/</link>
		<comments>http://www.voyce.com/index.php/2009/09/03/getting-iunknown-from-__comobject/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 22:51:35 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WinDbg]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[mscorwks]]></category>
		<category><![CDATA[RCW]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=330</guid>
		<description><![CDATA[How do you find the unmanaged COM object that's being referenced by a .NET object?]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working in an environment with a lot of mixed managed (F#) and unmanaged (C++ COM) code. One of the big problems with this is the mix of lifetime management techniques; .NET uses garbage collection while COM relies on reference counting. Furthermore .NET garbage collection is somewhat non-deterministic, which adds further complexity.</p>
<p>So quite often in our mixed code-base, we find that the .NET garbage collection process doesn&#8217;t kick in when we need it to. For instance, when we&#8217;ve allocated a lot of memory in the COM code that .NET isn&#8217;t aware of. Memory exhaustion has to get pretty bad for the GC to occur at any other time than during a .NET allocation, either the system-wide low-memory event has to be signalled or an <code>OutOfMemoryException</code> needs to be thrown. In both of these cases it&#8217;s probably too late to do anything about it.</p>
<p>In this case it&#8217;s extremely useful to be able to see what .NET objects are still alive, and what COM objects they&#8217;re hanging on to. Unfortunately this isn&#8217;t as easy as it might seem.<br />
<span id="more-330"></span><br />
The COM object itself hides within a weakly-typed <code>System.__ComObject</code> or a strongly-typed managed wrapper, depending on whether rich type information is available. Furthermore, a runtime controller RCW (runtime callable wrapper) is what actually holds a pointer to the object itself, and this structure is internal to mscorwks.dll.</p>
<p>So how can we untangle this and, on finding a <code>__ComObject</code> that happens to still be alive (i.e. is not reachable in the object graph and is therefore eligible for garbage collection) identify which COM object it&#8217;s hanging on to.</p>
<p>First of all, let&#8217;s see how many <code>__ComObjects</code> are still alive. In this case, it&#8217;s only one (phew!):</p>
<pre>
0:005> !DumpHeap -type __ComObject
 Address       MT     Size
01453b74 79306e60       16
total 1 objects
Statistics:
      MT    Count    TotalSize Class Name
79306e60        1           16 System.__ComObject
Total 1 objects
</pre>
<p>And you remember the layout of .NET objects in memory, don&#8217;t you? Of course you do! The 4 bytes prior to the address displayed (<code>01453b74</code>) are the &#8220;object header&#8221;. The exact content of the header is apparently undocumented. Let&#8217;s see what it contains (at least on a 32-bit platform, your mileage may vary):</p>
<pre>
0:005> dd 01453b74-4 L1
01453b70  08000002
</pre>
<p>According to various sources the object header contains 2 fields; a handle and a sync block index. If the object is an RCW, the handle is always 0&#215;08000. You can use the index with SOS&#8217;s <code>!syncblk</code> command to de-reference it:</p>
<pre>
0:005> !syncblk 2
Index SyncBlock MonitorHeld Recursion Owning Thread Info  SyncBlock Owner
    2 001e0fec            0         0 00000000     none    01453b74 System.__ComObject
-----------------------------
Total           3
CCW             0
RCW             1
ComClassFactory 0
Free            0
</pre>
<p>The sync block itself is an undocumented structure, but after a bit of investigation, it turns out that at offset 0&#215;1c there is a pointer to a further structure that contains the &#8220;interop information&#8221;:</p>
<pre>
0:005> dd 001e0fec+1c L1
001e1008  001e9510
</pre>
<p>And from this, we can obtain a pointer to the RCW itself. We&#8217;re almost there!</p>
<pre>
0:005> dd 001e9510+c L1
001e951c  001e5380
</pre>
<p>The RCW is a pretty large structure, but for our purposes there are only a couple of interesting fields: the IUnknown pointer at 0&#215;64, and the object&#8217;s virtual function table pointer at 0&#215;88. If you use <code>dds</code> you can easily see any symbols associated with these pointers:</p>
<pre>
0:005> dds 01e5380+64 L1
001e53e4  00ef6c24
</pre>
<pre>
0:005> dds 01e5380+88 L1
001e5408  00eb9710 rcwrepro!ATL::CComObject<ctestObject>::`vftable'
</pre>
<p>This is the salient information; we now know exactly what type of COM object we&#8217;re dealing with. This is obviously a bit fragile, given that it relies on structures from mscorwks that may well change in newer versions of the runtime (I&#8217;ll check on .NET 4 when I get a chance). It&#8217;s also a bit of a pain to go through all these steps manually in WinDbg, so I put together a simple extension DLL to do it automatically given the address of the __ComObject. I&#8217;ll upload that and blog about it soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/09/03/getting-iunknown-from-__comobject/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Visualising Black-Scholes option pricing using F# and WPF</title>
		<link>http://www.voyce.com/index.php/2009/06/26/black-scholes-option-pricing-using-fsharp-and-wpf/</link>
		<comments>http://www.voyce.com/index.php/2009/06/26/black-scholes-option-pricing-using-fsharp-and-wpf/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 16:17:10 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=173</guid>
		<description><![CDATA[Using F# to create simple plots of Black-Scholes option prices and greeks using WPF.]]></description>
			<content:encoded><![CDATA[<p>The other day I was looking for an example of some code relevant to finance that I could use as a test for experimenting with Windows Presentation Foundation (WPF) and F#. I decided I could use a simple Black-Scholes option pricer combined with WPF to easily visualise how the option inputs affect the value and greeks. For example, given all the usual Black-Scholes assumptions, and a non-zero interest rate, you&#8217;d expect the value of an at-the-money call option to increase as time to expiry increases, whereas a put option would decrease in value.</p>
<h3>Calculating option values using F#</h3>
<p>The first thing you need is an approximation to the cumulative normal distribution. I used the Abromowitz and Stegun approximation, which should give us enough precision. It&#8217;s fairly concise to implement in F#:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> ncdf x <span style="color: #000080;">=</span>
  <span style="color: #06c; font-weight: bold;">let</span> b1 <span style="color: #000080;">=</span>  <span style="color: #c6c;">0.319381530</span>
  <span style="color: #06c; font-weight: bold;">let</span> b2 <span style="color: #000080;">=</span> <span style="color: #000080;">-</span><span style="color: #c6c;">0.356563782</span>
  <span style="color: #06c; font-weight: bold;">let</span> b3 <span style="color: #000080;">=</span>  <span style="color: #c6c;">1.781477937</span>
  <span style="color: #06c; font-weight: bold;">let</span> b4 <span style="color: #000080;">=</span> <span style="color: #000080;">-</span><span style="color: #c6c;">1.821255978</span>
  <span style="color: #06c; font-weight: bold;">let</span> b5 <span style="color: #000080;">=</span>  <span style="color: #c6c;">1.330274429</span>
  <span style="color: #06c; font-weight: bold;">let</span> p  <span style="color: #000080;">=</span>  <span style="color: #c6c;">0.2316419</span>
  <span style="color: #06c; font-weight: bold;">let</span> c  <span style="color: #000080;">=</span>  <span style="color: #c6c;">0.39894228</span>
  <span style="color: #06c; font-weight: bold;">match</span> x <span style="color: #06c; font-weight: bold;">with</span>
  <span style="color: #000080;">|</span> x <span style="color: #06c; font-weight: bold;">when</span> x <span style="color: #000080;">&gt;=</span> <span style="color: #c6c;">0.0</span> <span style="color: #000080;">-&gt;</span>
    <span style="color: #06c; font-weight: bold;">let</span> t <span style="color: #000080;">=</span> <span style="color: #c6c;">1.0</span> <span style="color: #000080;">/</span> <span style="color: #000080;">&#40;</span><span style="color: #c6c;">1.0</span> <span style="color: #000080;">+</span> p <span style="color: #000080;">*</span> x<span style="color: #000080;">&#41;</span>
    <span style="color: #000080;">&#40;</span><span style="color: #c6c;">1.0</span> <span style="color: #000080;">-</span> c <span style="color: #000080;">*</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Exp</span><span style="color: #000080;">&#40;</span> <span style="color: #000080;">-</span>x <span style="color: #000080;">*</span> x <span style="color: #000080;">/</span> <span style="color: #c6c;">2.0</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">*</span> t <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span>t<span style="color: #000080;">*</span><span style="color: #000080;">&#40;</span>t<span style="color: #000080;">*</span><span style="color: #000080;">&#40;</span>t<span style="color: #000080;">*</span><span style="color: #000080;">&#40;</span>t<span style="color: #000080;">*</span>b5<span style="color: #000080;">+</span>b4<span style="color: #000080;">&#41;</span><span style="color: #000080;">+</span>b3<span style="color: #000080;">&#41;</span><span style="color: #000080;">+</span>b2<span style="color: #000080;">&#41;</span><span style="color: #000080;">+</span>b1<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
  <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">-&gt;</span>
    <span style="color: #06c; font-weight: bold;">let</span> t <span style="color: #000080;">=</span> <span style="color: #c6c;">1.0</span> <span style="color: #000080;">/</span> <span style="color: #000080;">&#40;</span><span style="color: #c6c;">1.0</span> <span style="color: #000080;">-</span> p <span style="color: #000080;">*</span> x<span style="color: #000080;">&#41;</span>
    <span style="color: #000080;">&#40;</span>c <span style="color: #000080;">*</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Exp</span><span style="color: #000080;">&#40;</span> <span style="color: #000080;">-</span>x <span style="color: #000080;">*</span> x <span style="color: #000080;">/</span> <span style="color: #c6c;">2.0</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">*</span> t <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span>t<span style="color: #000080;">*</span><span style="color: #000080;">&#40;</span>t<span style="color: #000080;">*</span><span style="color: #000080;">&#40;</span>t<span style="color: #000080;">*</span><span style="color: #000080;">&#40;</span>t<span style="color: #000080;">*</span>b5<span style="color: #000080;">+</span>b4<span style="color: #000080;">&#41;</span><span style="color: #000080;">+</span>b3<span style="color: #000080;">&#41;</span><span style="color: #000080;">+</span>b2<span style="color: #000080;">&#41;</span><span style="color: #000080;">+</span>b1<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>The CDF should be near 0 for low values, around 0.5 for zero, and near 1 for high values. Let&#8217;s check:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #000080;">&gt;</span> <span style="color: #000080;">&#91;</span><span style="color: #000080;">-</span><span style="color: #c6c;">5.0</span><span style="color: #000080;">;</span> <span style="color: #c6c;">0.0</span><span style="color: #000080;">;</span> <span style="color: #c6c;">5.0</span><span style="color: #000080;">&#93;</span> <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">map</span> ncdf<span style="color: #000080;">;;</span>
<span style="color: #06c; font-weight: bold;">val</span> it <span style="color: #000080;">:</span> float list <span style="color: #000080;">=</span> <span style="color: #000080;">&#91;</span>2<span style="color: #000080;">.</span>871049992e<span style="color: #000080;">-</span>07<span style="color: #000080;">;</span> <span style="color: #c6c;">0.500000001</span><span style="color: #000080;">;</span> <span style="color: #c6c;">0.9999997129</span><span style="color: #000080;">&#93;</span></pre></div></div>

<p>Looks good.</p>
<p>Now let&#8217;s put it to use by implementing the option pricing formula for call options:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> call strike spot <span style="color: #000080;">&#40;</span>rate<span style="color: #000080;">:</span>float<span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#40;</span>now<span style="color: #000080;">:</span>float<span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#40;</span>expiry<span style="color: #000080;">:</span>float<span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#40;</span>vol<span style="color: #000080;">:</span>float<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
    <span style="color: #06c; font-weight: bold;">let</span> exp <span style="color: #000080;">=</span> expiry<span style="color: #000080;">-</span>now
    <span style="color: #06c; font-weight: bold;">let</span> d1 <span style="color: #000080;">=</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Log</span><span style="color: #000080;">&#40;</span>spot<span style="color: #000080;">/</span>strike<span style="color: #000080;">&#41;</span> <span style="color: #000080;">+</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#40;</span>rate<span style="color: #000080;">+</span><span style="color: #000080;">&#40;</span>vol<span style="color: #000080;">*</span>vol<span style="color: #000080;">&#41;</span><span style="color: #000080;">/</span><span style="color: #c6c;">2.0</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">*</span>exp<span style="color: #000080;">&#41;</span><span style="color: #000080;">/</span><span style="color: #000080;">&#40;</span>vol <span style="color: #000080;">*</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Sqrt</span><span style="color: #000080;">&#40;</span>exp<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> d2 <span style="color: #000080;">=</span> d1 <span style="color: #000080;">-</span> <span style="color: #000080;">&#40;</span>vol <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span>Math<span style="color: #000080;">.</span><span style="color: #505090;">Sqrt</span><span style="color: #000080;">&#40;</span>exp<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #000080;">&#40;</span>spot <span style="color: #000080;">*</span> ncdf d1<span style="color: #000080;">&#41;</span> <span style="color: #000080;">-</span> <span style="color: #000080;">&#40;</span>strike <span style="color: #000080;">*</span> Math<span style="color: #000080;">.</span><span style="color: #505090;">Pow</span><span style="color: #000080;">&#40;</span>Math<span style="color: #000080;">.</span><span style="color: #505090;">E</span>, <span style="color: #000080;">-</span>rate<span style="color: #000080;">*</span>exp<span style="color: #000080;">&#41;</span><span style="color: #000080;">*</span><span style="color: #000080;">&#40;</span>ncdf d2<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>, ncdf d1</pre></div></div>

<p>Notice that the function returns a tuple of (value,delta). Give that the greeks are available analytically we may as well return them at the same time as the value.</p>
<p>We can poke this a bit to check that it&#8217;s doing the right thing. A call option that&#8217;s way in-the-money (i.e. spot > strike) near to expiry, has a lot of intrinsic value:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #000080;">&gt;</span> call <span style="color: #c6c;">10.0</span> <span style="color: #c6c;">100.0</span> <span style="color: #c6c;">0.0</span> <span style="color: #c6c;">0.0</span> <span style="color: #c6c;">0.1</span> <span style="color: #c6c;">0.5</span><span style="color: #000080;">;;</span>
<span style="color: #06c; font-weight: bold;">val</span> it <span style="color: #000080;">:</span> float <span style="color: #000080;">*</span> float <span style="color: #000080;">=</span> <span style="color: #000080;">&#40;</span><span style="color: #c6c;">89.26911958</span>, <span style="color: #c6c;">0.9913821898</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>An at-the-money call option should have a delta close to 0.5 at expiry:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #000080;">&gt;</span> call <span style="color: #c6c;">10.0</span> <span style="color: #c6c;">10.0</span> <span style="color: #c6c;">0.0</span> <span style="color: #c6c;">0.0</span> <span style="color: #c6c;">0.1</span> <span style="color: #c6c;">0.5</span><span style="color: #000080;">;;</span>
<span style="color: #06c; font-weight: bold;">val</span> it <span style="color: #000080;">:</span> float <span style="color: #000080;">*</span> float <span style="color: #000080;">=</span> <span style="color: #000080;">&#40;</span><span style="color: #c6c;">0.6301280626</span>, <span style="color: #c6c;">0.5315064031</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>All seems fine.</p>
<p>So lets see what we can do about visualising these relationships.</p>
<h3>Using WPF with F#</h3>
<p>You&#8217;d be forgiven for thinking that the XAML markup language is the only way to construct user interfaces in WPF. Indeed, if you want to avoid writing code it&#8217;s the way to go. But unfortunately it&#8217;s not possible to use F# as the code-behind XAML files, so you&#8217;re forced to use C#. And it&#8217;s also not as dynamic or immediate as it could be; involving the usual write, compile, run iteration. We can do better in F# using scripts and F# interactive (FSI).</p>
<p>The key is to construct the WPF object model imperatively, rather than declaratively with XAML. Yeah, I know this is normally the opposite of what you&#8217;d want to do.</p>
<p>For instance, here&#8217;s some code to create a Canvas. Note the use of a construction expression to both create the object and set some of it&#8217;s properties. This is just syntactic sugar which helps to make the object </i>look</i> slightly less mutable than it actually is:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> c <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">new</span> Canvas<span style="color: #000080;">&#40;</span>Name<span style="color: #000080;">=</span><span style="color: #008080;">&quot;Canvas&quot;</span>, Width<span style="color: #000080;">=</span><span style="color: #c6c;">250.0</span>, Height<span style="color: #000080;">=</span><span style="color: #c6c;">250.0</span><span style="color: #000080;">&#41;</span>
    c<span style="color: #000080;">.</span><span style="color: #505090;">Background</span> <span style="color: #000080;">&lt;-</span> SolidColorBrush<span style="color: #000080;">&#40;</span>Color<span style="color: #000080;">.</span><span style="color: #505090;">FromRgb</span><span style="color: #000080;">&#40;</span>228uy,228uy,228uy<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>We can use the WPF canvas panel to enable us to explicitly place points (or rather, Rectangles) on our plot, it uses absolute locations rather than the implied flow layout of the other containers (Grid, StackPanel etc). Putting this together, we can write a function which will take a parent Panel, and a list of (x,y) tuples and create a plot:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> plot <span style="color: #000080;">&#40;</span>panel<span style="color: #000080;">:</span>Panel<span style="color: #000080;">&#41;</span> <span style="color: #000080;">&#40;</span>pts<span style="color: #000080;">:</span><span style="color: #000080;">&#40;</span>double <span style="color: #000080;">*</span> double<span style="color: #000080;">&#41;</span> list<span style="color: #000080;">&#41;</span> <span style="color: #000080;">=</span>
    <span style="color: #06c; font-weight: bold;">let</span> bgc <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">new</span> Canvas<span style="color: #000080;">&#40;</span>Name<span style="color: #000080;">=</span><span style="color: #008080;">&quot;Canvas&quot;</span>, Width<span style="color: #000080;">=</span><span style="color: #c6c;">300.0</span>, Height<span style="color: #000080;">=</span><span style="color: #c6c;">300.0</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> c <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">new</span> Canvas<span style="color: #000080;">&#40;</span>Name<span style="color: #000080;">=</span><span style="color: #008080;">&quot;Canvas&quot;</span>, Width<span style="color: #000080;">=</span><span style="color: #c6c;">250.0</span>, Height<span style="color: #000080;">=</span><span style="color: #c6c;">250.0</span><span style="color: #000080;">&#41;</span>
    c<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span>Canvas<span style="color: #000080;">.</span><span style="color: #505090;">LeftProperty</span>, <span style="color: #c6c;">25.0</span><span style="color: #000080;">&#41;</span>
    c<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span>Canvas<span style="color: #000080;">.</span><span style="color: #505090;">TopProperty</span>, <span style="color: #c6c;">25.0</span><span style="color: #000080;">&#41;</span>
    c<span style="color: #000080;">.</span><span style="color: #505090;">Background</span> <span style="color: #000080;">&lt;-</span> SolidColorBrush<span style="color: #000080;">&#40;</span>Color<span style="color: #000080;">.</span><span style="color: #505090;">FromRgb</span><span style="color: #000080;">&#40;</span>228uy,228uy,228uy<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> x,y <span style="color: #000080;">=</span> pts <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">unzip</span>
    <span style="color: #06c; font-weight: bold;">let</span> xmin,xmax <span style="color: #000080;">=</span> x <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">min</span>, x <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">max</span>
    <span style="color: #06c; font-weight: bold;">let</span> ymin,ymax <span style="color: #000080;">=</span> y <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">min</span>, y <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">max</span>
    <span style="color: #06c; font-weight: bold;">let</span> xscale <span style="color: #000080;">=</span> c<span style="color: #000080;">.</span><span style="color: #505090;">Width</span> <span style="color: #000080;">/</span> <span style="color: #000080;">&#40;</span>xmax<span style="color: #000080;">-</span>xmin<span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> yscale <span style="color: #000080;">=</span> c<span style="color: #000080;">.</span><span style="color: #505090;">Height</span> <span style="color: #000080;">/</span> <span style="color: #000080;">&#40;</span>ymax<span style="color: #000080;">-</span>ymin<span style="color: #000080;">&#41;</span>
    pts
    <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">map</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> pt <span style="color: #000080;">-&gt;</span>
        <span style="color: #06c; font-weight: bold;">let</span> p <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">new</span> Rectangle<span style="color: #000080;">&#40;</span>Width<span style="color: #000080;">=</span><span style="color: #c6c;">2.0</span>,Height<span style="color: #000080;">=</span><span style="color: #c6c;">2.0</span><span style="color: #000080;">&#41;</span>
        p<span style="color: #000080;">.</span><span style="color: #505090;">Stroke</span> <span style="color: #000080;">&lt;-</span> <span style="color: #06c; font-weight: bold;">new</span> SolidColorBrush<span style="color: #000080;">&#40;</span>Color<span style="color: #000080;">.</span><span style="color: #505090;">FromRgb</span><span style="color: #000080;">&#40;</span>0uy,0uy,0uy<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
        p<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span> Canvas<span style="color: #000080;">.</span><span style="color: #505090;">LeftProperty</span>, <span style="color: #000080;">&#40;</span>fst pt <span style="color: #000080;">-</span> xmin<span style="color: #000080;">&#41;</span> <span style="color: #000080;">*</span> xscale<span style="color: #000080;">&#41;</span>
        p<span style="color: #000080;">.</span><span style="color: #505090;">SetValue</span><span style="color: #000080;">&#40;</span> Canvas<span style="color: #000080;">.</span><span style="color: #505090;">TopProperty</span>, c<span style="color: #000080;">.</span><span style="color: #505090;">Height</span> <span style="color: #000080;">-</span> <span style="color: #000080;">&#40;</span>snd pt <span style="color: #000080;">-</span> ymin<span style="color: #000080;">&#41;</span> <span style="color: #000080;">*</span> yscale<span style="color: #000080;">&#41;</span>
        p
        <span style="color: #000080;">&#41;</span>
    <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">iter</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> rect <span style="color: #000080;">-&gt;</span>
        ignore <span style="color: #000080;">&lt;|</span> c<span style="color: #000080;">.</span><span style="color: #505090;">Children</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> rect<span style="color: #000080;">&#41;</span>
    ignore <span style="color: #000080;">&lt;|</span> bgc<span style="color: #000080;">.</span><span style="color: #505090;">Children</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> <span style="color: #000080;">&#40;</span>fst <span style="color: #000080;">&#40;</span>makeYScale ymin ymax<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    ignore <span style="color: #000080;">&lt;|</span> bgc<span style="color: #000080;">.</span><span style="color: #505090;">Children</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> <span style="color: #000080;">&#40;</span>fst <span style="color: #000080;">&#40;</span>makeXScale xmin xmax<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    ignore <span style="color: #000080;">&lt;|</span> bgc<span style="color: #000080;">.</span><span style="color: #505090;">Children</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> c
    ignore <span style="color: #000080;">&lt;|</span> panel<span style="color: #000080;">.</span><span style="color: #505090;">Children</span><span style="color: #000080;">.</span><span style="color: #505090;">Add</span> bgc
    <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>The function returns nothing (unit in F# parlance) and performs a side-effecting modify of the passed Panel. I&#8217;ve omitted the makeXScale and makeYScale functions, as they&#8217;re a bit gnarly, and don&#8217;t really serve to demonstrate anything in particular.</p>
<p>Now we need to create some data to plot. We can do this in many ways, but one thing I looked at was creating a set of call option values with varying time to expiry. I thought this could use a floating point sequence, but it generated a deprecation warning, so I decided to do it long hand instead. This function returns a list of (time,value) tuples, where time range from <code>rfrom</code> to <code>rto</code> in </code>num</code> steps and value is calculated using the passed function <code>f</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> varyExpiry f num rfrom rto <span style="color: #000080;">=</span>
    List<span style="color: #000080;">.</span><span style="color: #505090;">init</span> num <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> n <span style="color: #000080;">-&gt;</span>
        <span style="color: #06c; font-weight: bold;">let</span> s <span style="color: #000080;">=</span> rfrom <span style="color: #000080;">+</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#40;</span>float n<span style="color: #000080;">/</span>float num<span style="color: #000080;">&#41;</span> <span style="color: #000080;">*</span> <span style="color: #000080;">&#40;</span>rto<span style="color: #000080;">-</span>rfrom<span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
        float s, fst <span style="color: #000080;">&lt;|</span> f <span style="color: #c6c;">10.0</span> <span style="color: #c6c;">10.0</span> <span style="color: #c6c;">0.05</span> <span style="color: #c6c;">0.0</span> s <span style="color: #c6c;">0.5</span> <span style="color: #000080;">&#41;</span></pre></div></div>

<p>We can pass the resulting list directly to our plot function, but first we need to create a window to display it in:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> w <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">new</span> Window<span style="color: #000080;">&#40;</span>Name<span style="color: #000080;">=</span><span style="color: #008080;">&quot;Plot&quot;</span>,Width<span style="color: #000080;">=</span><span style="color: #c6c;">500.0</span>,Height<span style="color: #000080;">=</span><span style="color: #c6c;">500.0</span><span style="color: #000080;">&#41;</span>
<span style="color: #06c; font-weight: bold;">let</span> wp <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">new</span> WrapPanel<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
w<span style="color: #000080;">.</span><span style="color: #505090;">Content</span> <span style="color: #000080;">&lt;-</span> wp
w<span style="color: #000080;">.</span><span style="color: #505090;">Visibility</span> <span style="color: #000080;">&lt;-</span> Visibility<span style="color: #000080;">.</span><span style="color: #505090;">Visible</span></pre></div></div>

<p>Executing this code in FSI will display a blank window (probably behind your active window if you're within Visual Studio). Then we can add the plot to the graph:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">plot wp <span style="color: #000080;">&#40;</span>varyExpiry call <span style="color: #c6c;">100</span> <span style="color: #c6c;">10.0</span> <span style="color: #c6c;">100.0</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>Voila! Obviously the plot is very, very basic, but it's an interesting experiment, and it does makes it extremely easy to plot functions interactively in almost the same way as you can with applications like Excel and MatLab. Pretty powerful.<br />
<div id="attachment_190" class="wp-caption alignnone" style="width: 160px"><a href="http://72.47.193.211/wp-content/uploads/2009/06/graph_call_expiry.png"><img src="http://www.voyce.com/wp-content/uploads/2009/06/graph_call_expiry-150x150.png" alt="Call option values for varying expiries" title="graph_call_expiry" width="150" height="150" class="size-thumbnail wp-image-190" /></a><p class="wp-caption-text">Call option values for varying expiries</p></div> <div id="attachment_191" class="wp-caption alignnone" style="width: 310px"><a href="http://72.47.193.211/wp-content/uploads/2009/06/graph_call_put_expiry.png"><img src="http://www.voyce.com/wp-content/uploads/2009/06/graph_call_put_expiry-300x170.png" alt="Call and put option values for varying expiries" title="graph_call_put_expiry" width="300" height="170" class="size-medium wp-image-191" /></a><p class="wp-caption-text">Call and put option values for varying expiries</p></div></p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/06/26/black-scholes-option-pricing-using-fsharp-and-wpf/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>IL analysis using F#</title>
		<link>http://www.voyce.com/index.php/2009/04/24/il-analysis-using-fsharp/</link>
		<comments>http://www.voyce.com/index.php/2009/04/24/il-analysis-using-fsharp/#comments</comments>
		<pubDate>Fri, 24 Apr 2009 21:19:17 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[IL]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=128</guid>
		<description><![CDATA[A description of using F# language features and reflection to enable basic analysis of .NET IL (intermediate language).]]></description>
			<content:encoded><![CDATA[<p>I recently needed to determine which functions were called by some of our F# code. Naively, you can use existing tools like ildasm, to disassemble a .NET DLL and then search the resulting IL source code for references. The obvious problem here though, is that you&#8217;re going to include <em>all</em> references whether or not they&#8217;re actually called. In some circumstances this isn&#8217;t too bad, but in our case we pull in a great deal of shared library code, so you&#8217;re likely to get lots of false positives.</p>
<p>There are some other options to more accurately determine whether the method you&#8217;re interested in is actually called: run the code, or &#8220;almost&#8221; run it, by simulating the operation of the CLR. To radically understate; this is quite a lot of work. Yet another option is to statically analyse the original source code. This is generally easier than dynamic evaluation, but there are some serious and well known problems doing it exhaustively, that can result in the complexity eventually converging with that of full dynamic analysis.</p>
<p>So broadly, we have 3 types of approches:<br />
<table>
<tr>
<td><em><br />
Approach</em></p>
</td>
<td><em><br />
Implementation</em></p>
</td>
<td><em><br />
Accuracy</em></p>
</td>
</tr>
<tr>
<td>Disassembly</td>
<td>Easy</td>
<td> Superset</td>
</tr>
<tr>
<td>Dynamic analysis</td>
<td> Hard</td>
<td> Exact</td>
</tr>
<tr>
<td>Static analysis</td>
<td> Medium</td>
<td> Medium</td>
</tr>
</table>
<p>Anyone for a trade-off? Unsurprisingly I decided to look at implementing the third option. Although static analysis is normally performed on the source code itself, it&#8217;s actually easier for us to use the generated IL, it certainly requires less gnarly parsing. We can also take some short cuts based on the fact that we&#8217;re analysing F# code, more on that later.</p>
<p>We can use F#&#8217;s discriminated unions &#8211; a type that is constructed from one of many possible options &#8211; to describe the universe of IL instructions in a pretty concise way, e.g. (a partial example):</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">type</span> inst <span style="color: #000080;">=</span>
    <span style="color: #000080;">|</span> Nop
    <span style="color: #000080;">|</span> Break
    <span style="color: #000080;">|</span> Ldarg_0
    <span style="color: #000080;">|</span> Ldc_i4 <span style="color: #06c; font-weight: bold;">of</span> int32
    <span style="color: #000080;">|</span> Newobj <span style="color: #06c; font-weight: bold;">of</span> meth
<span style="color: #06c; font-weight: bold;">and</span> field <span style="color: #000080;">=</span> FieldInfo
<span style="color: #06c; font-weight: bold;">and</span> meth <span style="color: #000080;">=</span> MethodBase
<span style="color: #06c; font-weight: bold;">and</span> typ <span style="color: #000080;">=</span> Type</pre></div></div>

<p>This allows us to construct instances of <code>inst</code> by doing something like this in fsi (F# interactive):<br />
<code><br />
&gt; let i = Ldc_i4 2;;<br />
val i : inst<br />
</code><br />
You may have noticed that as well as the instructions that take simple types like int32, we also have ones that accept <code>meth</code>, which is an alias for System.Reflection.MethodBase, the base class for all methods, including constructors, which is what&#8217;s used to construct a <code>Newobj</code>.</p>
<p>Now we have this discrimated union defined, we need a way to build instances of it. In the IL byte stream, instructions are stored as opcodes, an unsigned 16bit integer. Firstly we need to get the raw bytes representing the IL. Using Reflection, it&#8217;s fairly easy given <code>m</code> of type <code>MethodInfo</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> body <span style="color: #000080;">=</span> m<span style="color: #000080;">.</span><span style="color: #505090;">GetMethodBody</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> ilbytes <span style="color: #000080;">=</span> body<span style="color: #000080;">.</span><span style="color: #505090;">GetILAsByteArray</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> ms <span style="color: #000080;">=</span> <span style="color: #06c; font-weight: bold;">new</span> IO<span style="color: #000080;">.</span><span style="color: #505090;">MemoryStream</span><span style="color: #000080;">&#40;</span>ilbytes<span style="color: #000080;">&#41;</span>
    <span style="color: #000080;">...</span></pre></div></div>

<p>So now we have a stream of bytes, and we can use functions from System.IO to extract information in various sized pieces:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">let</span> getByte <span style="color: #06c; font-weight: bold;">_</span>  <span style="color: #000080;">=</span> <span style="color: #000080;">&#40;</span>byte <span style="color: #000080;">&#40;</span>ms<span style="color: #000080;">.</span><span style="color: #505090;">ReadByte</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">let</span> i2 <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span> readInt16 ms
    <span style="color: #06c; font-weight: bold;">let</span> i4 <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">=</span> readInt32 ms
    <span style="color: #000080;">...</span></pre></div></div>

<p>As Harry Hill would say; &#8220;well, you get the idea with that&#8221;. It&#8217;s worth noting that these functions have a dummy argument (indicated by the<br />
underscore). This is required because they have a side effect &#8211; reading from the stream, changing it&#8217;s state &#8211; which is not obvious to the compiler, so if we omitted it the function would only be called once. Although adding the dummy arg is required, it does have the unfortunate consequence that we have to pass something (normally unit) which can look a little ugly in the normally terse F# world.</p>
<p>As the ECMA CIL spec describes, IL opcodes consist of either 1 or 2 bytes, in which case the first is always 0xFE. Now we can begin to implement something serious. Given <code>ms</code> of type <code>MemoryStream</code> we can write something that will convert it to instructions:</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">    <span style="color: #06c; font-weight: bold;">match</span> ms<span style="color: #000080;">.</span><span style="color: #505090;">ReadByte</span><span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span> <span style="color: #06c; font-weight: bold;">with</span>
    <span style="color: #000080;">|</span> 0xFE <span style="color: #06c; font-weight: bold;">as</span> lb <span style="color: #000080;">-&gt;</span>
        <span style="color: #060; font-style: italic;">// Two byte instruction, read further byte</span>
        <span style="color: #06c; font-weight: bold;">let</span> hb <span style="color: #000080;">=</span> getByte<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span>
        <span style="color: #06c; font-weight: bold;">let</span> i <span style="color: #000080;">=</span> <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#40;</span>uint16 lb<span style="color: #000080;">&#41;</span> <span style="color: #000080;">&lt;&lt;&lt;</span> <span style="color: #c6c;">8</span> <span style="color: #000080;">&#41;</span> <span style="color: #000080;">+</span> <span style="color: #000080;">&#40;</span>uint16 hb<span style="color: #000080;">&#41;</span>
        <span style="color: #06c; font-weight: bold;">let</span> t <span style="color: #000080;">=</span>
            <span style="color: #06c; font-weight: bold;">match</span> i <span style="color: #06c; font-weight: bold;">with</span>
            <span style="color: #000080;">|</span> 0xfe01us <span style="color: #000080;">-&gt;</span> Ceq
    <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #06c; font-weight: bold;">as</span> b <span style="color: #000080;">-&gt;</span>
        <span style="color: #06c; font-weight: bold;">let</span> t <span style="color: #000080;">=</span>
            <span style="color: #06c; font-weight: bold;">match</span> b <span style="color: #06c; font-weight: bold;">with</span>
            <span style="color: #000080;">|</span> 0x0 <span style="color: #000080;">-&gt;</span> Nop
            <span style="color: #000080;">|</span> 0x1f <span style="color: #000080;">-&gt;</span> Ldc_i4_s <span style="color: #000080;">&#40;</span>getByte<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
            <span style="color: #000080;">|</span> 0x20 <span style="color: #000080;">-&gt;</span> Ldc_i4 <span style="color: #000080;">&#40;</span>i4<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span>
            <span style="color: #000080;">|</span> 0x73 <span style="color: #000080;">-&gt;</span> Newobj <span style="color: #000080;">&#40;</span>meth<span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>So we now have a function that will go from a method to a list of opcodes and operands (<code>MethodBase -> inst []</code>). These are essentially the same steps we would perform if we were writing an interpreter for a textual language; taking the source and transforming it into an abstract syntax tree. In that case it&#8217;s a tree rather than a list, but the next step is pretty much the same anyway: we pattern match over it. This is the point where we can decide how we want to interpret the instruction stream.</p>

<div class="wp_syntax"><div class="code"><pre class="fsharp" style="font-family:monospace;">        insts
        <span style="color: #000080;">|&gt;</span> List<span style="color: #000080;">.</span><span style="color: #505090;">map</span> <span style="color: #000080;">&#40;</span><span style="color: #06c; font-weight: bold;">fun</span> inst <span style="color: #000080;">-&gt;</span>
            <span style="color: #06c; font-weight: bold;">match</span> inst <span style="color: #06c; font-weight: bold;">with</span>
            <span style="color: #000080;">|</span> Newobj<span style="color: #000080;">&#40;</span>meth<span style="color: #000080;">&#41;</span> <span style="color: #000080;">-&gt;</span>
                printf <span style="color: #008080;">&quot;NEW: %s.%s<span style="color: #008080; font-weight: bold;">\n</span>&quot;</span> meth<span style="color: #000080;">.</span><span style="color: #505090;">DeclaringType</span><span style="color: #000080;">.</span><span style="color: #505090;">Namespace</span> meth<span style="color: #000080;">.</span><span style="color: #505090;">DeclaringType</span><span style="color: #000080;">.</span><span style="color: #505090;">Name</span>
            <span style="color: #000080;">|</span> <span style="color: #06c; font-weight: bold;">_</span> <span style="color: #000080;">-&gt;</span>
                <span style="color: #000080;">&#40;</span><span style="color: #000080;">&#41;</span></pre></div></div>

<p>Here we need to make some compromises based on the problem domain. I&#8217;m not trying to create a general purpose static analyser, but one that will work on object code in a certain format &#8211; that generated by the F# compiler. As such we make some assumptions and use some knowledge about the internals of the compiler to get the result we&#8217;re after. To be specific we&#8217;re relying on the fact that the compiler generates types for closures, and we assume that closures will always be called, even though in reality they needn&#8217;t be.</p>
<p>So based on this, we can put together something that, given an entry point &#8211; a particular method on a type &#8211; can recurse through the code, following references to other methods and types via the <code>Newobj</code>, <code>Call</code>, <code>Calli</code> and <code>Callvirt</code> instructions. This will build up a graph of all types referenced directly from our starting point. We also use our intimate knowledge of the purpose of F#&#8217;s <code>FastFunc</code> type (from which all functions are derived) and always follow its Invoke method if we find an instance of that type, even if it&#8217;s not directly referenced.</p>
<p>There are some major caveats. Anything accessed purely via reflection will not be detected. And polymorphic objects passed in and accessed via interfaces will also be missed. Also, I don&#8217;t attempt to do full flow analysis; e.g. following branch instructions etc, as this isn&#8217;t a common pattern in fsc-generated IL.</p>
<p>Luckily in the particular cases I&#8217;m looking at, these shortcomings don&#8217;t have a significant impact. Instead, we end up with a reasonably straight-forward and useful way of determining whether a particular function is called. It&#8217;s already been used in anger to determine whether a buggy function was referenced from some release-candidate software.</p>
<p>As a little post-script: rather than writing your own library from the ground-up to do this, there are some &#8220;off-the-shelf&#8221; solutions that you can try. Notably the recently released <a href="http://ccimetadata.codeplex.com/">CCI</a>, a common compiler infrastructure out of Microsoft Research, that allows you to reverse engineer IL metadata. I haven&#8217;t had a chance to have a good look at this yet, but it seems to do what we need for call graph analysis. There&#8217;s also an API called AbstractIL &#8211; in the absil.dll assembly &#8211; that ships with and is used internally by the F# compiler toolset. This looks extremely powerful, but the API is complex and the documentation is poor. Depending on exactly what your motivation is for looking at this stuff, it&#8217;s worth checking if these ready-made libraries will do what you need.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/04/24/il-analysis-using-fsharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Verifying dynamically generated IL</title>
		<link>http://www.voyce.com/index.php/2009/03/30/verifying-dynamic-il/</link>
		<comments>http://www.voyce.com/index.php/2009/03/30/verifying-dynamic-il/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 10:17:52 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[emit]]></category>
		<category><![CDATA[IL]]></category>
		<category><![CDATA[peverify]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=97</guid>
		<description><![CDATA[It&#8217;s safe to assume that when you use the C#, F# or (heaven forfend) VB.NET compilers, the IL generated for you will be correct. But, if you&#8217;re using Reflection.Emit to generate code &#8220;by hand&#8221; in a dynamic method or assembly it can be difficult to identify problems with the IL you emit. In the majority [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s safe to assume that when you use the C#, F# or (heaven forfend) VB.NET compilers, the IL generated for you will be correct. But, if you&#8217;re using Reflection.Emit to generate code &#8220;by hand&#8221; in a dynamic method or assembly it can be difficult to identify problems with the IL you emit. In the majority of cases the runtime will simply throw an InvalidProgramException. This is of course, exactly as you&#8217;d expect, as the JIT compiler (which generates architecture-specific machine code from the IL) is intended to be highly performant, rather than robust to errors which should&#8217;ve been dealt with earlier in the tool chain.</p>
<p>So what tools can you use to troubleshoot problems with dynamic IL? In a word: peverify.<br />
<span id="more-97"></span><br />
<strong>What is peverify?</strong><br />
peverify (where PE stands for portable executable, the file format used by Windows executables) takes a .NET assembly and validates the metadata &#8211; the type structure &#8211; and IL &#8211; the instructions, using a combination of rules and static analysis.</p>
<p>As the MSDN pages states it&#8217;s intended for use by &#8220;compiler writers and script engine developers&#8221;, but with a few small modifications to your code you can also use it with Reflection.Emit.</p>
<p>Here&#8217;s some example code that uses F# to emit a simple type (deriving from MarshalByRefObject) to wrap another object. The intention is that the wrapper type implements the same interfaces as the underlying object, and delegates calls to it. The key part of the code is where we emit the body of each function.</p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;"><span style="color: blue;">let</span> wrapObject (obj:obj) =</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> name = <span style="color: maroon;">"MyAssembly"</span></pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> filename = name + <span style="color: maroon;">".dll"</span></pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> ab = AppDomain.CurrentDomain.DefineDynamicAssembly(AssemblyName(name), AssemblyBuilderAccess.RunAndSave)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> modb = ab.DefineDynamicModule(filename, filename)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> tb = modb.DefineType(<span style="color: maroon;">"MyType"</span>, TypeAttributes.Class, typeof&lt;MarshalByRefObject&gt;)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> objField : FieldBuilder = tb.DefineField(<span style="color: maroon;">"_underlyingObject"</span>, typeof&lt;obj&gt;, FieldAttributes.Public)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; obj.GetType().GetInterfaces() </pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; |&gt; Array.iter (<span style="color: blue;">fun</span> itf <span style="color: blue;">-&gt;</span></pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; tb.AddInterfaceImplementation(itf)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; itf.GetMethods()</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; |&gt; Array.iter (<span style="color: blue;">fun</span> m <span style="color: blue;">-&gt;</span></pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> ptypes = m.GetParameters() |&gt; Array.map (<span style="color: blue;">fun</span> p <span style="color: blue;">-&gt;</span> p.ParameterType)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> mb = tb.DefineMethod(m.Name, MethodAttributes.Public|||MethodAttributes.Virtual, m.ReturnType, ptypes)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> il = mb.GetILGenerator()</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// load object reference from field</span></pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; il.Emit(OpCodes.Ldarg_0)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; il.Emit(OpCodes.Ldfld, objField)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// cast it to appropriate type</span></pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; il.Emit(OpCodes.Castclass, itf)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// push all args, verbatim</span></pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; m.GetParameters() |&gt; Array.iteri (<span style="color: blue;">fun</span> n p <span style="color: blue;">-&gt;</span> il.Emit(OpCodes.Ldarg,n+1))</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// call method on underlying objects</span></pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; il.Emit(OpCodes.Callvirt, m)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; il.Emit(OpCodes.Ret)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; ))</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> typ = tb.CreateType()</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; ab.Save(filename)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> o = typ.GetConstructor([||]).Invoke([||])</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; typ.GetField(<span style="color: maroon;">"_underlyingObject"</span>).SetValue(o, obj)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; o</pre>
</div>
<p>Now, in my first version of the code, I forgot that you need to load &#8220;this&#8221; onto the stack before loading a field, so the code looked like this:</p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">let</span> il = mb.GetILGenerator()</p>
<p style="margin: 0px;"><span style="color: green;">// il.Emit(OpCodes.Ldarg_0) Oops, the forgot to load &#8220;this&#8221; onto stack</span></p>
<p style="margin: 0px;"> il.Emit(OpCodes.Ldfld, objField)</p>
<p style="margin: 0px;"> il.Emit(OpCodes.Castclass, itf)</p>
</div>
<p>I used the following code to create an instance of a type implementing IFoo, wrap it and invoke the function:</p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;"><span style="color: blue;">do</span></pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> o = </pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; { <span style="color: blue;">new</span> MyInterfaces.IFoo <span style="color: blue;">with</span></pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">member</span> this.Bar(a) = a + <span style="color: maroon;">"!"</span> }</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">let</span> wrappedObj = wrap o</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; wrappedObj.GetType().InvokeMember(<span style="color: maroon;">"Bar"</span>, BindingFlags.Instance|||BindingFlags.Public|||BindingFlags.InvokeMethod, <span style="color: blue;">null</span>, wrappedObj, [|box <span style="color: maroon;">"Hello"</span>|])</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; ()</pre>
</div>
<p>As you&#8217;d expect the function generated the expected InvalidProgramException:<br />
<code><br />
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> <b>System.InvalidProgramException: Common Language Runtime detected an invalid program.</b><br />
   at MyType.Bar(String )<br />
   --- End of inner exception stack trace ---<br />
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct&#038; sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)<br />
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)<br />
</code></p>
<p>In order to use peverify with your code, the first thing you need to do is save the assembly to disk. This involves making a couple of changes to the code, because normally you&#8217;d do everything in memory and avoid the cost of the disk access. First, change Run to RunAndSave in the call to define the assembly:</p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">let</span> ab = AppDomain.CurrentDomain.DefineDynamicAssembly(AssemblyName(name), AssemblyBuilderAccess.<b>RunAndSave</b>)</p>
</div>
<p>And ensure you include the filename when you create the module:</p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">let</span> modb = ab.DefineDynamicModule(filename<b>, filename</b>)</p>
</div>
<p>Now, you should be able to save the assembly to disk by adding a call after you&#8217;re finished building the type:</p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">ab.Save(filename)</p>
</div>
<p>Be aware that you can&#8217;t specify a path in the call to AssemblyBuilder.Save. This is presumably a security restriction; keeping generated binaries within the application&#8217;s directory tree and preventing people creating arbitrary binaries all over the file system. If you&#8217;re not running from an obvious &#8220;top level&#8221; application, e.g. you&#8217;re using a scripting environment like F# interactive, you may find the location of the file odd; when using FSI from within Visual Studio, the binary is created in &#8220;C:Program FilesMicrosoft Visual Studio 9.0Common7IDE&#8221;.</p>
<p>Now we can run peverify on the DLL and we get a much richer explanation of the problem:</p>
<p><code><br />
Microsoft (R) .NET Framework PE Verifier.  Version  3.5.30729.1<br />
Copyright (c) Microsoft Corporation.  All rights reserved.<br />
</code><code><br />
[IL]: Error: [c:Program FilesMicrosoft Visual Studio 9.0Common7IDEMyAssembl<br />
y.dll : MyType::Bar][offset 0x00000000] <b>Stack underflow</b>.<br />
1 Error(s) Verifying c:Program FilesMicrosoft Visual Studio 9.0Common7IDEMy<br />
Assembly.dll<br />
</code></p>
<p>From this error message it&#8217;s pretty clear that the first thing we&#8217;re doing (i.e. the instruction at offset 0) is underflowing the stack; calling an instruction that expects more on the stack than we&#8217;ve put there. That should give us a good idea of how to fix the problem.</p>
<p>Another error that I came across was the omission of a cast in the IL:</p>
<div style="font-family: Consolas; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;"><span style="color: blue;">let</span> il = mb.GetILGenerator()</p>
<p style="margin: 0px;">il.Emit(OpCodes.Ldarg_0)</p>
<p style="margin: 0px;">il.Emit(OpCodes.Ldfld, objField)</p>
<p style="margin: 0px;"><span style="color: green;">//il.Emit(OpCodes.Castclass, itf) Oops, forget to cast object to specific type</span></p>
</div>
<p>From which peverify generated the fantastically specific error message:<br />
<code><br />
[IL]: Error: [c:Program FilesMicrosoft Visual Studio 9.0Common7IDEMyAssembl<br />
y.dll : MyType::Bar][offset 0x0000000C][found ref 'System.Object'][expected ref<br />
'MyInterfaces.IFoo'] Unexpected type on the stack.<br />
</code></p>
<p>And of course, once all your emission bugs are fixed, you should get a success report:<br />
<code><br />
All Classes and Methods in c:Program FilesMicrosoft Visual Studio 9.0Common7<br />
IDEMyAssembly.dll Verified.<br />
</code></p>
<p>The only problem with peverify as far as I can see is that there are no compiler style &#8220;error codes&#8221; to help you identify and resolve the problem. It assumes fairly intimate knowledge of the IL/CLR specification and there may be a bit of effort required to get from the error to the resolution. But one thing&#8217;s for sure: it&#8217;s definitely easier than trying to do it with just InvalidProgramException.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/03/30/verifying-dynamic-il/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
