<?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; win32</title>
	<atom:link href="http://www.voyce.com/index.php/tag/win32/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>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>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>3</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>The 7 signs your UI was created by a programmer</title>
		<link>http://www.voyce.com/index.php/2009/09/14/the-7-signs-your-ui-was-created-by-a-programmer/</link>
		<comments>http://www.voyce.com/index.php/2009/09/14/the-7-signs-your-ui-was-created-by-a-programmer/#comments</comments>
		<pubDate>Mon, 14 Sep 2009 22:57:35 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Excel]]></category>
		<category><![CDATA[Rant]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Usability]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=344</guid>
		<description><![CDATA[Programmers are notoriously bad at creating good user interfaces. How can you tell if your app was designed by a programmer? (Hint: it's easy).]]></description>
			<content:encoded><![CDATA[<p>Do you suspect a programmer may have put together the terrible user interface on that &#8220;enterprise&#8221; software you&#8217;re forced to use every day? There are some give-away indicators. Look out for them in your software, hunt down the developer and force them to read <a href="http://www.amazon.com/gp/product/0470084111?ie=UTF8&#038;tag=wwwvoycecom-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0470084111">a book about user interface design</a><img src="http://www.assoc-amazon.com/e/ir?t=wwwvoycecom-20&#038;l=as2&#038;o=1&#038;a=0470084111" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />. If you&#8217;re suitably senior, force them to a) improve it, or even better b) get someone with real UI experience to fix it.</p>
<p><b>1. Exclamation marks in dialog box messages</b><br />
Look, it&#8217;s probably the 50th time I&#8217;ve seen this message today. The fact that this application &#8220;Cannot connect to database!&#8221; is no longer a surprise. You may have noticed that most professional software uses a neutral tone for its communication with the user. Try that. Also:<br />
<b>1a. Double negatives in confirmation dialogs</b><br />
&#8220;Are you sure you don&#8217;t want to lose your changes?&#8221; Err&#8230; what? No. I mean YES. Oh sh*t. Any dialog that requires you to stop and try to parse the question in order to work out if you&#8217;re about to destroy several hours of work is not doing its job. It&#8217;s getting in the way of you doing your job. In fact, convoluted messages are such a serious issue that Microsoft even tried to help developers to help their users by introducing a whole new kind of dialog box in Vista: the <a href="http://msdn.microsoft.com/en-us/library/aa511269(loband).aspx#questionDialogsLinks">question/task dialog</a>. Good luck with that.</p>
<p><b>2. No tab ordering defined\mouse only navigation</b><br />
Because no-one&#8217;s ever going to use the keyboard to navigate the zillion controls in your data entry app, are they? This one actually surprises me, because I&#8217;d have thought that developers would&#8217;ve needed to navigate quickly through the application while they&#8217;re writing it. Well, that doesn&#8217;t seem to be the case. Pretty much all commercial apps are good counter examples. I don&#8217;t mean to hold up Microsoft Office as a paragon of UI virtue, but they definitely do the &#8220;alternate way of navigating everything&#8221; thing well. Everything you need can be reached by both keyboard and mouse. Unplug your mouse and try that with your favourite piece of in-house software and see how you get on.</p>
<p><a href="http://72.47.193.211/wp-content/uploads/2009/09/groups.png"><img src="http://72.47.193.211/wp-content/uploads/2009/09/groups.png" alt="groups" title="groups" width="360" height="327" class="alignleft size-full wp-image-358" /></a><b>3. Group boxes around everything</b><br />
This is a bit of a WinForms specific one. The clue is in the name: group boxes are for <i>grouping</i> logically related controls, not for providing a kewl recessed border around <i>every single one</i> of the controls in your dialog. Don&#8217;t kid yourself that this is doing anything other than using up some valuable screen real estate. (See if you can spot another pet peeve in the example dialog, too).</p>
<p><a href="http://72.47.193.211/wp-content/uploads/2009/09/icon_editor.png"><img src="http://72.47.193.211/wp-content/uploads/2009/09/icon_editor.png" alt="icon_editor" title="icon_editor" width="128" height="128" class="alignleft size-full wp-image-361" /></a><b>4. Icons created in the IDE</b><br />
Look, Visual Studio&#8217;s a really good integrated development environment, but it ain&#8217;t no Photoshop. Don&#8217;t try and use it to create icons. And while you&#8217;re at it, please don&#8217;t make icons consisting solely of the name of your application (inevitably an acronym) in pixel font and primary colours. Oh, and don&#8217;t just steal various icons from another application, unless you&#8217;re going to steal the whole lot; one of the key visual aspects of a good UI is consistency. Mixing your hand-drawn 4-bit icons with the glorious 32-bit shiny ones you borrowed is going to be jarring. In fact, why not go the whole way and get someone who can actually draw to create your icons for you? After all, you wouldn&#8217;t have someone who wasn&#8217;t a programmer writing the code, would you&#8230;?</p>
<p><b>5. Data grids</b><br />
Otherwise known as the &#8220;Excel is the pinnacle of user interface design&#8221; disease. Break the habit. Generally, the more types of controls that are embedded in your grid, the less likely that it&#8217;s the right kind of interface paradigm. Yeah, I&#8217;m looking at you, person embedding a calendar control, drop down box, graph, slider and checkbox in each row of a data grid. And whatever your 3rd-party grid provider of choice says, it&#8217;s not going to do screen redraw performance any good, either.</p>
<p><b>6. Not implemented message boxes</b><br />
Ahh, the GUI equivalent of source code TODO comments. Of course, it&#8217;s an in-house software give-away; no commercial (desktop) software would be brazen enough to ship with bits of functionality dangling from the stumps of buttons and menu items. Would it? Feel free to provide counter-examples if you have them.</p>
<p><a href="http://72.47.193.211/wp-content/uploads/2009/09/dialog_dialog.png"><img src="http://www.voyce.com/wp-content/uploads/2009/09/dialog_dialog-300x114.png" alt="dialog_dialog" title="dialog_dialog" width="300" height="114" class="alignright size-medium wp-image-365" /></a><b>7. Excessive use of dialog boxes</b><br />
Warning: dialog boxes are considered harmful (to usability). They&#8217;re the equivalent of restraining your user by force and preventing her from moving until she answers your question. That might be OK for matters of life or death (i.e. data loss), but not otherwise. Every time you find yourself about to add a new message box, stop, take a deep breath and consider whether it&#8217;s really necessary.</p>
<p>So, if you&#8217;re a victim or one, many, or all of these user interface faux pas, all I can say is: sorry. I&#8217;ve been responsible for doing at least one of these things myself over the years. Consider this post repentance for my user interface sins.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/09/14/the-7-signs-your-ui-was-created-by-a-programmer/feed/</wfw:commentRss>
		<slash:comments>43</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>
		<item>
		<title>Diagnosing out of memory errors with VMMap</title>
		<link>http://www.voyce.com/index.php/2009/07/28/diagnosing-out-of-memory-errors-with-vmmap/</link>
		<comments>http://www.voyce.com/index.php/2009/07/28/diagnosing-out-of-memory-errors-with-vmmap/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 22:38:19 +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[memory]]></category>
		<category><![CDATA[private bytes]]></category>
		<category><![CDATA[VMMap]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=216</guid>
		<description><![CDATA[VMMap is a new tool from Mark Russinovich et al that's very useful for diagnosing virtual memory/address space exhaustion issues. I describe it here, and give some information that should help you interpret what it reports.]]></description>
			<content:encoded><![CDATA[<p>The other day a colleague pointed me to a new tool from Mark Russinovich et al (ex-SysInternals) that turns out to be very useful for diagnosing virtual memory/address space exhaustion issues. I thought I&#8217;d describe it here, and give some &#8211; hopefully useful &#8211; extra information on what it reports.</p>
<p>(I had problems with WordPress choking on this long post, so I&#8217;ve split it into 2 parts. This the first part, the second part is <a href="http://www.voyce.com/index.php/2009/07/29/diagnosing-out-of-memory-errors-with-vmmap-part-2/">here</a>).</p>
<p><span id="more-216"></span><br />
First things first: you can download it from <a href="http://technet.microsoft.com/en-us/sysinternals/dd535533.aspx">here</a>.</p>
<h2>Using VMMap</h2>
<p>VMMap graphically displays the contents of your processes&#8217; virtual memory, which each type of memory colour coded. This means you can quickly get an idea of how all of your valuable 2GB address space is being used.</p>
<p>At this point it&#8217;s worth pointing out that this article refers to the 32 bit Windows XP platform only, as that&#8217;s what I use on a day-to-day basis. Moving to a 64 bit address space makes it so large that exhaustion of a process&#8217; address space is pretty damn unlikely, discounting your application doing something pathological.</p>
<p><div id="attachment_219" class="wp-caption alignleft" style="width: 310px"><a href="http://72.47.193.211/wp-content/uploads/2009/07/overview.png"><img src="http://www.voyce.com/wp-content/uploads/2009/07/overview-300x99.png" alt="VMMap top pane" title="VMMap top pane" width="300" height="99" class="size-medium wp-image-219" /></a><p class="wp-caption-text">VMMap top pane</p></div> Before digging in to the different types of allocation, you can quickly get a good overview using the top part of the window.<br clear="all"/>The top bar, Virtual Memory Summary (5040K in this example), corresponds to the Committed memory column and the Working Set summary bar (1140K) below it corresponds to the Total WS column.</p>
<p>The number in the bottom left in the largest free block of address space. It&#8217;s the same number as reported by <code>!address -summary</code> in WinDbg. See the post <a href="http://www.voyce.com/index.php/2009/08/21/largest-free-block-of-address-space/">here</a> if you want to calculate it programmatically. If this number is small (less than 64MB) you&#8217;ll probably have out of memory issues, see below for more details.</p>
<p><b>Note:</b> Generally the working set size is NOT the important number here; it&#8217;s a common mistake that people make when looking at memory usage figures in something like Task Manager. The working set size is merely an indication of the amount of virtual memory that has recently been accessed and it&#8217;s entirely possible to make the WS size number plummet by explicitly &#8220;flushing&#8221; the working set. You can do this by, for example, minimising a GUI application. As such, this is really not the number you want to be tracking. Instead, look at the Private Bytes or Virtual Memory Size counter in perfmon.</p>
<p>But back to VMMap. There are various different types of allocation reported. I&#8217;ll describe some of the most interesting ones:</p>
<h3>Image</h3>
<p>A DLL or other executable file, as typically loaded by <code>LoadLibraryEx</code>. You&#8217;ll see the protection is Execute/Copy on Write; this is the standard for executables, where the OS will share the memory between processes unless they modify it &#8211; which is very rare.</p>
<p>You may also see the same file loaded as a mapped image. For instance, when using a COM server that contains an embedded type library resource, it will be loaded in both ways; once as an executable using <code>LoadLibrary</code> and once as a mapped file using <code>LoadTypeLib</code>. You may also notice that non-ngen&#8217;d .NET images are mapped <b>twice</b>. This appears to be a bug that Microsoft are aware of, there&#8217;s a <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=467560">bug</a> logged in Connect for it.</p>
<p>You can expand the image entry to see the size of the image sections, the file header, code (.text), resources (.rsrc) and relocations (.reloc) for example.</p>
<h3>Mapped file</h3>
<p>These are typically data files loaded using <code>CreateFileMapping</code>. Depending on how the mapping was created (whether an explicit maximum size was specified), either the whole of the file or some small section of it will be mapped. Of course, the whole point of memory mapped files is to be able to get access to sections of a file without having to load it all, so the chances are that only small files will be mapped in their entirety.</p>
<p>Memory mapped files are often used to share data between processes, so you may find that things put on the clipboard may appear as mapped address space, albeit transiently. This is especially obvious in Microsoft Office apps like Excel.</p>
<h3>Heaps</h3>
<p>This is the meta-data associated with each heap in the process. The actual allocations from the heap are stored separately in the address space (more on that later, see Private Data).</p>
<p>Some people are surprised that there can be multiple heaps in a single process, but it&#8217;s actually quite common practice in unmanaged code, especially where there are specific memory management requirements. MSXML is a widely used example of this; it does it&#8217;s own garbage collection using it&#8217;s own dedicated heaps.</p>
<p>There is always a default heap created by the loader during process creation, and others are created explicitly using <code>HeapCreate</code>. The address of the heap displayed by VMMap can be used with the WinDbg <code>!heap</code> command to delve more deeply into it&#8217;s contents and structure. For instance, <code>!heap -m</code> will display it&#8217;s segment details.</p>
<h3>Managed heap</h3>
<p>Obviously this is only relevant for applications using .NET &#8211; managed apps themselves or unmanaged apps that implicitly load .NET assemblies in some other way, say, via COM. The number displayed is the sum of the generation 0, 1, 2 and large object heap sizes.</p>
<h3>Thread stack</h3>
<p>Each thread in the OS has a stack that can grow to 1MB by default (although this is configurable at link time, and controllable programmatically). It starts as a block of uncommitted reserved memory, with the used space committed at the bottom, and a guard block that is used to determine when to expand the block downwards. VMMap helpfully displays the thread ID in the stack space row.</p>
<p>Remember that each thread will have it&#8217;s own stack space, so spinning up threads is not free in terms of virtual memory use. See <a href="http://msdn.microsoft.com/en-us/library/ms686774(VS.85).aspx">here</a> for more details on thread stack space.</p>
<p>Read on <a href="http://www.voyce.com/index.php/2009/07/29/diagnosing-out-of-memory-errors-with-vmmap-part-2/">here</a> for more&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2009/07/28/diagnosing-out-of-memory-errors-with-vmmap/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Programmatically checking memory usage</title>
		<link>http://www.voyce.com/index.php/2008/06/20/programmatically-checking-memory-usage/</link>
		<comments>http://www.voyce.com/index.php/2008/06/20/programmatically-checking-memory-usage/#comments</comments>
		<pubDate>Fri, 20 Jun 2008 07:09:10 +0000</pubDate>
		<dc:creator>ian</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[pdh]]></category>
		<category><![CDATA[perfmon]]></category>
		<category><![CDATA[private bytes]]></category>
		<category><![CDATA[win32]]></category>

		<guid isPermaLink="false">http://www.voyce.com/?p=31</guid>
		<description><![CDATA[One of the things that&#8217;s useful in a pre-release check is do a regression test on the memory usage of your unmanaged functions. This should help to ensure that the fantastic new data structure you introduced doesn&#8217;t cost too much in additional storage for the order-of-magnitude performance improvement you were boasting about.
Like most of my posts, this assumes that [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things that&#8217;s useful in a pre-release check is do a regression test on the memory usage of your unmanaged functions. This should help to ensure that the fantastic new data structure you introduced doesn&#8217;t cost <em>too</em> much in additional storage for the order-of-magnitude performance improvement you were boasting about.</p>
<p>Like most of my posts, this assumes that it&#8217;s not feasible to go through all your source code, and say, replace all instances of new with a version that tracks usage (the approach used by the debug CRT). As well as being logistically infeasible, this also tends to miss allocations that don&#8217;t go via new, for example, direct calls to HeapAlloc.</p>
<p><span id="more-31"></span>In the past, I&#8217;ve seen some code trying to use the <a href="http://msdn.microsoft.com/en-us/library/aa366781(VS.85).aspx">Win32 heap functions</a> to try and find out the amount of memory allocated by the process. It used GetProcessHeaps, HeapWalk and HeapSize to sum all the block sizes and get an overall memory in use figure, but in my experience it was extremely slow and unreliable.</p>
<p>What was really required was something that gave a figure similar to the &#8220;private bytes&#8221; counter in perfmon. If you didn&#8217;t know, this is the counter you need to be watching if you&#8217;re looking for memory leaks in a process. For goodness sake don&#8217;t use the &#8220;Mem Usage&#8221; column in Task Manager; this is in fact (almost) the working set size and it doesn&#8217;t correlate exactly with memory explicitly allocated by the process. It includes additional things including space occupied by the loaded DLLs. Also, the working set will shrink if the app is paged out, although it still has the memory allocated. To see an example of this in action, open Excel and a large spreadsheet, calc it, look in Task manager and you&#8217;ll see a large number (if not, you&#8217;re obviously not looking at a <em>real</em> spreadsheet). Then minimise the Excel window. You&#8217;ll see the mem usage value plummet as the working set is &#8221;trimmed&#8221; &#8211; probably by a call to <a href="http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx">SetProcessWorkingSetSize</a>. The OS does this because it expects the app won&#8217;t be being used, so it makes sense to free up physical memory for use by other processes.</p>
<p>So essentially what I want to do is get the perfmon &#8220;private bytes&#8221; value programmatically as my app is running, and this can be achieved using the Performance Data Helper (PDH) library. It provides an API to access the performance counters in a similar way to the perfmon GUI.</p>
<p>It uses the concept of &#8220;queries&#8221;; you create a query, add a counter to it, then collect the query data as required (not forgetting to remove the counter and close the query when you&#8217;re done).</p>
<p>The first thing to do is open the query:</p>
<div style="font-family: Lucida Sans Typewriter; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">    PDH_STATUS status = PdhOpenQuery(NULL, 0, &amp;hquery);</p>
<p style="margin: 0px;">    <span style="color: #0000ff;">if</span> (status != ERROR_SUCCESS)</p>
<p style="margin: 0px;">        <span style="color: #0000ff;">return</span> status;</p>
</div>
<p> </p>
<p>Then add the required counters (this code assumes you&#8217;re looking at a process on the current machine):</p>
<div style="font-family: Lucida Sans Typewriter; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">    status = PdhAddCounter(hquery, _T(<span style="color: #800000;">&#8220;\\\\.\\Process(processname)\\Private Bytes&#8221;</span>), 0, &amp;hcounter);</p>
<p style="margin: 0px;">    <span style="color: #0000ff;">if</span> (status != ERROR_SUCCESS)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        PdhCloseQuery(hquery);</p>
<p style="margin: 0px;">        <span style="color: #0000ff;">return</span> status;</p>
<p style="margin: 0px;">    }</p>
</div>
<p>At this point you&#8217;re ready to start polling for updates. At periodic intervals you can collect the query data and do with it what you will:</p>
<div style="font-family: Lucida Sans Typewriter; font-size: 10pt; color: black; background: white;">
<p style="margin: 0px;">    PDH_STATUS status = PdhCollectQueryData(hquery);</p>
<p style="margin: 0px;">    <span style="color: #0000ff;">if</span> (status == ERROR_SUCCESS)</p>
<p style="margin: 0px;">    {</p>
<p style="margin: 0px;">        PDH_RAW_COUNTER value;</p>
<p style="margin: 0px;">        DWORD dwType;</p>
<p style="margin: 0px;">        status = PdhGetRawCounterValue(hcounter, &amp;dwType, &amp;value);</p>
<p style="margin: 0px;">        <span style="color: #0000ff;">if</span> (status == ERROR_SUCCESS)</p>
<p style="margin: 0px;">        {</p>
<p style="margin: 0px;">            printf(<span style="color: #800000;">&#8220;%lld %lld %s\n&#8221;</span>, value.TimeStamp, value.FirstValue, sz);</p>
<p style="margin: 0px;">        }</p>
<p style="margin: 0px;">    }</p>
</div>
<p>Luckily for the Private Bytes counter we&#8217;ve got the simplest type of counter to &#8216;decode&#8217;; a raw counter value, essentially just a number. We don&#8217;t need to do any further manipulation on it to get the information we need, like having to divide by some frequency.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.voyce.com/index.php/2008/06/20/programmatically-checking-memory-usage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

