<?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; Windows</title>
	<atom:link href="http://www.voyce.com/index.php/category/software-development/windows/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.voyce.com</link>
	<description>Programming and debugging tidbits</description>
	<lastBuildDate>Sun, 15 Jan 2012 13:10:46 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>C++: The oldest new kid on the block</title>
		<link>http://www.voyce.com/index.php/2011/09/18/cpp-the-oldest-new-kid-on-the-block/</link>
		<comments>http://www.voyce.com/index.php/2011/09/18/cpp-the-oldest-new-kid-on-the-block/#comments</comments>
		<pubDate>Sat, 17 Sep 2011 23:06:09 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1294</guid>
		<description><![CDATA[Is C++ coming back to a warm welcome from Microsoft?  ]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.voyce.com/wp-content/uploads/2011/09/ballmer_cpp.png"><img src="http://www.voyce.com/wp-content/uploads/2011/09/ballmer_cpp.png" alt="Tasty" title="Tasty" width="200" height="200" class="alignright size-full wp-image-1296" /></a>Nobody could have failed to notice the recent resurgence of interest in the C++ programming language. In particular, the recent <a href="http://www.buildwindows.com/">Build</a> conference was the most we’ve seen Microsoft talking about C++ for several years. Why has a language that’s been languishing in the “prehistoric irrelevance” category for so long suddenly come back into vogue?<br />
<span id="more-1294"></span></p>
<h3>Dark Days</h3>
<p>We should bear in mind that in some camps, C++ never went away. The financial, scientific and games programming communities have bravely kept the fires burning.</p>
<p>Why? Primarily performance. In these industries performance is a feature, it’s a key differentiator, and it will help you make money. Can you say the same for an enterprise app (there I go, using that term disparagingly again) that just displays a form interface over a relational database?</p>
<p>However, even in the C++ bastions, the language was getting a bad press. I can only speak for the finance industry, where I’ve been working for the past 10 years, but even here the focus briefly switched away from raw performance to complex (overly-complex, dangerously-complex, as hindsight tells us) trades where getting to market first with something new was key: developer productivity was key. Flexibility and generality was key.</p>
<p>In that case, you don’t want to be dealing with the vagaries of subtle errors, crashes and memory leaks that can easily creep in when you’re using a language as low-level as C++. You just want to be able to release quickly. You probably want to be using a managed language.</p>
<p>In fact, C++ was getting a bad press all over. The functional power that was provided in languages like Haskell and F# &#8211; and being hastily added to C# &#8211; was missing or awkwardly implemented in C++. The provision of things like the .NET thread pool provided programmers on the CLR an easy way to schedule asynchronous tasks, and it was being touted as the only way to survive in the highly-parallel near-future. Of course, it was possible to do this stuff in C++, it was just more difficult.   </p>
<p>Despite this, the programming community widely understood the power that C++ brings, but also that it has to be wielded carefully. Witness the oft-repeated jokes about the fact that when you shoot yourself in the foot with C++, you tend to blow your leg off. There were even tensions within Microsoft, with the pro-managed DevDiv vs the hardcore, native-favouring Windows division.</p>
<h3>The New Order</h3>
<p>So what’s changed? Herb Sutter’s recent <a href="http://channel9.msdn.com/posts/C-and-Beyond-2011-Herb-Sutter-Why-C">talk</a> covered many of the reasons why C++ is relevant again, and the most obvious reason is the emergence and importance of mobile devices and data centres. </p>
<p>They have a completely different set of requirements than the desktop: they focus on squeezing the best experience out of every available cycle (and corresponding minute of battery life), and the most performance out of every watt of data centre power per degree of cooling. We’re seeing the impact of the smartphone in your pocket and the data-centric web and social media reflecting back onto the languages we use to write software.  </p>
<p>Managed languages fall down in some important areas here. They sacrifice memory efficiency to the god of garbage collection and they offer fewer opportunities for aggressive compiler optimisations, including, in the case of .NET, making use of chip-provided performance features like SIMD instructions.</p>
<p>Nowadays in more and more of the computing industry, it’s the hardware that’s driving the development choices, not the other way around.</p>
<p>With resource-constricted platforms, you want to be doing more of the heavy lifting offline, at compile time, not at run-time with a JIT compiler.</p>
<h3>How the iPhone showed devs don&#8217;t care</h3>
<p>While (parts of) Microsoft were busy pushing the managed languages hard, Apple was quietly producing game-changing pieces of hardware that the device-carrying public were buying in their hordes. And they weren’t just buying devices, they were buying apps to play on these devices &#8211; in their millions. Lots of developers wanted a piece of this action but &#8211; quelle horreur! &#8211; You had to use an obscure variant of C to create them.</p>
<p>But &#8211; surprise, surprise &#8211; developers did it anyway. Luckily, they weren’t on their own, but this time rather than a managed runtime, they had an API to use. And they had to use it; it was, and is, literally a condition of sale that your app uses only the APIs that Apple provide and in the way that they intended. Whatever your view on the fairness of this approach, having a restricted surface area and well defined set of libraries helps developers win back some of the productivity they might otherwise have sacrificed by using Objective-C.</p>
<p>Microsoft must’ve been looking askance at this, wondering how Apple had so effectively switched the model around. MS had been based on the idea of developer productivity being king and the hardware being utterly insignificant. Now developers were writing code in a language that was broadly derided by people in the programming community, yet they were in a virtuous circle where writing apps helped to ship hardware that increased the market for their apps. </p>
<h3>We need libraries</h3>
<p>Is it possible to find a good balance between the raw power of C++ and the productivity of managed languages? I think it is; and partly it comes down to having a good set of libraries. When I say good, I mean consistent, relevant, well-documented, easily available set of libraries. Can you see where C++ may have struggled here before?</p>
<p>For the low-level, programming task oriented basics, Boost is the answer. Seriously, Boost always seems to be the answer to questions of “how do I do X in C++?” where X is a modern programming technique. Smart pointers, lambdas, higher-order functions… they’re all there. </p>
<p>A few years ago if you were working in C++, you didn’t have many options apart from vanilla STL, Boost, and writing-it-yourself (again). Now, the STL and the language itself is richer and anecdotally, organisations are more receptive to the use of Boost. So hopefully, this combination gives us back access to most of the functionality that’s available to managed developers in their pre-packaged base class libraries.</p>
<h3>C++ and Apps</h3>
<p>But how is that going to help people use it to produce compelling apps and “experiences” (cough) and specifically, how is Microsoft going to use its developer productivity nous to keep Windows relevant in the new hardware markets? </p>
<p>They need something else; something like the Apple Core frameworks. It looks like this is what Microsoft is talking about with Windows 8 and the Windows Runtime. It’s suddenly not embarrassed to admit that, hey, Windows itself is written in C++, so maybe you shouldn’t have to go through a managed ‘interpretation’ of the existing APIs, one that’s exclusively available to managed languages.</p>
<p>Of course, Microsoft can’t do anything as radical as forcing all developers targeting a mobile or tablet platform to use C++. For them, programmers, rather than any particular hardware, are the bread-and-butter, so they tend to have a slightly less dictator-style relationship with devs than Apple does. </p>
<p>Judging from what I’ve seen from Build, Microsofts chosen approach is to provide language-specific “projections” (their term) from the Windows Runtime layer into a variety of languages, including C++. The native C++ types are mapped into corresponding concepts in the vernacular of the higher level languages; Javascript, C# etc. They’ve gone to some lengths, it seems, to ensure that transitions between levels are efficient. Using C++ at both levels should be the fast path, and of course you can mix it freely with code that, for example, uses Boost or other C++ libraries. </p>
<p>Additionally and importantly, as well as basic types, collections etc, the Windows Runtime also contains all of the rich APIs for accessing app-level functionality; things like image capture, sound and geolocation. So suddenly, all of this stuff is available in all its glory directly from C++ &#8211; and other languages too via cheap bridges. What they’ve essentially got is an identical copy of the architecture that exists in the iOS world, while still attempting to keep non C++ developers on-side. </p>
<h3>The Return&#8230;?</h3>
<p>So, have Microsoft managed to bring C++ in from the cold? They seem to have admitted, at least to themselves, that developers will need to use it in order to effectively target some platforms, and they’ve used their tooling experience to make it look and feel like a managed language in their IDEs, as well as leveraging their compiler technology to do some additional useful performance tricks. It feels like C++ was a fundamental concern in the redesign of the new alternative to the creaking Win32 API.</p>
<p>But will the transition be something to make current developers switch to C++, especially those who’ve been used to living in the cosseted managed world? Perhaps, if the Microsoft-based tablet market becomes as compelling &#8211; read, large &#8211; as Apple’s. Otherwise I don’t see any reason why developers who don’t have specific platform or other runtime requirements would move; for the majority of environments, developer time is still the dominant cost, so developer productivity will still be paramount. </p>
<p>The gap between managed and unmanaged languages has certainly narrowed in that area, but it still exists. C++ is still proving surprisingly relevant, despite its 30+ years, and hopefully its use in new and different areas of computing will feed back into improvements in the language and libraries for everyone’s benefit. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/09/18/cpp-the-oldest-new-kid-on-the-block/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Am I being called from DllMain?</title>
		<link>http://www.voyce.com/index.php/2011/08/20/am-i-being-called-from-dllmain/</link>
		<comments>http://www.voyce.com/index.php/2011/08/20/am-i-being-called-from-dllmain/#comments</comments>
		<pubDate>Sat, 20 Aug 2011 12:52:37 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WinDbg]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=1258</guid>
		<description><![CDATA[How can you tell if your code is being called from within DllMain? You could use an undocumented function from ntdll.dll.]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_1265" class="wp-caption alignright" style="width: 210px"><a href="http://www.voyce.com/wp-content/uploads/2011/08/lock_200.png"><img src="http://www.voyce.com/wp-content/uploads/2011/08/lock_200.png" alt="Lock; literal images &#039;r&#039; us" title="lock_200" width="200" height="200" class="size-full wp-image-1265" /></a><p class="wp-caption-text">Lock; literal images 'r' us</p></div>While Googling for an obscure Windows function the other day, I came across <a href="http://www.geoffchappell.com/viewer.htm?doc=index.htm">this</a> fantastically useful repository of undocumented WinAPI functions, put together by Geoff Chappell. I&#8217;m not sure how I hadn&#8217;t discovered it before.</p>
<p>One of the functions that immediately caught my eye was <a href="http://www.geoffchappell.com/viewer.htm?doc=studies/windows/win32/ntdll/api/ldrapi/lockloaderlock.htm">LdrLockLoaderLock</a>. I&#8217;d previously spent quite a few frustrating hours trying to figure out how to determine whether some code was being executed from DllMain, i.e. while in the loader lock, so I could avoid doing anything dodgy &#8211; or indeed, anything at all. </p>
<p>The case I was looking at was some logging library code that was used, amongst other things, to record the fact that DLLs were being unloaded. Unfortunately when this was called from DllMain, it sometimes caused a deadlock, for all the reasons we already know about. The library code was called from lots of DLLs, so it wasn&#8217;t feasible to fix all of the call sites, instead I had to make the logging a no-op when it&#8217;s not safe.<br />
<span id="more-1258"></span><br />
I&#8217;m embarrassed to say that my previous attempt to detect the lock involved some pretty heinous hackery. I worked out the memory address (the offset within ntdll.dll) where the loader lock critical section is located, cast that bit of memory to a CRITICAL_SECTION and tested it. I even had to provide the ability to change the offset based on the version of ntdll being used, in a vain attempt to reduce its fragility. Ouch. It was very nasty, and to be honest although it worked in the cases where I tested it, I was reluctant to release it.</p>
<p>Luckily, along comes LdrLockLoaderLock to save my blushes. It appears to give me exactly the functionality I need; you can pass a flag to tell it to return immediately if the lock&#8217;s already been taken, and there&#8217;s a status parameter that can be used to tell if you got the lock &#8211; whereupon you can call the corresponding <a href="http://www.geoffchappell.com/viewer.htm?doc=studies/windows/win32/ntdll/api/ldrapi/unlockloaderlock.htm">LdrUnlockLoaderLock</a>. Nice!  </p>
<p>I wonder if this is what&#8217;s used by the Visual Studio <a href="http://msdn.microsoft.com/en-us/library/ms172219.aspx">loader lock managed debugging assistant</a> to determine if your managed code is being run under the loader lock?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2011/08/20/am-i-being-called-from-dllmain/feed/</wfw:commentRss>
		<slash:comments>0</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>Modifying the VC runtime to get better heap allocation stack traces</title>
		<link>http://www.voyce.com/index.php/2010/03/17/modifying-the-vc-runtime-to-get-better-heap-allocation-stack-traces/</link>
		<comments>http://www.voyce.com/index.php/2010/03/17/modifying-the-vc-runtime-to-get-better-heap-allocation-stack-traces/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 23:24:30 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WinDbg]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[heap]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=754</guid>
		<description><![CDATA[Heap allocation stack traces are useless when using certain versions of the MSVC runtime. Is it possible to modify and rebuild MSVCR80 to avoid this?]]></description>
			<content:encoded><![CDATA[<p>Today I was trying to track down some &#8211; how can I put this politely &#8211; &#8220;unusual&#8221; memory usage in some unmanaged code running inside Excel. I broke out WinDbg and tried the usual suspects to get an idea of how memory was being used. Unfortunately, the way that msvcr80.dll is built stopped me from getting decent stack traces for the allocations, so I decided to try and rebuild it with a fix to remedy the situation.<br />
<span id="more-754"></span></p>
<h2>Collecting stack traces</h2>
<p>One of the most helpful things the heap manager can do for you when investigating memory issues is to capture stack traces for each heap allocation. You can enable the &#8220;collect stack traces&#8221; heap flag using the gflags GUI or from within WinDbg:</p>
<pre>
0:006> !gflag +ust
Current NtGlobalFlag contents: 0x00001040
    hpc - Enable heap parameter checking
    ust - Create user mode stack trace database
</pre>
<p>This means that for each heap block (one located at <code>0x0bbf7308</code> in this case), you can see where it was allocated by using the -a (show all information) option:</p>
<pre>
0:006> !heap -p -a 0bbf7308
    address 0bbf7308 found in
    _HEAP @ a630000
      HEAP_ENTRY Size Prev Flags    UserPtr UserSize - state
        0bbf7308 0073 0000  [07]   0bbf7310    00380 - (busy)
        Trace: 401c
        7c96d6dc ntdll!RtlDebugAllocateHeap+0x000000e1
        7c949d18 ntdll!RtlAllocateHeapSlowly+0x00000044
        7c91b298 ntdll!RtlAllocateHeap+0x00000e64
        78134333 MSVCR80!malloc+0x00000077
</pre>
<p>But the obvious problem with this is that the stack trace always stops at malloc. Something&#8217;s allocating some memory? You don&#8217;t say&#8230; </p>
<p>It turns out that this is a <a href="http://http://www.nynaeve.net/?p=209">well understood</a> and documented issue with the Microsoft VC++ runtime, variously known as msvcrt, msvcr70, msvcr71, msvcr80, msvcr90, etc. Unfortunately they&#8217;re all built using the stack frame pointer omission optimisation. Well they&#8217;re built with the <a href="http://msdn.microsoft.com/en-us/library/8f8h5cxt.aspx">-O1</a> (favour small code) option, which implies <a href="http://msdn.microsoft.com/en-us/library/2kxx5t2c.aspx">-Oy</a>. This means that the fast stack-walking algorithm the heap manager uses stops at functions without a return address. The only way to get a decent trace in this situation would be to use the DbgHelp API along with the .pdb files, which would be far too slow to do at each allocation site.</p>
<h2>&#8220;Fixing&#8221; it</h2>
<p>So, given that the source for the runtime library ships as part of Visual Studio, maybe it would be possible to build it without the -Oy option?</p>
<p>My first attempt at building it failed miserably with errors like:<br />
<code><br />
NMAKE : fatal error U1073: don't know how to make 'build\intel\mt_obj\startup.lib'<br />
</code><br />
Luckily this <a href="http://blogs.msdn.com/michkap/articles/478235.aspx">excellent page</a> helped me get past this to a point where I could actually get a DLL built.</p>
<p>The next stage was to modify the build scripts to use different compiler switches. This was simply a case of changing line 69 of <code>makefile.sub</code> from:<br />
<code>CFLAGS=$(CFLAGS) -O1</code><br />
to:<br />
<code>CFLAGS=$(CFLAGS) -O1 <b>-Oy-</b></code></p>
<p>I thought I may have to also modify the build scripts to output a version of the DLL with the same name as the file I was replacing, msvcr80.dll, directly, in case there were internal references to the name in embedded manifests. There&#8217;s a section at the top of the build script for choosing a name for your private version of the library, but it strongly discourages use of the &#8220;reserved&#8221; MSVC* names. Luckily it turns out not to be necessary; the DLL is constructed in such a way as to be rename-able without any ill effects. I could build _sample_.dll (the default output name) and simply copy it to the destination directory in the SxS tree (<code>C:\WINNT\WinSxS\x86_Microsoft.VC80.CRT_1fc8b3b9a1e18e3b_8.0.50727.3053_x-ww_b80fa8ca</code>) and rename it.</p>
<h2>Result</h2>
<p>Now I get the expected full stack trace (names have been changed to protect the innocent):</p>
<pre>
0:006> !heap -p -a 0bbf7308
    address 0bbf7308 found in
    _HEAP @ a630000
      HEAP_ENTRY Size Prev Flags    UserPtr UserSize - state
        0bbf7308 0073 0000  [07]   0bbf7310    00380 - (busy)
        Trace: 401c
        7c96d6dc ntdll!RtlDebugAllocateHeap+0x000000e1
        7c949d18 ntdll!RtlAllocateHeapSlowly+0x00000044
        7c91b298 ntdll!RtlAllocateHeap+0x00000e64
        78134333 MSVCR80!malloc+0x00000077
        7816207f MSVCR80!operator new+0x0000001d
        fa92336 leakydll!std::allocator<std::vector<ATL::CAdapt<ATL::CComBSTR>,std::allocator<ATL::CAdapt<ATL::CComBSTR> > > >::allocate+0x00000016
        fa9879b leakydll!std::vector<CComVariant,std::allocator<CComVariant> >::resize+0x0000005b
        ...
        ...etc...
</pre>
<p>That&#8217;ll make it <i>much</i> easier to work out what&#8217;s happening and who&#8217;s responsible. Of course, you should be careful with this modified version. Only use it on development machines, and make sure it doesn&#8217;t escape into the wild: with great power comes great responsibility.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/03/17/modifying-the-vc-runtime-to-get-better-heap-allocation-stack-traces/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Where&#8217;s my window?</title>
		<link>http://www.voyce.com/index.php/2010/01/31/wheres-my-window/</link>
		<comments>http://www.voyce.com/index.php/2010/01/31/wheres-my-window/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 20:06:30 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Windows]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[hidden]]></category>
		<category><![CDATA[invisible]]></category>
		<category><![CDATA[missing]]></category>
		<category><![CDATA[screen]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=667</guid>
		<description><![CDATA[Where's my window gone? I'm sure I left it around here somewhere...]]></description>
			<content:encoded><![CDATA[<p>On Windows, if you regularly change screen resolution or size, perhaps by accessing a machine remotely, you might find some of your application windows are no longer visible; they&#8217;re positioned outside of the visible display area. If you can&#8217;t see the window, it can be a <i>little</i> difficult to use the application. How can you get that window back?<br />
<span id="more-667"></span><br />
In most cases &#8211; but only only on pre-Vista versions of Windows &#8211; it can be easily resolved by right clicking on the task bar icon for the application, selecting Move and then using the cursor keys. This makes the cursor &#8220;stick&#8221; to the caption of the window, and you can move the mouse (without clicking!) to bring it onto the screen. Clicking releases the window.</p>
<p>You can do it without the mouse, too. Just make sure the window is selected in the task bar (perhaps by using the Windows key and then tabbing to the appropraite icon), then hit Alt-Space, Alt-M, and then using the cursor keys.</p>
<p>The only problem is, some application developers choose to change the system menu &#8211; the menu visible from clicking the app&#8217;s icon in the top left, or by right-clicking the task bar icon &#8211; perhaps deciding for some insane reason not to include the standard Move option (as an aside, this breaks one of the fundamental tenets of usability: don&#8217;t change &#8211; or in this case, remove &#8211; existing, established behaviour). If this is the case, you can instead use a handful of lines of Windows API code to access the window and move it programatically. Here&#8217;s the entire code of a program that will do exactly that:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#include &lt;windows.h&gt;</span>
<span style="color: #339900;">#include &lt;tchar.h&gt;</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: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>argc <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">2</span><span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		_tprintf<span style="color: #008000;">&#40;</span>_T<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;usage: mover windowtitle<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
		<span style="color: #0000ff;">return</span> <span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
	<span style="color: #008000;">&#125;</span>
	HWND hwnd <span style="color: #000080;">=</span> FindWindow<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">NULL</span>, argv<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>hwnd<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		SetWindowPos<span style="color: #008000;">&#40;</span>hwnd, HWND_TOP, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">0</span>, <span style="color: #0000dd;">400</span>,<span style="color: #0000dd;">400</span>, <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #008000;">&#125;</span>
	<span style="color: #0000ff;">else</span>
		_tprintf<span style="color: #008000;">&#40;</span>_T<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Unable to find window %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span>, argv<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</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>Compile it up and you can use it as a handy little utility to move arbitrary top level windows, e.g. if you&#8217;ve got regedit running:<br />
<code><br />
mover "Registry Editor"<br />
</code><br />
The only tricky thing is finding the exact title of the window to use. Well, you wouldn&#8217;t want it to be <i>too</i> easy, would you?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2010/01/31/wheres-my-window/feed/</wfw:commentRss>
		<slash:comments>2</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>Don&#8217;t do anything in DllMain&#8230; Please</title>
		<link>http://www.voyce.com/index.php/2009/12/03/dont-do-anything-in-dllmain-please/</link>
		<comments>http://www.voyce.com/index.php/2009/12/03/dont-do-anything-in-dllmain-please/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 23:27:13 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[dll]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=554</guid>
		<description><![CDATA[Thinking of adding some code to your DLLs DllMain function? STOP!]]></description>
			<content:encoded><![CDATA[<p>Novice Windows programmers can often think that <code>DllMain</code> is a good place to get that one-time set-up and tear-down work done. It seems to offer an ideal opportunity to know when your DLL has just been loaded, and when it&#8217;s about to be unloaded. What better place to add all that expensive, complicated initialisation&#8230;? STOP! WAIT! Before you add anything in <code>DllMain</code>, make sure you understand what state the process will be in when it gets called. Once you know that, you may well change your mind&#8230;<br />
<span id="more-554"></span><br />
Firstly, take a look at <a href="http://www.microsoft.com/whdc/driver/kernel/DLL_bestprac.mspx">this page</a>. It does a pretty good job of ramming home the point that there&#8217;s very little that it&#8217;s safe to do in <code>DllMain</code>. Essentially this is because while the function&#8217;s being called, the OS is holding a process-wide lock that isn&#8217;t re-entrant. As such, if you do anything that causes a DLL to be loaded, a deadlock may occur. There are many, many things that may have a side-effect of loading a DLL; calling COM functions, creating threads etc.</p>
<p>This is such a common source of bugs, and such an important requirement, that from Vista onwards Microsoft introduced a new set of functions in the Windows API explicitly to support it: <a href="http://msdn.microsoft.com/en-us/library/aa363808(VS.85).aspx">One-Time Initialization</a>.</p>
<p>And even if you get away with doing naughty things in <code>DllMain</code> now, don&#8217;t think that it&#8217;ll stay that way forever. We got away with it for years, then when .NET came along it introduced all sorts of additional correctness checks. For instance, the Managed Debugging Assistant (MDA) in Visual Studio will shout loudly should you attempt to run managed code during <code>DllMain</code>.<br />
<code><br />
Managed Debugging Assistant 'LoaderLock' has detected a problem in 'C:\YourApp.vshost.exe'.<br />
Additional Information: Attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang.<br />
</code><br />
And it&#8217;s easier than you think to do so. For example, calling something as innocuous as <code>GetWindowText</code> can result in managed code being run. </p>
<p>How can you get around this?</p>
<p>One of the approaches I&#8217;ve used has been to make use of Win32 asynchronous procedure calls. Specifically you can call <a href="http://msdn.microsoft.com/en-us/library/ms684954(VS.85).aspx">QueueUserAPC</a> to add a function to the queue, and this can contain the initialisation you would&#8217;ve otherwise done in <code>DllMain</code>. </p>
<p>However there is significant gotcha regarding use of APCs: your function will not be called until the thread is in an &#8220;alertable wait state&#8221;. This means you (or some other code on the thread) need to call an alertable wait function such as <a href="http://msdn.microsoft.com/en-us/library/ms686307(VS.85).aspx"><code>SleepEx</code></a>, <a href="http://msdn.microsoft.com/en-us/library/ms687036(VS.85).aspx"><code>WaitForSingleObjectEx</code></a> and specify TRUE for the alertable parameter. </p>
<p>Once your APC is getting called successfully you&#8217;ll be in much better place; your code will be executed outside of the scope of the dreaded OS loader lock and you&#8217;ll be doing things by the book, hopefully avoiding all the potential pitfalls that lie in wait within <code>DllMain</code>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/12/03/dont-do-anything-in-dllmain-please/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>5</slash:comments>
		</item>
		<item>
		<title>Finding the largest free block of address space</title>
		<link>http://www.voyce.com/index.php/2009/08/21/largest-free-block-of-address-space/</link>
		<comments>http://www.voyce.com/index.php/2009/08/21/largest-free-block-of-address-space/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 20:57:12 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[WinDbg]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[address space]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[perfmon]]></category>
		<category><![CDATA[private bytes]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=258</guid>
		<description><![CDATA[I&#8217;ve been seeing problems recently with fragmented virtual address space. During the lifetime of a process, bits and pieces of memory are allocated throughout the 2GB 32-bit address space to such an extent that large contiguous blocks of free space are no longer available. If anything subsequently requires a large block of memory (like, for [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://72.47.193.211/wp-content/uploads/2009/08/buildings_small.png"><img src="http://72.47.193.211/wp-content/uploads/2009/08/buildings_small.png" alt="Buildings" title="Buildings" width="100" height="100" class="alignleft size-full wp-image-268" /></a>I&#8217;ve been seeing problems recently with fragmented virtual address space. During the lifetime of a process, bits and pieces of memory are allocated throughout the 2GB 32-bit address space to such an extent that large contiguous blocks of free space are no longer available. If anything subsequently requires a large block of memory (like, for instance, a somewhat out-of-date version of the GHC runtime), it will fail to get it.</p>
<p>It&#8217;s obvious looking at the output from <a href="http://www.voyce.com/index.php/2009/07/28/diagnosing-out-of-memory-errors-with-vmmap/">VMmap</a> or windbg&#8217;s <code>!address</code> command what the largest contiguous block is, e.g.</p>
<pre>
0:008> !address -summary
....
Largest free region: Base 07300000 - Size 63ed0000 (1637184 KB)
</pre>
<p>But what if you need that number in order to make a decision at run-time? For instance, to decide whether your process is in a fit state to continue, or if it should instead commit <a href="http://en.wikipedia.org/wiki/Seppuku">hara-kiri</a>. In that case, you need to access the information programmatically. That&#8217;s where the immensely useful <a href="http://msdn.microsoft.com/en-us/library/aa366907(VS.85).aspx">VirtualQueryEx</a> function comes in&#8230;<br />
<span id="more-258"></span><br />
VirtualQueryEx gives you information on a single page of your virtual address space at a time. Pages size are dependent on the architecture and OS, but if you just want to iterate over all of them, you don&#8217;t need to add any special handling; the function returns the size of the page in an element of the <a href="http://msdn.microsoft.com/en-us/library/aa366775(VS.85).aspx">MEMORY_BASIC_INFORMATION</a> structure, so you can simply move to the &#8216;next&#8217; page regardless of size.</p>
<p>If you&#8217;re interested in free space, you&#8217;ll need to find all the pages that have a state of MEM_FREE (0&#215;10000), and that&#8217;s pretty much all there is to it. By keeping track of how much space falls into a continuous range of MEM_FREE pages you can get to the number reported by VMmap and <code>!address</code>.</p>
<p>Here&#8217;s some C++ code that returns the address of the largest free contiguous block in <code>largestFreestart</code and the size in <code>largestFree</code>. Enjoy!</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">	MEMORY_BASIC_INFORMATION mbi<span style="color: #008080;">;</span>
	DWORD start <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
	<span style="color: #0000ff;">bool</span> recording <span style="color: #000080;">=</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span>
	DWORD freestart <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span>, largestFreestart <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
	__int64 <span style="color: #0000dd;">free</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span>, largestFree <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
	<span style="color: #0000ff;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">true</span><span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		SIZE_T s <span style="color: #000080;">=</span> VirtualQueryEx<span style="color: #008000;">&#40;</span>hproc, <span style="color: #0000ff;">reinterpret_cast</span><span style="color: #000080;">&lt;</span>lpvoid<span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>start<span style="color: #008000;">&#41;</span>, <span style="color: #000040;">&amp;</span>mbi, <span style="color: #0000dd;">sizeof</span><span style="color: #008000;">&#40;</span>mbi<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
		<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>s <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color: #0000dd;">sizeof</span><span style="color: #008000;">&#40;</span>mbi<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>GetLastError<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">!</span><span style="color: #000080;">=</span> ERROR_INVALID_PARAMETER<span style="color: #008000;">&#41;</span>
				<span style="color: #0000ff;">return</span> ReportError<span style="color: #008000;">&#40;</span>GetLastError<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, _T<span style="color: #008000;">&#40;</span><span style="color: #FF0000;">&quot;Failed to VirtualQueryEx at %08x&quot;</span><span style="color: #008000;">&#41;</span>, start<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
			<span style="color: #0000ff;">else</span>
				<span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
		<span style="color: #008000;">&#125;</span>
		<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>mbi.<span style="color: #007788;">State</span> <span style="color: #000080;">==</span> MEM_FREE<span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #000040;">!</span>recording<span style="color: #008000;">&#41;</span>
				freestart <span style="color: #000080;">=</span> start<span style="color: #008080;">;</span>
			<span style="color: #0000dd;">free</span> <span style="color: #000040;">+</span><span style="color: #000080;">=</span> mbi.<span style="color: #007788;">RegionSize</span><span style="color: #008080;">;</span>
			recording <span style="color: #000080;">=</span> <span style="color: #0000ff;">true</span><span style="color: #008080;">;</span>
		<span style="color: #008000;">&#125;</span>
		<span style="color: #0000ff;">else</span>
		<span style="color: #008000;">&#123;</span>
			<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>recording<span style="color: #008000;">&#41;</span>
			<span style="color: #008000;">&#123;</span>
				<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0000dd;">free</span> <span style="color: #000080;">&gt;</span> largestFree<span style="color: #008000;">&#41;</span>
				<span style="color: #008000;">&#123;</span>
					largestFree <span style="color: #000080;">=</span> <span style="color: #0000dd;">free</span><span style="color: #008080;">;</span>
					largestFreestart <span style="color: #000080;">=</span> freestart<span style="color: #008080;">;</span>
				<span style="color: #008000;">&#125;</span>
			<span style="color: #008000;">&#125;</span>
			<span style="color: #0000dd;">free</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
			recording <span style="color: #000080;">=</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span>
		<span style="color: #008000;">&#125;</span>
		start <span style="color: #000040;">+</span><span style="color: #000080;">=</span> mbi.<span style="color: #007788;">RegionSize</span><span style="color: #008080;">;</span>
	<span style="color: #008000;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/08/21/largest-free-block-of-address-space/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

