<?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>tdistler.com &#187; C++</title>
	<atom:link href="http://tdistler.com/tag/c/feed" rel="self" type="application/rss+xml" />
	<link>http://tdistler.com</link>
	<description>&#34;To err is human, but to really foul things up you need a computer.”</description>
	<lastBuildDate>Tue, 06 Dec 2011 20:46:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Eubonicode++: Hackin C++ Gangsta Style</title>
		<link>http://tdistler.com/2011/12/03/eubonicode-hackin-c-gangsta-style</link>
		<comments>http://tdistler.com/2011/12/03/eubonicode-hackin-c-gangsta-style#comments</comments>
		<pubDate>Sat, 03 Dec 2011 16:00:02 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[funny]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=1077</guid>
		<description><![CDATA["Foshizzle" is a modified version of the Clang compiler which supports Eubonicode++ (an alternate C++ syntax). Foshizzle supports all the existing features of Clang, but with extensions to more fully express your gansta style. All the regular C++ syntax still works, but you can now substitute Eubonicode++ keywords and operators.]]></description>
			<content:encoded><![CDATA[<p><a href="http://tdistler.com/wp-content/uploads/2011/12/Bjarne_foshizzle.jpg"><img class="alignright size-thumbnail wp-image-1078" title="A small part of me died doing this to Bjarne, but I couldn't resist." src="http://tdistler.com/wp-content/uploads/2011/12/Bjarne_foshizzle-150x150.jpg" alt="A little part of me died doing this to Bjarne, but I couldn't resist." width="150" height="150" /></a></p>
<p>&#8220;Foshizzle&#8221; is a modified version of the <a title="Clang Compiler" href="http://clang.llvm.org/" target="_blank">Clang</a> compiler which supports Eubonicode++ (an alternate C++ syntax). Foshizzle supports all the existing features of Clang, but with extensions to more fully express your gansta style. All the regular C++ syntax still works, but you can now substitute Eubonicode++ keywords and operators (see below).</p>
<p>Here&#8217;s a sample method that calculates factorials (Note: the semicolons can be replaced with a certain expletive):</p>
<pre>int factorialz(int n)
{
    int rezult be 1;
    slongas (n bepimpin 0)
    {
        rezult be rezult dimes n;
        dissin n;
    }
    putou rezult;
}</pre>
<p>&nbsp;</p>
<p>I can&#8217;t take all the credit. I was inspired by the Iowa State students that first created Eubonicode (webpage no longer available).</p>
<p>Here are my Clang modifications:<a title="Eubonicode++ Clang modifications" href="http://tdistler.com/media/code/eubonicode/ebpp-clang30rc4.patch" target="_blank"> ebpp-clang30rc4.patch</a></p>
<p>Build instructions are near the end of this post.<span id="more-1077"></span></p>
<h2>How It Happened</h2>
<p>I periodically venture off into the h4x0r wilderness and pour myself into some random project. It always starts out innocently enough, but the project soon takes on a life of it’s own. This time was no different&#8230; except it happened over Thanksgiving (much to my wife’s chagrin).</p>
<p>Being the charismatic socialite that I am (sarcasm), I was digging through the C++11 spec on Thanksgiving. What struck me was how much of my language design course I had forgotten, and it really bugged me. It&#8217;s one of those required courses in the CompSci graduate program that I loathed having to take, but turned out to be invaluable (don’t get me started on the database and UI design courses&#8230; blah).</p>
<p>Long story less long, I started refreshing on compilers (<a title="Rich Programmer Food" href="http://steve-yegge.blogspot.com/2007/06/rich-programmer-food.html" target="_blank">read this</a> for inspiration). I’d heard about Clang and <a title="LLVM" href="http://llvm.org/" target="_blank">LLVM</a> awhile ago, and I remembered their focus on modularity, maintainability, and all sorts of other *ability’s. I figured it&#8217;d be a good place to start, so I download the source code and dug through it (watch <a title="Clang Video" href="http://clang.llvm.org/clang_video-05-25-2007.html" target="_blank">this video</a> for background on Clang).</p>
<p>Stepping through Clang in a debugger sounded like a great way to start, but I quickly had mental stack overflow through the recursive parsing code. Okay, time for plan B. Common wisdom says that a good way to learn a piece of code is to try and fix a bug. So I went to the Clang bug list looking for a starter task, but all the “interesting” tasks were way too large in scope for a Clang newb like me.</p>
<p>Time to invent plan C: make a small tweak to the language and see if I can get it working. I remembered a few years ago that some students from Iowa State built an Eubonicode compiler for a language class they had. It got quite a few laughs around the office and was always wishing for a working compiler. So I decided take their idea and replace ‘<code>while</code>’ with ‘<code>slongas</code>’&#8230; and an hour later I had it working (which is testament to the readability of the Clang code&#8230; it’s very well commented).</p>
<p>Not satisfied to stop there, I moved on to other keywords&#8230; simple, once you get comfortable with how the code’s laid out. &#8220;What about operators and punctuators?&#8221;, I wondered. After a few failed attempts, it dawned on me that C++ has aliases for operators (‘<code>and_eq</code>’ can be used in place of ‘<code>&amp;=</code>’, etc). Instead of heavily modifying the parser/lexer, I started looking for how Clang handled these aliases&#8230; maybe I could just add some more. Turns out, it fairly simple to add new aliases, so ‘<code>==</code>’ got overloaded with ‘<code>sameas</code>’, ‘<code>!=</code>’ got overloaded with ‘<code>aint</code>’, etc&#8230; and it worked! Sweet!</p>
<p>After all that, I dug a little into the preprocessor and figured out how to support ‘<code>#mahomie</code>’ in place of ‘<code>#include</code>’. Simple enough. I dug a little into the build stuff and changed the name from ‘clang’ to ‘foshizzle’&#8230; cool. I little bit of frustration later, and I had it recognizing ‘*.opp’ and ‘*.ho’ as source and header files, respectively.</p>
<p>Three days after I started, I had a fully functional Eubonicode++ compiler and a lot deeper understanding of how a production C++ compiler works. I can’t stress enough that this project would never have happened if the Clang code wasn’t written so well. Kudos to the Clang team.</p>
<p>I really enjoyed this project, and I hope you get half the fun out of it I did. Next time you have a coding task, consider adding a litta gansta sizzle <img src='http://tdistler.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h2>C++ To Eubonicode++ Mapping</h2>
<p>&nbsp;</p>
<table style="text-align: center;" width="400" border="0">
<tbody>
<tr>
<th>C++</th>
<th>Eubonicode++</th>
<th>|</th>
<th>C++</th>
<th>Eubonicode++</th>
</tr>
<tr>
<td><code>#include</code></td>
<td><code>#mahomie</code></td>
<td>|</td>
<td><code>switch</code></td>
<td><code>whatchugondo</code></td>
</tr>
<tr>
<td><code>break</code></td>
<td><code>bustanut</code></td>
<td>|</td>
<td><code>this</code></td>
<td><code>dis</code></td>
</tr>
<tr>
<td><code>case</code></td>
<td><code>ifa</code></td>
<td>|</td>
<td><code>throw</code></td>
<td><code>throz</code></td>
</tr>
<tr>
<td><code>catch</code></td>
<td><code>wrekdit</code></td>
<td>|</td>
<td><code>true</code></td>
<td><code>tru</code></td>
</tr>
<tr>
<td><code>char</code></td>
<td><code>alphabizzle</code></td>
<td>|</td>
<td><code>try</code></td>
<td><code>checkit</code></td>
</tr>
<tr>
<td><code>class</code></td>
<td><code>claz</code></td>
<td>|</td>
<td><code>typedef</code></td>
<td><code>reprezentin</code></td>
</tr>
<tr>
<td><code>const</code></td>
<td><code>foodonchange</code></td>
<td>|</td>
<td><code>using</code></td>
<td><code>uzin</code></td>
</tr>
<tr>
<td><code>continue</code></td>
<td><code>mo</code></td>
<td>|</td>
<td><code>virtual</code></td>
<td><code>frontin</code></td>
</tr>
<tr>
<td><code>delete</code></td>
<td><code>cap</code></td>
<td>|</td>
<td><code>void</code></td>
<td><code>shiznit</code></td>
</tr>
<tr>
<td><code>else</code></td>
<td><code>elz</code></td>
<td>|</td>
<td><code>volatile</code></td>
<td><code>trippin</code></td>
</tr>
<tr>
<td><code>export</code></td>
<td><code>bounce</code></td>
<td>|</td>
<td><code>while</code></td>
<td><code>slongas</code></td>
</tr>
<tr>
<td><code>extern</code></td>
<td><code>othahood</code></td>
<td>|</td>
<td><code>;</code></td>
<td><code>bitch</code> or <code>biatch</code></td>
</tr>
<tr>
<td><code>false</code></td>
<td><code>falz</code></td>
<td>|</td>
<td><code>=</code></td>
<td><code>be</code></td>
</tr>
<tr>
<td><code>float</code></td>
<td><code>flo</code></td>
<td>|</td>
<td><code>==</code></td>
<td><code>sameas</code></td>
</tr>
<tr>
<td><code>for</code></td>
<td><code>fo</code></td>
<td>|</td>
<td><code>!=</code></td>
<td><code>aint</code></td>
</tr>
<tr>
<td><code>friend</code></td>
<td><code>homie</code></td>
<td>|</td>
<td><code>+</code></td>
<td><code>an</code></td>
</tr>
<tr>
<td><code>long</code></td>
<td><code>shlong</code></td>
<td>|</td>
<td><code>-</code></td>
<td><code>widout</code></td>
</tr>
<tr>
<td><code>namespace</code></td>
<td><code>namespaze</code></td>
<td>|</td>
<td><code>*</code></td>
<td><code>dimes</code></td>
</tr>
<tr>
<td><code>new</code></td>
<td><code>makea</code></td>
<td>|</td>
<td><code>/</code></td>
<td><code>videdby</code></td>
</tr>
<tr>
<td><code>private</code></td>
<td><code>nonyobiz</code></td>
<td>|</td>
<td><code>&gt;</code></td>
<td><code>bepimpin</code></td>
</tr>
<tr>
<td><code>protected</code></td>
<td><code>indafamily</code></td>
<td>|</td>
<td><code>&lt;</code></td>
<td><code>fearin</code></td>
</tr>
<tr>
<td><code>public</code></td>
<td><code>tweetdat</code></td>
<td>|</td>
<td><code>++</code></td>
<td><code>propsta</code></td>
</tr>
<tr>
<td><code>return</code></td>
<td><code>putou</code></td>
<td>|</td>
<td><code>--</code></td>
<td><code>dissin</code></td>
</tr>
</tbody>
</table>
<ul>
<li> *.cpp -&gt; *.opp</li>
<li>*.h -&gt; *.ho</li>
</ul>
<p>Many thanks to <a href="https://plus.google.com/s/sean%20tegtmeyer" target="_blank">Sean Tegtmeyer</a> for helping with the syntax definition.</p>
<h2>Building Foshizzle</h2>
<p>I <em>highly</em> suggest building Clang <strong>without</strong> my changes first and verify that you have it working correctly. Then it should be simple to apply my patch and rebuild. I did all my work on Fedora 16, so your mileage may vary on other distros or OSes.</p>
<p><strong>Note</strong>: If you have any problems building LLVM or Clang, please refer to their build page: <a title="Clang: Getting Started" href="http://clang.llvm.org/get_started.html" target="_blank">Getting Started</a></p>
<ol>
<li>Create a new directory (e.g. &#8220;foshizzle&#8221;).</li>
<li>Within the &#8220;foshizzle&#8221; directory, create the following directories: &#8220;build&#8221;, &#8220;src&#8221;, &#8220;install&#8221;</li>
<li>Checkout the LLVM source code into the &#8220;src&#8221; directory:</li>
<ul>
<li><code>svn co http://llvm.org/svn/llvm-project/llvm/tags/RELEASE_30/rc4 ./src</code></li>
</ul>
<li>Create a new directory for the Clang source within the LLVM &#8220;tools&#8221; directory:</li>
<ul>
<li><code>mkdir src/tools/clang</code></li>
</ul>
<li>Checkout the Clang source code into the &#8220;src/tools/clang&#8221; directoy:</li>
<ul>
<li><code>svn co http://llvm.org/svn/llvm-project/cfe/tags/RELEASE_30/rc4 ./src/tools/clang</code></li>
</ul>
<li>Change directories into the &#8220;build&#8221; directory.</li>
<li>Configure the Clang/LLVM build and point it to the &#8220;install&#8221; directory you created earlier:</li>
<ul>
<li><code>../src/configure --prefix=&lt;path&gt;/&lt;to&gt;/&lt;foshizzle&gt;/install</code></li>
</ul>
<li>Build (takes quite a while): <code>make</code></li>
<li>Install: <code>make install</code></li>
<li>Compile some test code to make sure it works: <code>install/bin/clang++ yourtestcode.cpp</code></li>
</ol>
<p><strong>Only</strong> continue on once the unmodified version of Clang is working.</p>
<ol>
<li>Download my patch file: <a href="http://tdistler.com/media/code/eubonicode/ebpp-clang30rc4.patch" target="_blank">ebpp-clang30rc4.patch</a></li>
<li>Change directories to where the Clang source is (src/tools/clang).</li>
<li>Apply the patch: <code>patch -p0 -i ebpp-clang30rc4.patch</code></li>
<li>Change back to the &#8220;build&#8221; directory.</li>
<li>Build: <code>make</code></li>
<li>Install: <code>make install</code></li>
<li>Test: <code>install/bin/foshizzle++ yordopecodez.opp</code></li>
</ol>
<p>You can also build the sample code below.</p>
<h2>Sample Code</h2>
<p><a href="http://tdistler.com/media/code/eubonicode/baseclaz.ho" target="_blank">baseclaz.ho</a>, <a href="http://tdistler.com/media/code/eubonicode/friendclaz.ho" target="_blank">friendclaz.ho</a>, <a href="http://tdistler.com/media/code/eubonicode/main.opp" target="_blank">main.opp</a></p>
<p><strong>Building</strong></p>
<pre>install/bin/foshizzle++ main.opp</pre>
<p>&nbsp;</p>
<p><strong>Program Output</strong></p>
<pre>baseclaz: protected = 1, private = 1
derivedclaz: protected = 0, private = 1
friendclaz: friend private = 0

Factorial(7) = 5040</pre>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2011/12/03/eubonicode-hackin-c-gangsta-style/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding stdint.h to Visual Studio</title>
		<link>http://tdistler.com/2011/11/13/adding-stdint-h-to-visual-studio</link>
		<comments>http://tdistler.com/2011/11/13/adding-stdint-h-to-visual-studio#comments</comments>
		<pubDate>Sun, 13 Nov 2011 13:00:51 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=1066</guid>
		<description><![CDATA[Yes, stdint.h and inttypes.h are missing from Microsoft Visual Studio. As a result, anyone who&#8217;s written cross-platform C\C++ code for Windows has probably seen this error: error C2146: syntax error : missing ';' before identifier 'foo' error C4430: missing type specifier - int assumed. Note: C++ does not support default-int The fact is that Visual [...]]]></description>
			<content:encoded><![CDATA[<p>Yes, <code>stdint.h</code> and <code>inttypes.h</code> are missing from Microsoft Visual Studio. As a result, anyone who&#8217;s written cross-platform C\C++ code for Windows has probably seen this error:</p>
<p><code>error C2146: syntax error : missing ';' before identifier 'foo'<br />
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int</code></p>
<p>The fact is that Visual Studio doesn&#8217;t implement C99&#8230; it implements C89 (for compatibility reasons). So, you don&#8217;t have access to familiar types like:</p>
<ul>
<li><code>int8_t, int16_t, int32_t, int64_t</code></li>
<li><code>uint8_t, uint16_t, uint32_t, uint64_t</code></li>
<li><code>INT8_MIN</code>, <code>INT8_MAX</code>, etc</li>
<li>The <code>fprintf</code> macros <code>PRId32</code>, <code>PRIu32</code>, etc</li>
<li><code>strtoimax()</code>, etc</li>
</ul>
<p>Fortunately, <a href="http://www.chemeris.ru/" target="_blank">Alexander Chemeris</a> has written <a title="Google Code" href="http://code.google.com/p/msinttypes/" target="_blank">msinttypes</a>: an implementation of <code>stdint.h</code> and <code>inttypes.h</code> for Microsoft Visual Studio. It is licensed under the BSD license, so the headers are actually usable commercially (no viral GPL). This following quote probably goes without saying (emphasis mine):</p>
<blockquote><p>Note though, that just adding these headers does <strong>not</strong> make Visual Studio compiler fully C99 compliant.</p></blockquote>
<p>This project has saved me a bunch of unwanted coding. Thanks Alex!</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2011/11/13/adding-stdint-h-to-visual-studio/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C++11: Move Semantics and Rvalue References</title>
		<link>http://tdistler.com/2011/08/18/c11-move-semantics-and-rvalue-references</link>
		<comments>http://tdistler.com/2011/08/18/c11-move-semantics-and-rvalue-references#comments</comments>
		<pubDate>Thu, 18 Aug 2011 15:00:36 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=1017</guid>
		<description><![CDATA[Thomas Becker has a great article explaining C++11&#8242;s rvalue references and how they allow move semantics and perfect forwarding. I particularly liked his summary of the 3 things you need to remember about rvalue references: By overloading a function like this: void foo(X&#38; x); // lvalue reference overload void foo(X&#38;&#38; x); // rvalue reference overload [...]]]></description>
			<content:encoded><![CDATA[<p><a title="Thomas Becker: C++ Rvalue References Explained" href="http://thbecker.net/articles/rvalue_references/section_01.html" target="_blank">Thomas Becker has a great article</a> explaining C++11&#8242;s rvalue references and how they allow move semantics and perfect forwarding.</p>
<p>I particularly liked his summary of the 3 things you need to remember about rvalue references:</p>
<ol>
<li>By overloading a function like this:<br />
<code>
<pre>

void foo(X&amp; x); // lvalue reference overload
void foo(X&amp;&amp; x); // rvalue reference overload
</pre>
<p></code><br />
you can branch at compile time on the condition &#8220;is foo being called on an lvalue or an rvalue?&#8221; The primary (and for all practical purposes, the only) application of that is to overload the copy constructor and copy assignment operator of a class for the sake of implementing move semantics. If and when you do that, make sure to pay attention to exception handling, and use the new noexcept keyword as much as you can.</li>
<li><code>std::move</code> turns its argument into an rvalue.</li>
<li><code>std::forward</code> allows you to achieve perfect forwarding if you use it exactly as shown:<br />
<code>
<pre>

template&lt;typename T, typename Arg&gt;
shared_ptr&lt;T&gt; factory(Arg&amp;&amp; arg)
{
    return shared_ptr&lt;T&gt;(new T(std::forward&lt;Arg&gt;(arg));
}</pre>
<p></code>
</li>
</ol>
<p>I also like his definition of lvalues and rvalues in the <a title="Thomas Becker: Introduction" href="http://thbecker.net/articles/rvalue_references/section_01.html" target="_blank">introduction</a>:</p>
<blockquote><p>The original definition of lvalues and rvalues from the earliest days of C is as follows: An <em>lvalue</em> is an expression <code>e</code> that may appear on the left or on the right hand side of an assignment, whereas an<em>rvalue</em> is an expression that can only appear on the right hand side of an assignment.</p>
<p>In C++, this is still useful as a first, intuitive approach to lvalues and rvalues. <strong>However</strong>, C++ with its user-defined types has introduced some subtleties regarding modifiability and assignability that cause this definition to be incorrect. There is no need for us to go further into this. Here is an alternate definition which, although it can still be argued with, will put you in a position to tackle rvalue references: <em><strong>An lvalue is an expression that refers to a memory location and allows us to take the address of that memory location via the <code>&amp;</code> operator. An rvalue is an expression that is not an lvalue. </strong></em></p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2011/08/18/c11-move-semantics-and-rvalue-references/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CRC32: A Simple C++ Class</title>
		<link>http://tdistler.com/2011/06/22/crc32-a-simple-c-class</link>
		<comments>http://tdistler.com/2011/06/22/crc32-a-simple-c-class#comments</comments>
		<pubDate>Wed, 22 Jun 2011 17:32:51 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=993</guid>
		<description><![CDATA[A simple C++ class for calculating CRC32.]]></description>
			<content:encoded><![CDATA[<p><a title="Wikipedia: Cyclic Redundancy Check" href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check" target="_blank">Cyclic Redundancy Checks</a> are a quick and convenient way to verify if a data set has changed. They are not meant to be &#8220;secure&#8221; like a MD5 or SHA-1, but they offer a very practical solution to most problems. CRC&#8217;s are also useful for verifying if 2 data sets are equal. Here&#8217;s a simple class I use that&#8217;s efficient. Honestly, I don&#8217;t remember what flavor of CRC32 it implements (sorry), but it has always worked for what I&#8217;ve needed. Cheers!</p>
<pre><code>static const uint32_t kCrc32Table[256] = {
    0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
    0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
    0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
    0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
    0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
    0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
    0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
    0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
    0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
    0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
    0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
    0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
    0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
    0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
    0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
    0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
    0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,<span id="more-993"></span>
    0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
    0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
    0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
    0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
    0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
    0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
    0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
    0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
    0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
    0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
    0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
    0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
    0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
    0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
    0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
    0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
    0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
    0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
    0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
    0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
    0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
    0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
    0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
    0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
    0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
    0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
    0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
    0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
    0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
    0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
    0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
    0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
    0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
    0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
    0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
    0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
    0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
    0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
    0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
    0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
    0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
    0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
    0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
    0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
    0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
    0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
    0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
}; // kCrc32Table

class Crc32
{
public:
    Crc32() { Reset(); }
    ~Crc32() throw() {}
    void Reset() { _crc = (uint32_t)~0; }
    void AddData(const uint8_t* pData, const uint32_t length)
    {
        uint8_t* pCur = (uint8_t*)pData;
        uint32_t remaining = length;
        for (; remaining--; ++pCur)
            _crc = ( _crc &gt;&gt; 8 ) ^ kCrc32Table[(_crc ^ *pCur) &amp; 0xff];
    }
    const uint32_t GetCrc32() { return ~_crc; }

private:
    uint32_t _crc;
};

</code></pre>
<p><strong>Note</strong>: I always have <code>uint32_t</code> defined in Windows, so you may have to define it yourself or use the Microsoft intrinsic <code>unsigned __int32</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2011/06/22/crc32-a-simple-c-class/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rendering Video with GDI (Example)</title>
		<link>http://tdistler.com/2011/04/20/rendering-video-with-gdi-example</link>
		<comments>http://tdistler.com/2011/04/20/rendering-video-with-gdi-example#comments</comments>
		<pubDate>Wed, 20 Apr 2011 18:04:25 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[video]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=932</guid>
		<description><![CDATA[Example C++ GDI video window class with text overlay.]]></description>
			<content:encoded><![CDATA[<p><a href="http://tdistler.com/wp-content/uploads/2011/04/video-icon.jpg"><img class="alignright size-thumbnail wp-image-948" title="video-icon" src="http://tdistler.com/wp-content/uploads/2011/04/video-icon-150x150.jpg" alt="" width="150" height="150" /></a>In this post, I outline a basic GDI video window class. GDI is inefficient for rendering video, but it&#8217;s also very convinient when writing simple tools on Windows. I find myself doing it often enough that it makes sense to do a brain-dump here. This is only an outline, but it should get you over the biggest hurdles.</p>
<h4>Outline</h4>
<ol>
<li>Video Window Class Definition</li>
<li>Creating and Destroying the Window</li>
<li>The Window Thread</li>
<li>The Message Pump</li>
<li>Rendering a Video Frame</li>
</ol>
<p>Things to note:</p>
<ul>
<li>You will need a thread in your window class to &#8220;pump&#8221; window events.</li>
<li>GDI does NOT do any color conversion, so you will need to convert each frame into the same format as the display (always RGB, usually 24 or 32 bits).</li>
</ul>
<h4>Video Window Class Definition</h4>
<pre><code>class VideoWindow
{
public:
    ...
private:
    static DWORD _ThreadMain(void*);
    static LRESULT WINAPI _MsgProc(HWND, UINT, WPARAM, LPARAM);

    CRITICAL_SECTION _lok;
    HANDLE _thread;
    HWND _hWnd;
    HDC _hDC;
    HDC _hFrameDC;
    HFONT _hFont;
    int _bpp;   // bit depth
    volatile bool _exit;
    int _x, _y, _w, _h; // Window dimensions
    int _imgWidth, _imgHeight, _imgLength; // Frame dimensions
    unsigned char *_imgBits;
};

</code></pre>
<h4>Creating and Destroying the Window</h4>
<pre><code>void VideoWindow::Create(int x, int y, int w, int h)
{
    EnterCriticalSection(&amp;_lok);
    _x = x;
    _y = y;
    _w = w;
    _h = h;
    _hWnd = 0;
    _exit = false;
    _thread = CreateThread( NULL, NULL, (LPTHREAD_START_ROUTINE)_ThreadMain,
        this, NULL, 0 );
    LeaveCriticalSection(&amp;_lok);

    // Wait for window to be created. Cheap, but it works.
    while (!_hWnd) {
        ::Sleep(100);
    }
}
<span id="more-932"></span>
void VideoWindow::Destroy()
{
    // Safe to call from the destructor.

    EnterCriticalSection(&amp;_lok);
    if(_hWnd)
    {
        _exit = true;
        LeaveCriticalSection(&amp;_lok);
        WaitForSingleObject( _thread, INFINITE );
        CloseHandle(_thread);
        EnterCriticalSection(&amp;_lok);
        DestroyWindow(_hWnd);
        _hWnd = 0;
    }
    if (_hFont) ::DeleteObject(_hFont);
    if (_hFrameDC) ::DeleteDC(_hFrameDC);
    if (_hDC) ::DeleteDC(_hDC);
    LeaveCriticalSection(&amp;_lok);
}

</code></pre>
<h4>The Window Thread</h4>
<pre><code>DWORD VideoWindow::_ThreadMain(void* ctx)
{
    VideoWindow *p = (VideoWindow*)ctx;
    EnterCriticalSection(&amp;p-&gt;_lok);

    LPCSTR className = "VideoWndClass";
    LPCSTR windowName = "MyWindowText";
    WNDCLASSEX wcex = {
        sizeof(WNDCLASSEX),
        CS_OWNDC | CS_HREDRAW | CS_VREDRAW,
        _MsgProc,
        0L,
        0L,
        NULL,
        NULL,
        NULL,
        (HBRUSH)GetStockObject(BLACK_BRUSH),
        NULL,
        className,
        NULL
    };

    RegisterClassEx(&amp;wcex);   

    p-&gt;_hWnd = CreateWindow(className, windowName, WS_OVERLAPPEDWINDOW,
        p-&gt;_x, p-&gt;_y, p-&gt;_w, p-&gt;_h, ::GetDesktopWindow(), NULL, NULL, NULL);

    p-&gt;_hDC = ::GetDC(p-&gt;_hWnd);
    p-&gt;_bpp = ::GetDeviceCaps(p-&gt;_hDC, BITSPIXEL);
    p-&gt;_hFrameDC = ::CreateCompatibleDC(p-&gt;_hDC);

    p-&gt;_hFont = ::CreateFont(18, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,
        ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
        ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "Arial");

    ShowWindow(p-&gt;_hWnd,SW_SHOW);
    UpdateWindow(p-&gt;_hWnd);

    while( !p-&gt;_exit )
    {
        MSG msg;
        if(PeekMessage(&amp;msg,p-&gt;_hWnd,0,0,PM_REMOVE))
        {
            TranslateMessage(&amp;msg);
            DispatchMessage(&amp;msg);
        }

        LeaveCriticalSection(&amp;p-&gt;_lok);
        Sleep(50); // A better way to do this is to use a message
        EnterCriticalSection(&amp;p-&gt;_lok);
    }
    LeaveCriticalSection(&amp;p-&gt;_lok);
    return 0;
}

</code></pre>
<h4>The Message Pump</h4>
<pre><code>LRESULT WINAPI VideoWindow::_MsgProc(HWND hWnd, UINT msg, WPARAM w, LPARAM l)
{
    if (msg == WM_PAINT &amp;&amp; l)
    {
        VideoWindow *p = (VideoWindow*)l;
        EnterCriticalSection(&amp;p-&gt;_lok);

        HGDIOBJ  oldFont  = ::SelectObject(p-&gt;_hDC, p-&gt;_hFont);
        COLORREF oldFtColor = ::SetTextColor(p-&gt;_hDC, RGB(255,255,255));
        COLORREF oldBkColor = ::SetBkColor(p-&gt;_hDC, RGB(64,64,64));

        // Render image
        //
        // NOTE: This assumes you've already coverted the image to the proper
        // RGB bit-depth (_bpp) and copied the data into _imageBits.
        //
        HBITMAP hBMP = ::CreateCompatibleBitmap(p-&gt;_hDC, p-&gt;_imgWidth,
            p-&gt;_imgHeight);
        ::SetBitmapBits(hBMP, p-&gt;_imgLength, p-&gt;_imgBits);
        HGDIOBJ oldBMP = ::SelectObject(p-&gt;_hFrameDC, hBMP);
        ::BitBlt(p-&gt;_hDC, 0, 0, p-&gt;_imgWidth, p-&gt;_imgHeight, p-&gt;_hFrameDC,
            0, 0, SRCCOPY);
        ::SelectObject(p-&gt;_hFrameDC, oldBMP);

        // Draw some text over the image
        RECT rect;
        ::SetRectEmpty(&amp;rect);
        ::DrawText(p-&gt;_hDC, p-&gt;_imageText, -1, &amp;rect, DT_CALCRECT);
        ::DrawText(p-&gt;_hDC, p-&gt;_imageText, -1, &amp;rect, DT_CENTER | DT_VCENTER);

        if (hBMP) ::DeleteObject(hBMP);

        LeaveCriticalSection(&amp;p-&gt;_lok);
    }
    return DefWindowProc(hWnd, msg, w, l);
}

</code></pre>
<p><strong>Rendering a Video Frame</strong></p>
<pre><code>
void VideoWindow::Render(const unsigned char* frame, int w, int h, int stride)
{
    // Convert frame to the proper RGB bit depth to match _bpp and copy it
    // into _imgBits buffer. Update _imgWidth, _imgHeight, and _imgLength as
    // necessary.

    ::PostMessage(_hWnd, WM_PAINT, 0, (LPARAM)this);
}

</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2011/04/20/rendering-video-with-gdi-example/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Define NaN (Not-a-Number) on Windows</title>
		<link>http://tdistler.com/2011/03/24/how-to-define-nan-not-a-number-on-windows</link>
		<comments>http://tdistler.com/2011/03/24/how-to-define-nan-not-a-number-on-windows#comments</comments>
		<pubDate>Thu, 24 Mar 2011 20:41:48 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=874</guid>
		<description><![CDATA[The C99 spec requires that math.h should define the constant float value NAN. However, NAN isn&#8217;t defined in the Visual Studio version of math.h, so you have to define it yourself (VS only implements C89). It&#8217;s pretty straight-forward for 32-bit machines&#8230; here&#8217;s my implementation with cross-platform protection: #ifdef WIN32 #ifndef NAN static const unsigned long [...]]]></description>
			<content:encoded><![CDATA[<p>The C99 spec requires that <a title="The Open Group: math.h" href="http://pubs.opengroup.org/onlinepubs/009695399/basedefs/math.h.html" target="_blank">math.h should define the constant float value NAN</a>. However, NAN isn&#8217;t defined in the Visual Studio version of math.h, so you have to define it yourself (VS only implements C89). It&#8217;s pretty straight-forward for 32-bit machines&#8230; here&#8217;s my implementation with cross-platform protection:</p>
<pre><code>#ifdef WIN32
    #ifndef NAN
        static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff};
        #define NAN (*(const float *) __nan)
    #endif
#endif

</code></pre>
<p>This code is adapted from an MSDN <a title="MSDN: Not A Number (NAN) Items" href="http://msdn.microsoft.com/en-us/library/w22adx1s(v=vs.80).aspx" target="_blank">example</a>.<del datetime="2011-04-20T17:26:37+00:00"></del></p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2011/03/24/how-to-define-nan-not-a-number-on-windows/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to Test if an Address is IPv4 or IPv6</title>
		<link>http://tdistler.com/2011/02/25/how-to-test-if-an-address-is-ipv4-or-ipv6</link>
		<comments>http://tdistler.com/2011/02/25/how-to-test-if-an-address-is-ipv4-or-ipv6#comments</comments>
		<pubDate>Fri, 25 Feb 2011 19:16:33 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[IPv6]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=785</guid>
		<description><![CDATA[Here&#8217;s a simple function using getaddrinfo() that will take an IP address and return the address family (AF_INET for IPv4, AF_INET6 for IPv6, etc). I works on both Linux and Windows. This function will also accept hostnames and return the address family of the first address returned. You can disable this feature (and the corresponding [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a simple function using <a title="getaddrinfo man page" href="http://linux.die.net/man/3/getaddrinfo" target="_blank">getaddrinfo()</a> that will take an IP address and return the address family (<code>AF_INET</code> for IPv4, <code>AF_INET6</code> for IPv6, etc). I works on both Linux and Windows. This function will also accept hostnames and return the address family of the first address returned. You can disable this feature (and the corresponding DNS lookup) by passing the AI_NUMERICHOST flag.<br />
<code>
<pre>
// Returns the address family of an address or hostname.
// AF_INET, AF_INET6, or -1 on error.
int getaddrfamily(const char *addr)
{
    struct addrinfo hint, *info =0;
    memset(&amp;hint, 0, sizeof(hint));
    hint.ai_family = AF_UNSPEC;
    // Uncomment this to disable DNS lookup
    //hint.ai_flags = AI_NUMERICHOST;
    int ret = getaddrinfo(addr, 0, &amp;hint, &amp;info);
    if (ret)
        return -1;
    int result = info-&gt;ai_family;
    freeaddrinfo(info);
    return result;
}</pre>
<p></code></p>
<p>See <a title="IETF RFC 3493" href="http://tools.ietf.org/html/rfc3493" target="_blank">RFC 3493</a> for more information on the latest socket API for dealing with IPv6.</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2011/02/25/how-to-test-if-an-address-is-ipv4-or-ipv6/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CPU Profiling on Windows: Very Sleepy</title>
		<link>http://tdistler.com/2010/12/21/cpu-profiling-on-windows-very-sleepy</link>
		<comments>http://tdistler.com/2010/12/21/cpu-profiling-on-windows-very-sleepy#comments</comments>
		<pubDate>Tue, 21 Dec 2010 19:59:04 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=697</guid>
		<description><![CDATA[A colleague of mine found a pretty cool profiling tool for Windows called Very Sleepy. It&#8217;s simple, straight-forward, free, and it works&#8230; everything I like in a tool (this is why I like the Sysinternals stuff so much). It&#8217;s also got call-graph and 64-bit support. Definitely worth checking out.]]></description>
			<content:encoded><![CDATA[<p>A colleague of mine found a pretty cool profiling tool for Windows called <a title="Coders Notes: Very Sleepy" href="http://www.codersnotes.com/sleepy" target="_blank">Very Sleepy</a>. It&#8217;s simple, straight-forward, free, and it works&#8230; everything I like in a tool (this is why I like the <a title="Mircosoft Sysinternals" href="http://www.sysinternals.com" target="_blank">Sysinternals</a> stuff so much). It&#8217;s also got call-graph and 64-bit support. Definitely worth checking out.</p>
<p><a href="http://tdistler.com/wp-content/uploads/2011/01/very_sleepy_screenshot.jpg"><img class="aligncenter size-medium wp-image-698" title="very_sleepy_screenshot" src="http://tdistler.com/wp-content/uploads/2011/01/very_sleepy_screenshot-300x218.jpg" alt="Very Sleep Screen Shot" width="300" height="218" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2010/12/21/cpu-profiling-on-windows-very-sleepy/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++ Enums in Lua</title>
		<link>http://tdistler.com/2010/09/13/c-enums-in-lua</link>
		<comments>http://tdistler.com/2010/09/13/c-enums-in-lua#comments</comments>
		<pubDate>Mon, 13 Sep 2010 15:28:42 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Lua]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=460</guid>
		<description><![CDATA[I&#8217;ve been working lately on embedding Lua 5.1.4 into a C++ application. I&#8217;m really impressed with Lua, and most things are pretty straight-forward. However, when it comes to mapping typed enumerations into Lua, I just haven&#8217;t found an easy way to do it. For example, let&#8217;s say you want to expose a C++ function into [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://tdistler.com/wp-content/uploads/2010/09/lua_logo.gif"><img class="alignright size-thumbnail wp-image-462" title="lua_logo" src="http://tdistler.com/wp-content/uploads/2010/09/lua_logo-150x150.gif" alt="Lua" width="150" height="150" /></a>I&#8217;ve been working lately on embedding <a title="Lua Programming Language" href="http://www.lua.org/" target="_blank">Lua 5.1.4</a> into a C++ application. I&#8217;m really impressed with Lua, and most things are pretty straight-forward. However, when it comes to mapping typed enumerations into Lua, I just haven&#8217;t found an easy way to do it. For example, let&#8217;s say you want to expose a C++ function into Lua called <code>create()</code>, which takes an enumerated type as a parameter. In C++ this would look like:</p>
<pre><code>typedef enum _TYPE {
    TYPE_FOO = 0,
    TYPE_BAR,
    TYPE_BAZ,
    TYPE_MAX
} TYPE;

bool create(const TYPE type);</code></pre>
<p>To me, it makes the most sense to call <code>create()</code> from Lua with syntax like:</p>
<p><code>&gt; create(type.foo)</code></p>
<p>Ideally, we&#8217;d also like the following:</p>
<ol>
<li>The enumeration is const, and can&#8217;t be altered from Lua code.</li>
<li>The C++ implementation of <code>create()</code> could validate the type passed to it is the expected type.</li>
</ol>
<p>Unfortunately, this isn&#8217;t as straight-forward as everything else I&#8217;ve done with Lua.</p>
<h4>Solution (i.e. cut-to-the-chase and explain later)</h4>
<p>Okay, I&#8217;m a practical guy&#8230; download <strong><a title="lua_typed_enums.h Header File" href="/media/code/lua_typed_enums.h">lua_typed_enums.h</a></strong> and include it in your code. Then you can add the enums shown above to Lua by calling <code>add_enum_to_lua()</code>:</p>
<pre><code>add_enum_to_lua( L, "type",
    "foo", TYPE_FOO,
    "bar", TYPE_BAR,
    "baz", TYPE_BAZ,
    0 );</code></pre>
<p>Your enums are now available in Lua as:</p>
<p><code>type.foo<br />
type.bar<br />
type.baz</code></p>
<p>Now, your C++ code that takes TYPE as an input and returns a boolean would be written as follows:</p>
<pre><code>static int lua_create( lua_State *L )
{
    if( !check_enum_type( L, "type", -1 ) ) {
        /* error */
    }

    int value = get_enum_value( L, -1 );

    /* do something cool */

    lua_pushboolean( L, 1 );
    return (1);
}</code></pre>
<p>You can now call your <code>create()</code> method from Lua how we wanted:</p>
<p><code>&gt; create(type.bar)</code></p>
<p>Look at the comments in the header file if you want more info about using <code>add_enum_to_lua()</code>, <code>check_enum_type()</code>, and <code>get_enum_value()</code>.</p>
<h4>How it Works</h4>
<p>There&#8217;s no direct way to map the expected behavior of C-enums into Lua (const-ness with typing). What I did was to create a read-only Lua table representing the enumerated type and then make each value in that table have a defined type.</p>
<p>Let&#8217;s deal with the first task: making a read-only table. This is pretty well documented on the web, but I&#8217;ve included a drawing below that would have helped me a lot in the beginning. Let&#8217;s assume we want to represent our enum as a Lua table. We could visualize it as follows:</p>
<p><a href="http://tdistler.com/wp-content/uploads/2010/09/lua_rotables_unprotected.jpg"><img class="aligncenter size-full wp-image-472" title="lua_rotables_unprotected" src="http://tdistler.com/wp-content/uploads/2010/09/lua_rotables_unprotected.jpg" alt="" width="169" height="97" /></a></p>
<p>We could still use the <code>type.foo</code> syntax with this table, but a user could assign a new value to the enum like:</p>
<p><code>&gt; type.foo = 9</code></p>
<p>To prevent this, we need to deny write access to the table. The trick to doing this is to use a metatable and set the <code>__index</code> and <code>__newindex</code> values.</p>
<p><a href="http://tdistler.com/wp-content/uploads/2010/09/lua_rotables_untyped.jpg"><img class="aligncenter size-full wp-image-473" title="lua_rotables_untyped" src="http://tdistler.com/wp-content/uploads/2010/09/lua_rotables_untyped.jpg" alt="" width="361" height="145" /></a></p>
<p>So how does this work? When the user reads a value from the table (i.e. by using <code>type.foo</code>), Lua fails to find &#8220;foo&#8221; in the table. So it looks in the metatable for the <code>__index</code> key. If that is set to point to a table, then it will try to lookup the value in that table. In the case above, it finds the &#8220;foo&#8221; value and returns it like normal. However, if the user attempts to assign to type.foo, Lua follows the <code>__newindex</code> path, which causes a function to get called that does nothing but print an error&#8230; effectively, the write is denied. Here&#8217;s what happens:</p>
<p><code>&gt; type.foo = 9<br />
[string "?"]:1: Attempt to modify read-only table</code></p>
<p>Okay, cool&#8230; we&#8217;ve made read-only enumerations, but what about typing. Glad you asked! We add one more layer of abstraction, of course &lt;groaning&gt;:</p>
<p><a href="http://tdistler.com/wp-content/uploads/2010/09/lua_rotables_typed1.jpg"><img class="aligncenter size-full wp-image-475" title="lua_rotables_typed" src="http://tdistler.com/wp-content/uploads/2010/09/lua_rotables_typed1.jpg" alt="" width="553" height="181" /></a></p>
<p>Basically, we make each value a table that includes the <em>actual</em> value and a type (&#8220;type&#8221; in our example above). The <code>check_enum_type()</code> function looks at the &#8220;type&#8221; field in the table to make sure the correct type was passed to your function. The <code>get_enum_value()</code> function gets the &#8220;value&#8221; field&#8230; which is equal to the actual C-enum type you&#8217;d expect. From the Lua side, you can inspect the enums like:</p>
<p><code>&gt; print(type.foo.value)<br />
0<br />
&gt; print(type.foo.type)<br />
type</code></p>
<p>Explicitly, &#8220;type&#8221; is a read-only table with value &#8220;foo&#8221;. The value of &#8220;foo&#8221; is the table <code>{ value=0, type="type" }</code>. I hope this explanation helps. Obviously, I&#8217;ve been geeking out on Lua a little too much lately <img src='http://tdistler.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2010/09/13/c-enums-in-lua/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ThreadNinja: Finding Rogue POSIX Threads</title>
		<link>http://tdistler.com/2010/07/08/threadninja-finding-rogue-posix-threads</link>
		<comments>http://tdistler.com/2010/07/08/threadninja-finding-rogue-posix-threads#comments</comments>
		<pubDate>Fri, 09 Jul 2010 02:10:04 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=277</guid>
		<description><![CDATA[What Is It? ThreadNinja is a Linux library my team created that tracks pthread_create() and pthread_join() calls in an application. It prints a stacktrace where each thread is created and where it is joined. Any rogue (unjoined) threads are reported when the application exits. ThreadNinja is unobtrusive: it does NOT have to be compiled into [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://tdistler.com/wp-content/uploads/2010/05/tux-ninja.jpg"><img class="alignright size-thumbnail wp-image-278" title="tux-ninja" src="http://tdistler.com/wp-content/uploads/2010/05/tux-ninja-150x150.jpg" alt="Tux Ninja" width="150" height="150" /></a><strong>What Is It?</strong></p>
<p>ThreadNinja is a Linux library my team created that tracks <code>pthread_create()</code> and <code>pthread_join()</code> calls in an application. It prints a stacktrace where each thread is created and where it is joined. Any rogue (unjoined) threads are reported when the application exits. ThreadNinja is <em>unobtrusive</em>: it does NOT have to be compiled into the code. This means you can use it on applications you didn&#8217;t compile.</p>
<p>We found it useful and thought we&#8217;d share it. It&#8217;s be no means production code&#8230; just a tool. Hack on it, expand it, change it&#8230; whatever. It&#8217;s pretty small, so it should be easy to dive right in. We&#8217;ve released it under the <a title="BSD License Page" href="http://www.opensource.org/licenses/bsd-license.php" target="_blank">BSD license</a>.</p>
<p><strong>Cut To The Chase</strong></p>
<p>You can checkout the source code from <a title="Thread Ninja Project on Google Code" href="http://code.google.com/p/threadninja/" target="_blank">Google Code</a>, or download the version 1.0 tarball directly (<a title="Thread Ninja Source Tarball" href="http://www.tdistler.com/media/code/threadninja.tar.gz" target="_blank">threadninja.tar.gz</a>).</p>
<p>To build ThreadNinja, simply untar it and call <code>make</code>:<br />
<code>&gt; tar -zxf threadninja.tar.gz<br />
&gt; make</code></p>
<p>Now, simply use <code>LD_PRELOAD</code> to run the application:</p>
<p><code>&gt; LD_PRELOAD=/path/to/threadninja/build/libthreadninja.so.1 TheApplication</code></p>
<p>If you don&#8217;t see function names in the stacktraces that are generated, then the application needs to be compiled with debug symbols. For my test app, I had to compile with the <code>-rdynamic</code> option:</p>
<p><code>&gt; ﻿g++ -Wall -rdynamic main.cpp -lpthread</code></p>
<p>This causes the global symbol table to be included in the executable, which contains all the application&#8217;s function names. For more info, look at the <code>--export-dynamic</code> option on the <a title="GNU Linker man page" href="http://linux.die.net/man/1/ld" target="_blank">GNU linker (ld) man page</a>.</p>
<p><strong>The Story Behind ThreadNinja</strong></p>
<p>My team was assigned to stabilize a large video application that runs as a Linux-based appliance. The application consisted of 100,000+ of lines to code that was a tangle of build warnings, circular references, and many creative hacks. Our particular task was to fix a persistent set of seg-faults and memory leaks.<span id="more-277"></span></p>
<p>One of the first things we noticed was that the application didn&#8217;t shutdown properly. The shutdown logic was something akin to: signal components to exit, sleep 2 seconds, call Release() a couple times to clean up extra ref-counts, sleep 2 seconds, and then just call exit() to get the process to terminate (bypassing the remaining clean up code). Of course, this renders <a title="Valgrind" href="http://valgrind.org/" target="_blank">Valgrind</a> useless when trying to find memory leaks, because the automatic memory cleanup code gets bypassed during the process abort.</p>
<p>As a result, our first priority was to get the app to shutdown cleanly. The first issue we ran into was that <code>pthread_join()</code> blocked indefinitely because threads were failing to terminate. We tried using GDB to track the threads, but many hundreds of threads were being created and destroyed dynamically. We needed a way to let the application run for hours, allow 1000+ threads to live and die, and still be able to track rogue threads. Hence, ThreadNinja was born.</p>
<p><strong>How It Works</strong></p>
<p>Through the magic of <code><a title="LD_PRELOAD" href="http://linux.die.net/man/8/ld.so" target="_blank">LD_PRELOAD</a></code>, ThreadNinja &#8220;injects&#8221; itself between all calls to <code>pthread_create()</code> and <code>pthread_join()</code>. This happens because <code>LD_PRELOAD</code> instructs the loader to load ThreadNinja into memory first, before other libraries (in this case, before the pthread library). The result is that ThreadNinja&#8217;s implementation of <code>pthread_create()</code> and <code>pthread_join()</code> are used by the application instead of pthread&#8217;s own implementation. What ThreadNinja does is track the calls to these methods and then pass the call on to the &#8220;real&#8221; pthread implementation. From the application&#8217;s point-of-view, the behavior of the thread methods are the same&#8230; the tracking is transparent.</p>
<p><strong>Output</strong></p>
<p>Each time <code>pthread_create()</code> is called, a stacktrace and timestamp are printed to stdout:</p>
<p><code>Thread Created: 3047947120<br />
[bt] Thu Jul  8 16:31:23 2010</code></p>
<p><code>[bt] ./a.out(StartService(unsigned long*, int))<br />
[bt] ./a.out(Initialize())<br />
[bt] ./a.out(main+0xb) [0x80489fa]<br />
[bt] /lib/libc.so.6(__libc_start_main+0xe6) [0xb5bbb6]<br />
[bt] ./a.out() [0x8048811]</code></p>
<p>The first line (&#8220;Thread Created&#8221;) gives the value of the <code>pthread_t</code> handle, so you can later track where rogue threads where created. The next line is the time when the create happened. The remaining lines are the call stack that led to the <code>pthread_create()</code> call.</p>
<p>Each time <code>pthread_join()</code> is called, similar information is printed to stdout:</p>
<p><code>Thread Joined: 3047947120<br />
[bt] Thu Jul  8 16:31:31 2010</code></p>
<p><code>[bt] ./a.out(Terminate())<br />
[bt] ./a.out(main+0x10) [0x80489ff]<br />
[bt] /lib/libc.so.6(__libc_start_main+0xe6) [0xb5bbb6]<br />
[bt] ./a.out() [0x8048811]</code></p>
<p>When the application terminates (cleanly or uncleanly), a summary of the current state of the application threads is printed:</p>
<p><code>exit_handler()<br />
[Thread Summary]<br />
Total Created: 573<br />
Total Joined: 568<br />
Total Running: 5</code></p>
<p>In this case, you&#8217;ll notice that 5 threads were never joined on.</p>
<p><strong>Limitations</strong></p>
<p>ThreadNinja only tracks calls to <code>pthread_create()</code> and <code>pthread_join(</code>). This means calls like <code>system()</code>, <code>exec()</code>, and <code>fork()</code> are not tracked. Also, calls to <code>pthread_cancel()</code> are not tracked. We had started adding code to track pthread mutexes and stuff, but it turned out we didn&#8217;t need it. Feel free to add support for all this stuff and submit changes to the Google code site.</p>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2010/07/08/threadninja-finding-rogue-posix-threads/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Macros with Variable Argument Lists</title>
		<link>http://tdistler.com/2010/06/21/macros-with-variable-argument-lists</link>
		<comments>http://tdistler.com/2010/06/21/macros-with-variable-argument-lists#comments</comments>
		<pubDate>Mon, 21 Jun 2010 22:46:39 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=325</guid>
		<description><![CDATA[In C/C++, macros that take a variable number of arguments (called variadic macros) can be very useful. Having printf-style macros just makes certain things easier to read and understand. Below I&#8217;ll describe how to do this in a way that works on Windows and Linux, as well as supports empty argument lists. Example Consider the [...]]]></description>
			<content:encoded><![CDATA[<p>In C/C++, macros that take a variable number of arguments (called <a title="Variadic Macros" href="http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html" target="_blank">variadic macros</a>) can be very useful. Having printf-style macros just makes certain things easier to read and understand. Below I&#8217;ll describe how to do this in a way that works on Windows and Linux, as well as supports empty argument lists.</p>
<p><strong>Example</strong></p>
<p><strong> </strong>Consider the following log method:</p>
<p><code>void WriteLog( const LOG_LEVEL level, const char* file, const int line, const char* format, ... );</code></p>
<p>Pretty straight-forward: it allows you to specify the log level (NOTICE, WARNING, ERROR, etc), a file name and line number, and a user-defined description in &#8220;printf&#8221; format. To log a warning message, you would type:</p>
<p><code>WriteLog( LL_WARNING, __FILE__, __LINE__, "[WARNING] Failed to import descriptor '%s:%i'!", _descriptor, _id );</code></p>
<p>The entry in the log file would look like:</p>
<p><code>Core.cpp:715 [WARNING] Failed to import descriptor 'timing-engine'!</code></p>
<p><strong>Creating a Variadic Macro</strong></p>
<p>Calling <code>WriteLog</code> directly works fine, but it&#8217;s pretty verbose and annoying to use. One way to make it simpler is to wrap <code>WriteLog</code> with a variadic macro:</p>
<p><code> #define LOG_WARNING( format, ... ) \\<br />
WriteLog( LL_WARNING, __FILE__, __LINE__, "[WARNING] " format, ##__VA_ARGS__ );</code></p>
<p>Then the example above would become:</p>
<p><code>LOG_WARNING( "Failed to import descriptor '%s:%i'!", _descriptor, _id );</code></p>
<p>The macro automatically fills in the file and line number where the log message was generated, and the log level is specified by the macro name (<code>LOG_WARNING</code>). This is much more straight-forward and I believe it makes the code easier to read.</p>
<p>Notice that <code>__VA_ARGS__</code> is used to get the variable argument list and pass it to <code>WriteLog</code>. During compilation, the preprocessor replaces <code>__VA_ARGS__</code> with the comma-separated list of  arguments. The &#8216;<code>##</code>&#8216; that prefixes <code>__VA_ARGS__</code> is vital if you want your macro to work like you expect. Without it, you would be <em>required</em> to have at least one argument after the format string. &#8217;<code>##</code>&#8216; has a special meaning in this case: it causes the preceding comma to be deleted if there are no variable arguments. Without this, the following line would generate a syntax error:</p>
<p><code>LOG_WARNING( "This would cause a syntax error" );</code></p>
<p>Prefixing <code>__VA_ARGS__</code> with &#8216;<code>##</code>&#8216; allows the above code to work just fine.</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2010/06/21/macros-with-variable-argument-lists/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stop Stealing My File Descriptors!</title>
		<link>http://tdistler.com/2010/06/18/stop-stealing-my-file-descriptors</link>
		<comments>http://tdistler.com/2010/06/18/stop-stealing-my-file-descriptors#comments</comments>
		<pubDate>Fri, 18 Jun 2010 21:48:43 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=313</guid>
		<description><![CDATA[We ran into a weird problem the other day where our Linux video display appliance would lose audio support when the process was restarted. The audio was supposed to play through a custom joystick-keyboard that was attached via USB (the keyboard is used by security guards to PTZ cameras, control monitors, etc). The audio could [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://tdistler.com/wp-content/uploads/2010/06/sherlock_tux.jpg"><img class="alignright size-thumbnail wp-image-319" title="sherlock_tux" src="http://tdistler.com/wp-content/uploads/2010/06/sherlock_tux-150x150.jpg" alt="Sherlock Tux" width="150" height="150" /></a>We ran into a weird problem the other day where our Linux video display appliance would lose audio support when the process was restarted. The audio was supposed to play through a custom joystick-keyboard that was attached via USB (the keyboard is used by security guards to PTZ cameras, control monitors, etc). The audio could be heard just fine when the box first booted, but if the application restarted audio would be lost.</p>
<p>Looking at the logs, we found that our audio pipeline was failing to open <code>/dev/dsp</code> on the restart. We then used <code>lsof</code> to list the open file descriptors to see which process currently held <code>/dev/dsp</code>:</p>
<p><code># lsof | grep /dev/dsp<br />
ntpd   18857    root   16u    CHR     14,3    180099 /dev/dsp<br />
</code></p>
<p>What!?!?&#8230; why the heck is NTP opening the sound device and how did it steal it from us??? After some discussion we started remembering a problem in the past with <code>ntpd</code> stealing our SNMP diagnostics port. This just didn&#8217;t make any sense.</p>
<p>Digging into our appliance code, we found this line:</p>
<p><code>system( "service ntpd restart" );</code></p>
<p>This would be called each time we were notified by the security system that the NTP server address had changed (which fired once each time the process was started so we could get the initial address). But this still didn&#8217;t explain why NTP took over ownership of our file descriptors on restart.</p>
<p>Long story short: <code>system()</code> is implemented as <code>fork()</code> followed by <code>execv()</code>. By default, <code>fork()</code> gives a copy of the parent&#8217;s file descriptors to the child process (i.e. the <code>ntpd</code> child process got a copy of the <code>/dev/dsp</code> file descriptor). To prevent this, you have to set the <code>FD_CLOEXEC</code> flag on the file desciptors you don&#8217;t want copied.</p>
<p>For example:</p>
<p><code>fd = open( "/dev/dsp", O_RDWR );<br />
fcntl( fd, F_SETFD, FD_CLOEXEC );</code></p>
<p><strong>Conclusion</strong>: setting the <code>FD_CLOEXEC</code> flag on the <code>/dev/dsp</code> file descriptor fixed the problem for audio. However, most of the other file desciptors still got owned by <code>ntpd</code>. Did we go back and set the <code>FD_CLOEXEC</code> flag on all file descriptors, you ask? Nope. It turns out we had a script monitoring the NTP config file and restarting ntpd for us when the file got updated&#8230; we just had to update the config file and remove the <code>system( "service ntpd restart" )</code> call.</p>
<p>Oh, and the reason audio worked on first boot but not subsequent restarts was due to a weird race condition around when <code>/dev/dsp</code> got opened.</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2010/06/18/stop-stealing-my-file-descriptors/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C/C++: Writing printf-style Functions</title>
		<link>http://tdistler.com/2010/01/11/cc-writing-printf-style-functions</link>
		<comments>http://tdistler.com/2010/01/11/cc-writing-printf-style-functions#comments</comments>
		<pubDate>Tue, 12 Jan 2010 00:31:14 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=339</guid>
		<description><![CDATA[Having printf-style functions is very useful. I find myself periodically having to remember how to write variable argument functions, so I decided to just blog about it. EDIT (4/18/2011): Simple Version That Just Prints #include &#60;stdarg.h&#62; void Foo( const char* format, ... ) { va_list args; va_start( args, format ); vprintf( format, args ); va_end( [...]]]></description>
			<content:encoded><![CDATA[<p>Having printf-style functions is very useful. I find myself periodically having to remember how to write variable argument functions, so I decided to just blog about it.</p>
<p><strong>EDIT (4/18/2011):</strong> Simple Version That Just Prints</p>
<pre><code>#include &lt;stdarg.h&gt;

void Foo( const char* format, ... )
{
    va_list args;
    va_start( args, format );
    vprintf( format, args );
    va_end( args );
}</code></pre>
<p><strong>End Edit</strong></p>
<pre><code>#include &lt;stdarg.h&gt;   // or &lt;cstdarg&gt;

// Hide annoying naming differences between Windows and other platforms
#ifdef WIN32
    #define my_vsnprintf _vsnprintf
#else
    #define my_vsnprintf vsnprintf
#endif

// The function
void Foo( const char* format, ... )
{
    // Parse the argument list
    va_list args;
    va_start( args, format );

    // Calculate the final length of the formatted string
    int len = my_vsnprintf( 0, 0, format, args );

    // Allocate a buffer (including room for null termination)
    char* target_string = new char[++len];

    // Generate the formatted string
    my_vsnprintf( target_string, len, format, args );

    /* Do something with the formatted string */

    // Clean up
    delete [] target_string;
    va_end( args );
}</code></pre>
<p><strong>Gotchas</strong></p>
<p>We ran into a problem with <code>vsnprintf()</code> using the Denx Linux distro on a PowerPC processor: <code>vsnprintf( 0, 0, format, args )</code> would modify the <code>va_list</code>, which would cause a crash on the second call to <code>vsnprintf()</code>&#8230; the one that does the actual formatting.  The work-around is to make a temporary copy of the <code>va_list</code> when determining the formatted string length:</p>
<p><code>va_list args_copy;<br />
va_copy( args_copy, args );<br />
int len = my_vsnprintf( 0, 0, format, args );<br />
va_end( args_copy );</code></p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2010/01/11/cc-writing-printf-style-functions/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Find &amp; Replace in Files on Linux</title>
		<link>http://tdistler.com/2009/04/13/find-replace-in-files-on-linux</link>
		<comments>http://tdistler.com/2009/04/13/find-replace-in-files-on-linux#comments</comments>
		<pubDate>Mon, 13 Apr 2009 19:28:59 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=200</guid>
		<description><![CDATA[A lot of solutions I&#8217;ve found for recursively replacing text in files is implemented using shell scripts, perl, php, or some other inconvenient way. Rushi got it right by using the Linux command line. Here it is (slightly modified) from his blog: find . -name &#8220;*.cpp&#8221; -print &#124; xargs sed -i &#8216;s/[find]/[replace]/g&#8217; where &#8220;[find]&#8221; and [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright" style="float: right;" src="/media/images/tux.jpg" alt="Tux" />A lot of solutions I&#8217;ve found for recursively replacing text in files is implemented using shell scripts, perl, php, or some other inconvenient way. <a href="http://rushi.vishavadia.com/blog/2008/08/05/find-replace-across-multiple-files-in-linux/" target="_blank">Rushi</a> got it right by using the Linux command line. Here it is (slightly modified) from his blog:</p>
<p class="codeblock">find . -name &#8220;*.cpp&#8221;  -print | xargs sed -i &#8216;s/[find]/[replace]/g&#8217;</p>
<p>where &#8220;[find]&#8221; and &#8220;[replace]&#8221; are the things you are searching for and substituting.</p>
<p>To search files with multiple file extensions, use:</p>
<p class="codeblock">find . -name &#8220;*.cpp&#8221;  -o -name &#8220;*.h&#8221; -o -name &#8220;*.c&#8221; | xargs sed -i &#8216;s/[find]/[replace]/g&#8217;</p>
<p><b>ADDED 4-13-2009:</b> See comments for other variations.</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2009/04/13/find-replace-in-files-on-linux/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How To Get An Error Message Describing Why A Library Failed To Load</title>
		<link>http://tdistler.com/2009/04/08/how-to-get-an-error-message-describing-why-a-library-failed-to-load</link>
		<comments>http://tdistler.com/2009/04/08/how-to-get-an-error-message-describing-why-a-library-failed-to-load#comments</comments>
		<pubDate>Wed, 08 Apr 2009 18:01:11 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=163</guid>
		<description><![CDATA[The title&#8217;s kind of a misnomer. This post is really to help me remember how to get a human-readable string from a Windows error code&#8230; I&#8217;m finally tired of always having to look it up . However, my current situation revolves around determining why a DLL (or *.so on Linux) failed to load, so that&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>The title&#8217;s kind of a misnomer. This post is really to help me remember how to get a human-readable string from a Windows error code&#8230; I&#8217;m finally tired of always having to look it up <img src='http://tdistler.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  . However, my current situation revolves around determining why a DLL (or *.so on Linux) failed to load, so that&#8217;s why this post it titled the way it is.</p>
<p>I like to disable the annoying default dialog that pops up in Windows when a library fails to load.</p>
<p><code>SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOOPENFILEERRORBOX);</code></p>
<p>Now, here&#8217;s the code to get a user friendly text string:</p>
<pre><code>#ifdef WIN32
    LPVOID pStr = 0;
    DWORD_PTR args[1] = { (DWORD_PTR)pFilename };
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_ARGUMENT_ARRAY,
        NULL,
        GetLastError(),
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)&#038;pStr,
        0,
        (va_list*)args);

    /* Do something with the string pStr here */

    LocalFree(pStr);
#else
    /* Call dlerror() and do something with the string */
#endif</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2009/04/08/how-to-get-an-error-message-describing-why-a-library-failed-to-load/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Print a Stack Backtrace Programatically in Linux</title>
		<link>http://tdistler.com/2008/11/15/how-to-print-a-stack-backtrace-programatically-in-linux</link>
		<comments>http://tdistler.com/2008/11/15/how-to-print-a-stack-backtrace-programatically-in-linux#comments</comments>
		<pubDate>Sun, 16 Nov 2008 00:36:58 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=149</guid>
		<description><![CDATA[So here&#8217;s a cool feature of GNU&#8217;s implementation of libc: you can get a stack backtrace (as an array of strings) dynamically in your code. This can be really useful when trying to determine the code path taken when an error occurs. Most times, it&#8217;s faster to just run the code in a debugger and [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright" style="float: right;" src="/media/images/GNULogo.jpg" alt="GNU Logo" />So here&#8217;s a cool feature of <a title="GUN libc" href="http://www.gnu.org/software/libc/" target="_blank">GNU&#8217;s implementation of libc</a>: you can get a stack backtrace (as an array of strings) dynamically in your code. This can be really useful when trying to determine the code path taken when an error occurs. Most times, it&#8217;s faster to just run the code in a debugger and use it to display a backtrace, but there are instances when doing it programmatically is your best option. For example, you could get a backtrace in your application&#8217;s exception handler and use it to augment error log messages.</p>
<p>First, you need to include execinfo.h to your code:</p>
<p><code>#include &lt;execinfo.h&gt;</code></p>
<p>Next, call the <code>backtrace()</code> function to get an array of void pointers that represents the current stack (the pointers are the return addresses for each stack frame).</p>
<p><code>void* tracePtrs[100];<br />
int count = backtrace( tracePtrs, 100 );</code></p>
<p>The <code>backtrace()</code> function returns the number of entries in the array (read the man pages for more info about the array size).</p>
<p>Finally, you need to resolve the function names associated with the pointers. You have 2 options: <code>backtrace_symbols()</code> and <code>backtrace_symbols_fd()</code>. Both of these methods resolve the pointers to strings, but the difference is that <code>backtrace_symbols()</code> allocates the strings on the heap while <code>backtrace_symbols_fd()</code> writes the strings to a file descriptor that you can read. Just keep in mind that <code>backtrace_symbols()</code> won&#8217;t work if the heap has been trashed.</p>
<p>Here&#8217;s an example using <code>backtrace_symbols()</code>:</p>
<pre><code>char** funcNames = backtrace_symbols( tracePtrs, count );

// Print the stack trace
for( int ii = 0; ii &lt; count; ii++ )
    printf( "%s\n", funcNames[ii] );

// Free the string pointers
free( funcNames );</code></pre>
<p><br/>NOTE: Make sure you call <code>free()</code> on the array of strings returned from <code>backtrace_symbols()</code>.</p>
<p>For more information, <a title="Linux Journal: Stack Backtraceing Inside Your Program" href="http://www.linuxjournal.com/article/6391" target="_blank">here&#8217;s a good article from the Linux Journal</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2008/11/15/how-to-print-a-stack-backtrace-programatically-in-linux/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Debugging: C++ Templates, Breakpoints, and GDB</title>
		<link>http://tdistler.com/2008/11/13/debugging-c-templates-brekpoints-and-gdb</link>
		<comments>http://tdistler.com/2008/11/13/debugging-c-templates-brekpoints-and-gdb#comments</comments>
		<pubDate>Fri, 14 Nov 2008 01:28:57 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=146</guid>
		<description><![CDATA[Debugging C++ templates is difficult. Debugging C++ templates with GDB can be an act of torture for even seasoned GDB users. I like GDB, but there are some tricks you should know when using it to debug templates. In this post, I deal with setting breakpoints. Breakpoint Basics: Setting a breakpoint in GDB is supposed [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright" style="float: right;" src="/media/images/GNULogo.jpg" alt="GNU Logo" />Debugging C++ templates is difficult. Debugging C++ templates with GDB can be an act of torture for even seasoned GDB users. I like GDB, but there are some tricks you should know when using it to debug templates. In this post, I deal with setting breakpoints.</p>
<p><strong>Breakpoint Basics:</strong></p>
<p>Setting a breakpoint in GDB is supposed to be simple. Here we set a breakpoint at line 50 in file main.cpp:</p>
<p class="codeblock">(gdb) b main.cpp:50<br />
Breakpoint 1 at 0x804937a: file main.cpp, line 50.</p>
<p>We can also use the function name and GDB will attempt to find the correct location for us:</p>
<p class="codeblock">(gdb) b DoSomething<br />
Breakpoint 2 at 0&#215;8049334: file main.cpp, line 150</p>
<p>Simple, right? Just wait&#8230;</p>
<p><strong>Breakpoint Gotchas:</strong></p>
<p>GDB&#8217;s breakpoint logic is pretty handy for simple projects, but it can break down fast when things get more complicated.</p>
<p>For example, let&#8217;s say your application is plugin-driven, with each plugin being a separate library. Now assume each plugin has a Plugin.cpp file under it&#8217;s own Source directory. Try to set a breakpoint in the Initialize() method of the Plugin class:</p>
<p class="codeblock">(gdb) b Initialize<br />
Breakpoint 3 at 0&#215;8049717: file main.cpp, line 230</p>
<p>Oops! There is an Initialize() method in main.cpp and GDB thought that&#8217;s where we wanted to put it: wrong!</p>
<p><span id="more-146"></span>Okay, let&#8217;s be more specific:</p>
<p class="codeblock">(gbd) b Plugin::Initialize<br />
Breakpoint 4 at 0&#215;8046194: file Source/Plugin.cpp, line 89</p>
<p>Okay, that looks better, but <em>which </em>Plugin.cpp file did GDB put the breakpoint? How do we know it&#8217;s the file for the plugin we want?</p>
<p>If we used namespaces, then we can get more specific:</p>
<p class="codeblock">(gdb) b MY_PLUGIN_A::Plugin::Initialize<br />
Breakpoint 5 at 0&#215;8050039: file Source/Plugin.cpp, line 130</p>
<p>We can see from the address and line number that the previous breakpoint was at the wrong place. Okay, moving on&#8230;</p>
<p><strong>Setting Breakpoint in Templates:</strong></p>
<p>Templates can be much harder to set breakpoints in because we have to specify the <em>exact </em>prototype for the fully-defined template. We as programmers are used to the compiler handling the template type stuff for us, so it can be difficult to guess the correct type.</p>
<p>For example, assume we have some abstract class BarAbstract that uses the template Foo&lt;&gt; to make it concrete. Now assume we&#8217;re really clever and we want to hide this from the users of our class. We could use a typedef to hide the true type:</p>
<p class="codeblock">typedef Foo&lt;BarAbstract&gt; Bar;</p>
<p>Now, all the user needs to do is instantiate Bar without a thought to the Foo&lt;&gt; template.</p>
<p class="codeblock">int DoSomething()<br />
{<br />
Bar b;<br />
return b.Baz();<br />
}</p>
<p>So far so good? Okay, now how the heck do you set a breakpoint in the Baz() method of class Bar?</p>
<p>The quick answer: use objdump, c++filt, and grep to find the complete definition that GDB will need.</p>
<p class="codeblock">$ objdump -t libMyLib.so | c++filt | grep &#8216;BarAbstract.*Baz&#8217;<br />
0000d2d6 w F .text 0000000a     MY_PLUGIN_A::Foo&lt;MY_PLUGIN_A::BarAbstract&gt;::Baz()</p>
<p>Now, simply copy-n-paste the full method definition to GDB when setting the breakpoint:</p>
<p class="codeblock">(gdb) b MY_PLUGIN_A::Foo&lt;MY_PLUGIN_A::BarAbstract&gt;::Baz()<br />
Breakpoint 6 at 0&#215;8048890: file Source/Bar.cpp, line 355</p>
<p>That&#8217;s it! Happy debugging!</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2008/11/13/debugging-c-templates-brekpoints-and-gdb/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>C/C++: Using Bitfields Effectively</title>
		<link>http://tdistler.com/2008/07/21/cc-using-bitfields-effectively</link>
		<comments>http://tdistler.com/2008/07/21/cc-using-bitfields-effectively#comments</comments>
		<pubDate>Mon, 21 Jul 2008 15:00:29 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Code Monkey]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://tdistler.com/?p=120</guid>
		<description><![CDATA[Introduction If you&#8217;ve ever done embedded development in C/C++, you are probably familiar with bitfields. They are a handy way to reference individual bits in things like hardware registers. The problem is that bitfields can lead to performance problems and race conditions if not used properly. I hope to highlight some of the issues you [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>If you&#8217;ve ever done embedded development in C/C++, you are probably familiar with bitfields. They are a handy way to reference individual bits in things like hardware registers. The problem is that bitfields can lead to performance problems and race conditions if not used properly. I hope to highlight some of the issues you should consider when using them.</p>
<p><strong>Usage</strong></p>
<p>First, let&#8217;s assume you need to check various fields in a hardware register with the following layout:</p>
<p style="text-align: center;"><img src="/media/images/BitfieldRegisterEx1.jpg" alt="Bitfield Register Example" width="431" height="52" /></p>
<p>You could define the following bitfield to represent this register:</p>
<p class="codeblock">1: struct HwReg<br />
2: {<br />
3: &nbsp;&nbsp;&nbsp;unsigned int Base : 16;<br />
4: &nbsp;&nbsp;&nbsp;unsigned int Offset : 8;<br />
5: &nbsp;&nbsp;&nbsp;unsigned int Rsvd : 5;<br />
6: &nbsp;&nbsp;&nbsp;unsigned int Flag : 1;<br />
7: &nbsp;&nbsp;&nbsp;unsigned int Type : 2;<br />
8: };</p>
<p>The total size of this data type is sizeof(unsigned int), with each line defining a different region (field) within that type (this looks confusing when you first look at it). The following code uses the HwReg bitfield to access a memory-mapped register:</p>
<p class="codeblock">1: struct HwReg* pReg = (struct HwReg*)0&#215;80001005;<br />
2:<br />
3: if (pReg-&gt;Flag &amp;&amp; pReg-&gt;Type == TYPE_1)<br />
4: {<br />
5: &nbsp;&nbsp;&nbsp;void* address = pReg-&gt;Base + pReg-&gt;Offset;<br />
6: }</p>
<p>Line 1 defines a pointer to the physical hardware register as type HwReg. We can now use this pointer to easily access the register fields. If this isn&#8217;t clear, you can read more about bitfields <a title="Wikipedia: Bit Field" href="http://en.wikipedia.org/wiki/Bit_field" target="_blank">HERE</a>.</p>
<p><strong>Performance Problems</strong></p>
<p>The compiler doesn&#8217;t know how to optimize bitfield accesses (especially because the pointers to memory-mapped hardware registers are almost always declared &#8216;volatile&#8217;). This means that every access to a member of the bitfield will require a read of the physical hardware register. This can be orders of magnitude slower than accessing main memory. In the code example above, the hardware register will be read 4 times; once for each field access.</p>
<p>The way to remedy this is to cache a copy of the register value and then operate on that. Consider the following code:</p>
<p class="codeblock">1: unsigned int* pFullReg = (unsigned int*)0&#215;80001005;<br />
2: unsigned int temp = *pFullReg;<br />
3: struct HwReg* pReg = (struct HwReg*)&amp;temp;<br />
4:<br />
5: if (pReg-&gt;Flag &amp;&amp; pReg-&gt;Type == TYPE_1)<br />
6: {<br />
7: &nbsp;&nbsp;&nbsp;void* address = pReg-&gt;Base + pReg-&gt;Offset;<br />
8: }</p>
<p>Line 1 defines a pointer to the physical hardware register. Line 2 performs the actual read into a local variable (the slowest part). This local copy is now in main memory and the CPU cache. Line 3 casts the cached value to the bitfield for easy access. Finally, all accesses to the register fields is on the cached value, which can be read very fast from L1 cache.</p>
<p>Another advantage to this approach is when the hardware requires locking before the register can be accessed. By caching the value, you can keep all the locking code localized to a single area of the function. Without caching, you would hold the lock for a longer period of time (possibly forcing other operations to block) and have to make sure to release the lock on every return path (more difficult with exceptions).</p>
<p>NOTE: Remember you are only working with a <em>copy</em> of the register value. If you update a value in the bitfield, you must still copy the updated value back to the register.</p>
<p><strong>Race Conditions</strong></p>
<p>As stated above, each access to a field value generates its own read/write operation. Even if the CPU architecture guarantees that an individual operation is atomic, updating multiple fields are not. Thus, in a multi-threaded application you must lock the entire block of code that operates on the bitfield. I again suggest caching the value, as you only need to lock the actual read/write of the entire register.</p>
<p><strong>Conclusion</strong></p>
<p>Bitfields are a nice language construct that can help make it easier to write clean code (as opposed to using macros and bitmasks). Unfortunately, it&#8217;s all too easy to shoot-yourself-in-the-foot with bitfields if you don&#8217;t understand the pitfalls. As always, use caution when writing performance-critical code and make sure you understand how to use the available code constructs.</p>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://tdistler.com/2008/07/21/cc-using-bitfields-effectively/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

