<?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>bbum&#039;s weblog-o-mat &#187; Mac OS X</title>
	<atom:link href="http://www.friday.com/bbum/category/science/technology/apple/mac-os-x/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.friday.com/bbum</link>
	<description>...so google can index my head.</description>
	<lastBuildDate>Fri, 19 Mar 2010 16:06:43 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Geotagging Photos With Aperture &amp; QStarz BT-1300S</title>
		<link>http://www.friday.com/bbum/2010/03/11/geotagging-photos-with-aperture-qstarz-bt-1300s/</link>
		<comments>http://www.friday.com/bbum/2010/03/11/geotagging-photos-with-aperture-qstarz-bt-1300s/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 07:28:55 +0000</pubDate>
		<dc:creator>bbum</dc:creator>
				<category><![CDATA[Industrial Design]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Photography]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://www.friday.com/bbum/?p=1773</guid>
		<description><![CDATA[With the release of Aperture 3, geotagging photos is now an integral part of the application&#8217;s workflow.  Aperture grew the Faces &#038; Places features like iPhotos!
In particular, the Places feature allows you to import GPS data from iPhone photos or from GPS data captured by pretty much any device that can spew a standard [...]]]></description>
			<content:encoded><![CDATA[<p>With the release of <a href="http://www.apple.com/aperture/">Aperture 3</a>, geotagging photos is now an integral part of the application&#8217;s workflow.  Aperture grew the <a href="http://www.apple.com/aperture/whats-new.html#faces">Faces</a> &#038; <a href="http://www.apple.com/aperture/whats-new.html#places">Places</a> features like iPhotos!</p>
<p>In particular, the <a href="http://www.apple.com/aperture/whats-new.html#places">Places</a> feature allows you to import GPS data from iPhone photos <em>or</em> from GPS data captured by pretty much any device that can spew a standard <a href="http://www.topografix.com/gpx.asp">GPX format</a> data file.</p>
<div class="imgLeft"><img src="http://www.friday.com/bbum/wp-content/uploads/2010/03/ImportFromiPhone.png" alt="ImportFromiPhone.png" title="ImportFromiPhone.png" border="0" width="231" height="162" /></div>
<p>Tagging from the iPhone is straightforward.  With the iPhone connected to your computer, go to <strong>Places</strong> in Aperture and then select <strong>Import from iPhone Photos&#8230;</strong>.  Aperture will then display all the photos on your iPhone that have GPS metadata and you can pick the photos from which the GPS data is to be imported.  Once picked, Aperture will apply the GPS data to photos taken near the same time as the imported data.</p>
<p>However, one issue with the iPhone is that it really isn&#8217;t a terribly good GPS logging device.  Using it as one eats the battery and the data generated often has holes.  And, because the iPhone uses A-GPS (GPS assisted by cellular signal), it doesn&#8217;t work at all when hiking in areas without cell signal.  Apparently, I&#8217;m mistaken about <a href="http://en.wikipedia.org/wiki/Assisted_GPS">A-GPS</a> &#8212; it should fall back to regular GPS behavior.  My experience, though, is that the iPhone just isn&#8217;t a terribly good GPS device when it doesn&#8217;t have a cell signal and has often been off by miles when in the hinterlands.  It works <em>great</em> when on the road or near cities, though.</p>
<p><span id="more-1773"></span></p>
<div class="imgRight"><img src="http://www.friday.com/bbum/wp-content/uploads/2010/03/PlacingPhotos.png" alt="PlacingPhotos.png" title="PlacingPhotos.png" border="0" width="578" height="642" /><br /><strong>Dragging a photo onto a track.</strong>  Note that my camera&#8217;s clock was set correctly.</div>
<p>Importing a raw GPS Track is a slightly more involved process and, at first blush, doesn&#8217;t entirely seem as easy as it could be.  But there is a good reason for the way it works; clocks on cameras generally suck and, thus, there is a need to effectively timeshift imported photos vs. the GPS data.</p>
<p>When you import a GPS track, the <strong>Tracks and Waypoints</strong> submenu will be populated with the various segments of GPS track data imported from the log.  Once you select a GPS track that includes a location for a photo that you want to geotag, drag the photo to the exact location on the track where the photo was taken.  Aperture will display the offset in time between the photo&#8217;s timestamp and the GPS data.  When you drop the photo, Aperture will ask if you want to assign GPS metadata to all photos taken during the (potentially offset) duration of the GPS track.</p>
<p>Done. Photos geotagged.  And, if you haven&#8217;t happened to reset your camera&#8217;s clock recently, you&#8217;ll probably be chagrined and amazed to know exactly how poorly your camera keeps time!</p>
<p>Of course, you need a source of GPS metadata.  And this is where your fuzzy happy generally intuitive and &#8220;just works&#8221; experience ends.  Frankly, the state of GPS support on the Mac just flat out sucks outside of a handful of navigation oriented devices.</p>
<div class="imgLeft"><iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;nou=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=billbumgarner-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=B001EV2IY0" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe></div>
<p>After purchasing and returning two different devices, I finally settled on the <a href="http://www.amazon.com/gp/product/B001EV2IY0?ie=UTF8&#038;tag=billbumgarner-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=B001EV2IY0">Qstarz BT-Q1300S</a><img src="http://www.assoc-amazon.com/e/ir?t=billbumgarner-20&#038;l=as2&#038;o=1&#038;a=B001EV2IY0" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />.</p>
<p>First, the good:  the Q1300S has about a 15 hour battery life, recharges conveniently off of USB, and is conveniently small in size.  Once you deal with the shenanigans that I&#8217;ll describe below, the unit &#8220;just works&#8221;.  The LED indicators on the front are pretty straightforward.  Overall, the passive industrial design &#8212; the case, the indicators, the static elements &#8212; are quite solid and attractive.</p>
<p>Now, reality:</p>
<p>Physically, the device is small and conveniently sized.  The strap is too tight and, thus, doesn&#8217;t really swivel much.  I can easily replace that.</p>
<p>There are two additional flaws that can&#8217;t be fixed.  First, the unit uses a single button for power and other functions.  It is of poor quality and, after only a few uses, is starting to stick.  A co-worker with the same device has the same problem.</p>
<p>Second, the mini-USB connector is covered by a rubber shield (good!), but that shield flips open to cover the power button (which you need to get to) and actually gets in the way of sticking in the USB cable! Dumb.</p>
<p>From a User Experience perspective, the device is a train wreck.  To turn on, hold the power button for 4 seconds.  It boots and then it starts logging (the LEDs on the front do a pretty good job of giving status, though &#8220;solid&#8221; vs. &#8220;blinking&#8221; for &#8220;looking for GPS&#8221; vs. &#8220;GPS signal good&#8221; is non-obvious).  To turn off logging (convenient for downloading or for just using as a BlueTooth data source), hold down the button two seconds.  To turn off, hold down the button for four seconds.   There is very little visual feedback during this process.</p>
<p>Horrible.  Combined with a button that sticks and it is close to unusable.   I would much rather have two buttons &#8212; power and mode &#8212; without the need to hold either down for any length of time.</p>
<p>To download data, <em>requires that the device be on</em>.   Plugging in the device causes the Battery light to come on &#8212; almost looking like a power indicator.  Of course, if you turn <em>on</em> the device, it&#8217;ll default to logging data.  Expect to always have a dozen or so data points from wherever you happened to be when you downloaded the data.  Remember that rubber gasket thingy from the USB port I mentioned earlier?  The one that covers the power button?  Yes, it is in the way if you need to turn on the device after plugging it in.</p>
<p>Why the damned thing doesn&#8217;t simply turn on when USB power is applied is beyond me.  Better yet, why not let the device mount as a flash drive (some units do, but they had other flaws that made them even worse than the QStarz).</p>
<p>Since it <em>doesn&#8217;t</em> mount as a drive, that means you need some software to retrieve data from the device.   Thankfully, <a href="http://www.houdah.com/houdahGPS/">HoudahGPS</a> to the rescue.  Once configured, it works quite well.  Plug in the unit, make sure it is powered up, and then click the <strong>Acquire</strong> button. Done.</p>
<p>Configuring the device from a Mac is&#8230; unfortunate.</p>
<div class="imgRight"><a href="http://www.flickr.com/photos/49503114554@N01/4424488282" title="View 'Roger &#038; Phone Booth' on Flickr.com"><img title="Roger &#038; Phone Booth"border="0"width=""alt="Roger &#038; Phone Booth"src="http://farm3.static.flickr.com/2741/4424488282_77b70ee4a3.jpg"height=""/></a></div>
<p>The QStarz device is based on the <a href="http://www.google.com/search?rls=en&#038;q=mtk+chipset&#038;ie=UTF-8&#038;oe=UTF-8">MTK chipset</a>.  This is a fairly standard chipset and, thus, there exists open source software for interacting with it.  In particular, you&#8217;ll want <a href="http://www.bt747.org/">BT747</a>.  It is a Java application that can configure, download, and otherwise manage an MTK based device (amongst other).  Via the BT747 software, you can configure the sampling rate of the device. It defaults to once-a-second, but 2 or 3 times a second is useful for tracking relatively fast moving motion that changes directions quickly; biking or driving, for example.</p>
<p>If you want to communicate with the QStarz via BlueTooth (and maybe via USB &#8212; I didn&#8217;t try), go to the Finder and check the <strong><em>Open in 32-bit mode</em></strong> option.</p>
<p>Bottom line; with geotagging of photos becoming pretty much ubiquitous across both photo organization tools and the various websites (flickr, etc), it is only a matter of time &#8212; 12 to 18 months, I would guess &#8212; until pretty much every camera has GPS built in.  Until then, the QStarz 1300S fills the gap.  Not nicely, but it does work.</p>
<p>Heck, not only can I take can take a photo of Roger and one of the very few phone booths left in the state, but I can even show you <a href="http://www.flickr.com/photos/bbum/map/?photo=4424488282&#038;zl=1">exactly where it is (turn on &#8220;Hybrid&#8221; mode to see more than a green blob on the map)</a>!</p>
<p>I am concerned about build quality. The company does monitor twitter, is aware of my power button issue, and is responding extremely proactively (so far).  I&#8217;m impressed and, frankly, if QStarz comes through with their promise to replace my device, it will go far to assuage my disdain for the device.</p>
<p>Now, if QStarz would produce a useful &#8212; simple &#8212; Mac client, that would make me even happier.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.friday.com/bbum/2010/03/11/geotagging-photos-with-aperture-qstarz-bt-1300s/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>objc_msgSend() Tour Part 4: Method Lookup &amp; Some Odds and Ends</title>
		<link>http://www.friday.com/bbum/2010/02/04/objc_msgsend-tour-part-4-method-lookup-some-odds-and-ends/</link>
		<comments>http://www.friday.com/bbum/2010/02/04/objc_msgsend-tour-part-4-method-lookup-some-odds-and-ends/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 06:45:15 +0000</pubDate>
		<dc:creator>bbum</dc:creator>
				<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://www.friday.com/bbum/?p=1726</guid>
		<description><![CDATA[Table of Contents

objc_msgSend() Tour Part 1: The Road Map
objc_msgSend() Tour Part 2: Setting the Stage
objc_msgSend() Tour Part 3: The Fast Path
objc_msgSend() Tour Part 4: Method Lookup &#038; Some Odds and Ends

In the first three parts, I gave an overview, explained a bit of the ABI used by Objective-C, and took a near instruction by instruction [...]]]></description>
			<content:encoded><![CDATA[<p><b>Table of Contents</b></p>
<ol>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-part-1-the-road-map/">objc_msgSend() Tour Part 1: The Road Map</a></li>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-2-setting-the-stage/">objc_msgSend() Tour Part 2: Setting the Stage</a></li>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-3-the-fast-path/">objc_msgSend() Tour Part 3: The Fast Path</a></li>
<li><a href="http://www.friday.com/bbum/2010/02/04/objc_msgsend-tour-part-4-method-lookup-some-odds-and-ends/">objc_msgSend() Tour Part 4: Method Lookup &#038; Some Odds and Ends</a></li>
</ol>
<p>In the first three parts, I gave an overview, explained a bit of the ABI used by Objective-C, and took a near instruction by instruction tour of what happens on the <em>fast path</em> of Objective-C method dispatch.  By <em>fast path</em>, I mean what happens 99.9% of the time; a very fast, no overhead, no function call, no locking, set of instructions that grabs the method implementation from the cache and does a tail-call jump to that implementation.</p>
<p>The <em>slow path</em> is used rarely.  As little as once per unique selector invoked per class with a goal of filling the cache such that the slow path is never used again for that selector/class combination.  A handful of operations will cause a class&#8217;s cache to be flushed;  method swizzling, category loading, and the like.</p>
<p>Note that during <code>+initialize</code>, methods won&#8217;t always be cached.  Yet another reason to <em><a href="http://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not-so-much/">not do any real work during</a> <code>+initialize</code>!</em><span id="more-1726"></span>In <a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-3-the-fast-path/">part 3</a>, the cache lookup loop contained a NULL check and, if NULL was encountered in the cache, then the code jumped to a cache miss label.  It looked like this (with the original source interleaved):</p>
<pre>
// 	movq	buckets(%a5, %a4), %r11	// method = cache->buckets[bytes/8]
0x0000512d  movq        0x10(%r8,%rcx),%r11
// 	testq	%r11, %r11			// if (method == NULL)
0x00005132  testq       %r11,%r11
// 	je	LCacheMiss$1			//   goto cacheMissLabel
0x00005135  je          0x0000515c
</pre>
<p>Note that the disassembly shows that the cache miss label is located at address <code>0x0000515c</code>.  Not at all coincidentally, that is exactly where this particular post&#8217;s tour starts.  Namely, what happens when the cache lookup misses and the cache must be filled.</p>
<p>When I referred to this code path as the <em>slow path</em>, I wasn&#8217;t kidding! This is the one spot where the messenger actually makes a call into a C function which is then responsible for traipsing about the runtime metadata to resolve the method and fill the cache.  Beyond that, the C function &#8212; <code> _class_lookupMethodAndLoadCache()</code> &#8212; is also responsible for ensuring that any <code>+initialize</code> methods of the class (and superclasses) are invoked prior to the method itself being invoked. This also implies that <code>objc_msgSend()</code> must effectively be recursively safe across this particular call site.</p>
<p>And that requirement leads to the need to preserve all of the various registers and push a stack from for the purposes of making the call.  This is actually considerably more involved than a <em>normal</em> call site because the runtime is effectively hijacking the method invocation call to call something totally alien to the original method&#8217;s implementation!</p>
<pre>
0x0000515c  pushq       %rbp
0x0000515d  movq        %rsp,%rbp
0x00005160  subq        $0x000000c0,%rsp
</pre>
<p>The above saves the current stack pointer and then bumps the stack pointer down by 0xc0 (192) bytes.  This is to make room for&#8230;</p>
<pre>
0x00005167  movdqa      %xmm0,0xffffff40(%rbp)
0x0000516f  movdqa      %xmm1,0xffffff50(%rbp)
0x00005177  movdqa      %xmm2,0xffffff60(%rbp)
0x0000517f  movdqa      %xmm3,0xffffff70(%rbp)
0x00005187  movdqa      %xmm4,0x80(%rbp)
0x0000518c  movdqa      %xmm5,0x90(%rbp)
0x00005191  movdqa      %xmm6,0xa0(%rbp)
0x00005196  movdqa      %xmm7,0xb0(%rbp)
0x0000519b  movq        %r10,0xc0(%rbp)
0x0000519f  movq        %rax,0xc8(%rbp)
0x000051a3  movq        %rdi,0xd0(%rbp)
0x000051a7  movq        %rsi,0xd8(%rbp)
0x000051ab  movq        %rdx,0xe0(%rbp)
</pre>
<p>&#8230; all of the registers that need to be pushed onto the stack.  Note that %r10 doesn&#8217;t actually have to be pushed &#8212; it is a scratch register.  Someday, <code>%r10</code> might disappear from that instruction stream.</p>
<pre>
0x000051af  movq        (%rdi),%rdi
0x000051b2  movq        %rsi,%rsi
0x000051b5  callq       __class_lookupMethodAndLoadCache
0x000051ba  movq        %rax,%r11
</pre>
<p>Now we get to the actual function call itself.</p>
<pre>IMP _class_lookupMethodAndLoadCache(Class cls, SEL sel)</pre>
<p>You can find the declaration and implementation in <a href="http://www.opensource.apple.com/source/objc4/objc4-437.1/runtime/objc-class.m">objc-class.m</a>.</p>
<p>If you had read <a href="http://www.sealiesoftware.com/blog/archive/2008/09/22/objc_explain_So_you_crashed_in_objc_msgSend.html">Greg&#8217;s &#8220;So You Crashed in Objc_MsgSend&#8221;</a>, you would know that <code>%rdi</code> contains the first argument and <code>%rsi</code> contains the second argument when calling a function.</p>
<p>The <code> movq        (%rdi),%rdi</code> instruction dereferences the contents of <code>%rdi</code> and shoves the result into <code>%rdi</code>.  Effectively, it grabs the <code>isa</code> of the targeted object and passes it as the first parameter to the function.  In the case of an instance, this will be the class of the instance.  In the case of a class, it will be the metaclass of the class.</p>
<p><s>Frankly, the <code>movq        %rsi,%rsi</code> instruction makes no sense to me.  It is clearly loading the second argument, but it is effectively a no-op since the source and destination are the same and the <code>movq</code> instruction doesn&#8217;t set or reset any of the processor&#8217;s status flags.  Then again, I could easily be missing something.</s></p>
<p>The <code> movq        %rsi,%rsi</code> instruction looks like nonsense in this context.  It is <em>here</em>, but I forgot that this is actually an expanded macro (thanks, Greg, for the explanation!).  If we return to the original source and grab the line from the macro, you will see:</p>
<pre>
	movq	$0, %a1
	movq	$1, %a2
	call	__class_lookupMethodAndLoadCache
</pre>
<p>The <code> movq	$1, %a2</code> instruction generates the <code> movq        %rsi,%rsi</code> instruction when expanded.  Note that the source is a parameter to the macro, though!  For other variants of <code>objc_msgSend()</code> &#8212; for the ones that return values on the stack and not in registers &#8212; <em>the &#8220;self&#8221; argument is actually in <code>%a2</code> and &#8220;_cmd&#8221; is in <code>%a3</code></em>.  Thus, the reason for the sometimes meaningless instruction.</p>
<p>If this particular codepath was performance sensitive to the degree where one or two instructions matters, the assembly macro language <em>does</em> have conditionals that could be used to eliminate the instruction when source and destination are the same.</p>
<p>Finally, the return value is passed back in register <code>%rax</code> and is stowed away into register <code>%r11</code> for use shortly.</p>
<pre>
0x000051bd  movdqa      0xffffff40(%rbp),%xmm0
0x000051c5  movdqa      0xffffff50(%rbp),%xmm1
0x000051cd  movdqa      0xffffff60(%rbp),%xmm2
0x000051d5  movdqa      0xffffff70(%rbp),%xmm3
0x000051dd  movdqa      0x80(%rbp),%xmm4
0x000051e2  movdqa      0x90(%rbp),%xmm5
0x000051e7  movdqa      0xa0(%rbp),%xmm6
0x000051ec  movdqa      0xb0(%rbp),%xmm7
0x000051f1  movq        0xc0(%rbp),%r10
0x000051f5  movq        0xc8(%rbp),%rax
0x000051f9  movq        0xd0(%rbp),%rdi
0x000051fd  movq        0xd8(%rbp),%rsi
0x00005201  movq        0xe0(%rbp),%rdx
0x00005205  movq        0xe8(%rbp),%rcx
0x00005209  movq        0xf0(%rbp),%r8
0x0000520d  movq        0xf8(%rbp),%r9
0x00005211  movq        %rbp,%rsp
0x00005214  popq        %rbp
</pre>
<p>And&#8230; all these instructions are simply to restore all the registers back to the state they were in prior to the call to <code> _class_lookupMethodAndLoadCache()</code>.<br />
&#8232;
<pre>
0x00005215  cmpq        %r11,%r11
0x00005218  jmp         *%r11d
</pre>
<p>Finally, dispatch!  The <code>cmpq</code> resets the status registers to indicate a non-structure return value.  In other words, the above two instructions are no longer contained in the method lookup macro, but are found in the messenger itself (and will be different from the other messengers).</p>
<p>Note that <code>_class_lookupMethodAndLoadCache()</code> will <em>never return NULL</em> and, hence no need for a NULL check above.  If a method isn&#8217;t found, then <code>_class_lookupMethodAndLoadCache()</code> returns the address of the forwarding handler.  Because forwarding may actually come into play often, the forwarding handler is actually put into the cache such that future invocations can leverage the fast path.</p>
<p>That is it;  that is both the fast and the slow path of method invocation. </p>
<hr />
<p>But what are these instructions??  There appear to be some leftovers!?!</p>
<pre>
0x0000521b  movq        0x000b32be(%rip),%rdi
0x00005222  testq       %rdi,%rdi
0x00005225  jneq        0x0000510a
0x0000522b  movq        $0x00000000,%rax
0x00005232  movq        $0x00000000,%rdx
0x00005239  xorps       %xmm0,%xmm0
0x0000523c  xorps       %xmm1,%xmm1
0x0000523f  ret
</pre>
<p>Way back as the very first two instructions to <code>objc_msgSend()</code> there was a nil check.  If the target of method invocation is nil, then <code> jeq         0x0000521b</code>.</p>
<p>This is the nil handling code.  The last five instructions &#8212; the two <code>movq</code>, two <code>xorps</code>, and <code>ret</code> &#8212; take care of actually zeroing out all of the return value registers and returning control to the caller.  This also explains why not <em>some</em> types of return values are undefined on message-to-nil.  Message-to-nil can only safely zero out values that are returned in the return registers.  There isn&#8217;t enough metadata in the C ABI to know how much of the stack to zero for values returned on the stack.</p>
<p>THe first three instructions load the value &#8212; <code>movq        0x000b32be(%rip),%rdi</code> &#8212;  contained in the <code>_objc_nilReceiver</code> global into the register <code>%rdi</code>.  The <code> testq       %rdi,%rdi</code> instruction sets the processor&#8217;s <code>zero flag</code> in the status register if the value contained in <code>%rdi</code> is zero.  The <code>jneq        0x0000510a</code> instruction will jump if the value is not zero.  That address is actually <em>back</em> into <code>objc_msgSend</code> and, in particular, basically does a dispatch to the nil message receiver with the same selector.</p>
<p>I wrote up <a href="http://www.friday.com/bbum/2008/01/02/objective-c-logging-messages-to-nil/">how to write your own nil receiver</a> quite some time ago.</p>
<pre>
0x00005240  movq        %rdi,%rax
0x00005243  ret
</pre>
<p>These final two instructions are what happens when you invoke one of the ignored selectors under GC.  It effectively causes the method to <code>return self;</code> by moving the target of the method call from the first argument register <code>%rdi</code> into the return value register <code>%rax</code>.</p>
<p>Note that this is also the reason why <code>-retainCount</code> returns such an outrageous value under GC;  it is the address of the object.</p>
<hr />
<p>There you have it.  That is every instruction that may be executed in <code>objc_msgSend()</code> from beginning to end.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.friday.com/bbum/2010/02/04/objc_msgsend-tour-part-4-method-lookup-some-odds-and-ends/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using malloc to Debug Memory Misuse in Cocoa</title>
		<link>http://www.friday.com/bbum/2010/01/10/using-malloc-to-debug-memory-misuse-in-cocoa/</link>
		<comments>http://www.friday.com/bbum/2010/01/10/using-malloc-to-debug-memory-misuse-in-cocoa/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 01:08:14 +0000</pubDate>
		<dc:creator>bbum</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.friday.com/bbum/?p=1703</guid>
		<description><![CDATA[Every few months, there is a discussion on cocoa-dev or a question on stackoverflow.com that basically boils down to &#8220;I have a leak or over-release and I can&#8217;t use Instruments to debug it. Help?&#8221;.
Quite often, the questioner can actually use Instruments just fine, but simply lacks the know-how or hasn&#8217;t tried in a while and [...]]]></description>
			<content:encoded><![CDATA[<p>Every few months, there is a discussion on <a href="http://lists.apple.com/mailman/listinfo/cocoa-dev">cocoa-dev</a> or a question on <a href="http://stackoverflow.com/questions/tagged/objective-c">stackoverflow.com</a> that basically boils down to <em>&#8220;I have a leak or over-release and I can&#8217;t use Instruments to debug it. Help?&#8221;</em>.</p>
<p>Quite often, the questioner <em>can</em> actually use <a href="http://developer.apple.com/mac/library/DOCUMENTATION/DeveloperTools/Conceptual/InstrumentsUserGuide/Introduction/Introduction.html">Instruments</a> just fine, but simply lacks the know-how or hasn&#8217;t tried in a while and doesn&#8217;t realize that Instruments has improved significantly with each release of the developer tools.  No, really, Instruments is a fantastic tool and I use it whenever I can;  what you see below is for the exceptional case, not the norm.</p>
<p>There are cases where using Instruments is either inconvenient or impractical.  Namely, trying to track down an intermittent crasher or trying to gain insight into memory leaks over a long running session will create a prohibitively large dataset for Instruments to process (Instruments allows for much more detailed analysis of the object graph and this analysis loads a lot more data than the tools I&#8217;ll demonstrate below).</p>
<p>Thus, it is helpful to be familiar with the rather powerful set of tools available from the command line and within the debugger.</p>
<p>Almost always, you are going to want to enable a bit of additional data via the malloc infrastructure.  Have a look at the <a href="x-man-page://malloc">malloc(3) man page</a>.  There is an entire section devoted to <strong>ENVIRONMENT</strong> variables and there are a handful of extremely useful variables!</p>
<p>First and foremost, you are almost <em>always going to want to use <strong><code><a href="http://developer.apple.com/mac/library/releasenotes/DeveloperTools/RN-MallocOptions/index.html">MallocStackLoggingNoCompact</a></code></strong></em>.   When enabled, <em>malloc stack logging</em> writes the stack trace of every allocation and free event to an efficiently compact binary file in /tmp/ (it used to be in memory and, thus, used to be a great way to exhaust heap.  No longer!!).  Unfortunately, it doesn&#8217;t record the retain and release events, but simply knowing <em>where</em> the object was allocated is generally quite useful (it is generally relatively easy to track down who retained an object once you know which object it is).  Under GC, you can set the <code>AUTO_REFERENCE_COUNT_LOGGING</code> and <code>CFRetain/CFRelease</code> events <em>will</em> be logged to the malloc history.</p>
<p>You can then use the <strong><code><a href="x-man-page://malloc_history">malloc_history</a></code></strong> command line tool to query for all events related to a particular address in memory.</p>
<p>While <code>malloc_history</code> requires that the process still exists, it doesn&#8217;t have to be running!  If you run your app under <strong>gdb</strong>, you can still use <code>malloc_history</code> to query the application even when it is stopped in the debugger!</p>
<p>Speaking of gdb, you can use the <code>info malloc</code> command in <strong>gdb</strong> to query the same information.   Under GC, the <code>info gc-roots</code> and <code>info gc-referers</code> commands can be used to interrogate the collector for information about the connectivity of the object graph in your running application.</p>
<p>If you enable zombies via setting the <code>NSZombieEnabled</code> environment variable to YES, the address spewed in the error message when messaging a zombie can be passed directly to <code>malloc_history</code>.</p>
<p>The <code><a href="x-man-page://leaks">leaks</a></code> command line tool scans memory and detects leaks in the form of allocations of memory for which the address to that memory is not stored anywhere else within the application.   The <code>leaks</code> tool has been vastly improved in the Snow Leopard release of the Xcode tools; it is much <em>much</em> faster and spits out false positives almost never.   It is still possible to have a leak that <code>leaks</code> cannot detect, of course.  And, remember, even if you can still <em>reach</em> memory, it is still a total waste if you never <em>use</em> that memory&#8217;s contents again!</p>
<p>So, that is a brief summary of the state of command line memory debugging on Mac OS X as of Snow Leopard.  Of course, that&#8217;s just a bunch of words.  How about an example?</p>
<p><span id="more-1703"></span>The code:</p>
<pre>#import &lt;Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    BOOL doLeak = !!getenv("leak");
    id o = [NSObject new];
    o = [NSMutableSet new];
    if (doLeak) {
        // leak some memory
        [o retain];
        [o release];
        [o retain];
        [o autorelease];
        o = @"Uncle";
    } else {
        // message an overreleased object
        [o autorelease];
        [o release];
        o = @"Bob";
    }
    [pool drain];
    sleep(4242424242);
    return 0;
}
</pre>
<p>If you create a standard Cocoa Command Line Tool project and paste the above into the main file, you will have effectively created the tool I used for the below examples.</p>
<p><strong>Detecting Leaks</strong></p>
<p>To test for leaks, you&#8217;ll want to use the <code>leaks</code> command line tool, generally.</p>
<p>You can either set the environment variables in the shell and then run the command or do it all at once:</p>
<pre>env MallocStackLoggingNoCompact=YES leak=YES /tmp/bbum-products/Debug/MemoryMunchies</pre>
<p>Or, in <code>gdb</code> you can use the <code>set env</code> to set the environment variables prior to a run.</p>
<p>In any case, when you run the tool with the environment variables set as above, you&#8217;ll see spewage like this:</p>
<pre>
MemoryMunchies(56604) malloc: recording malloc stacks to disk using standard recorder
MemoryMunchies(56604) malloc: stack logging compaction turned off; size of log files on disk can increase rapidly
MemoryMunchies(56604) malloc: stack logs being written into /tmp/stack-logs.56604.MemoryMunchies.z05dcb.index
</pre>
<p>Now, you can use the <code>leaks</code> command to scan for leaks:</p>
<pre>
% leaks 56604
Process 56604: 845 nodes malloced for 204 KB
Process 56604: 2 leaks for 64 total leaked bytes.
Leak: 0x10010c8e0  size=48  zone: DefaultMallocZone_0x100004000	instance of 'NSCFSet', type ObjC, implemented in Foundation
	0x70d06df8 0x00007fff 0x00001080 0x00000001 	.m.p............
	0x00000001 0x00000000 0x00000000 0x00010000 	................
	0x70ef7268 0x00007fff 0x00000000 0x00000000 	hr.p............
	Call stack: [thread 0x7fff7087cbe0]: | start | main | -[__NSPlaceholderSet initWithCapacity:]
| CFSetCreateMutable | CFBasicHashCreate | _CFRuntimeCreateInstance
| malloc_zone_malloc
Leak: 0x100108ee0  size=16  zone: DefaultMallocZone_0x100004000	instance of 'NSObject', type ObjC, implemented in CoreFoundation
	0x70f124a8 0x00007fff 0x00000000 0x00000000 	.$.p............
	Call stack: [thread 0x7fff7087cbe0]: | start | main | +[NSObject(NSObject) new]
| +[NSObject(NSObject) allocWithZone:] | _internal_class_createInstanceFromZone
| calloc | malloc_zone_calloc
</pre>
<p>Note that there are actually two leaks here!  I had inadvertently left in an extra object allocation as I hacked up that bit of code!  Oops.</p>
<p>Or, if I had used Object Alloc in Instruments to grab the address of an interesting object <em>or</em> if I had an <code>NSLog()</code> somewhere that dumped the address of an interesting object (use <code>%p</code> to print pointers nicely), then I could use the <code>malloc_history</code> command to find more information:</p>
<pre>% malloc_history 56604 0x10010c8e0
ALLOC 0x10010c8e0-0x10010c90f [size=48]: thread_7fff7087cbe0 |start | main
| -[__NSPlaceholderSet initWithCapacity:] | CFSetCreateMutable | CFBasicHashCreate
| _CFRuntimeCreateInstance | malloc_zone_malloc
</pre>
<p>In any case, both <code>leaks</code> and <code>malloc_history</code> make it abundantly clear that the allocation event occurred in the <code>main()</code> function.  You will quickly learn to ignore the implementation details of the frameworks that these tools expose.</p>
<p>Note that it is quite helpful to enable scribbling via the Malloc environment variables.  This will overwrite memory with a known set of non-pointer-esque values upon allocation and deallocation, thus preventing stale data from hiding leaks.</p>
<p><strong>Debugging Crashes</strong></p>
<p>Just like <code>MallocStackLoggingNoCompact</code>, zombies can be enabled via an environment variable; <code>NSZombieEnabled</code>.  Or more specifically:</p>
<pre>env MallocStackLoggingNoCompact=YES NSZombieEnabled=YES /tmp/bbum-products/Debug/MemoryMunchies</pre>
<p>Of course, the app just crashes, leaving you without a process to interrogate.  The log files in /tmp/ can&#8217;t be interrogated without the process still around.</p>
<p>So, we need to run it in gdb.  Being lazy, I just do:</p>
<pre>env MallocStackLoggingNoCompact=YES NSZombieEnabled=YES gdb /tmp/bbum-products/Debug/MemoryMunchies</pre>
<p>There&#8217;ll be a bunch of malloc spewage as various sub-processes are launched and reaped.  It can be safely ignored.  Or, if you want, you could set up the instance variables in gdb:</p>
<pre>
% gdb /tmp/bbum-products/Debug/MemoryMunchies
(gdb) set env MallocStackLoggingNoCompact=YES
(gdb) set env NSZombieEnabled=YES
(gdb) r
Reading symbols for shared libraries .++++....................... done
MemoryMunchies(57523) malloc: recording malloc stacks to disk using standard recorder
MemoryMunchies(57523) malloc: stack logging compaction turned off; size of log files on disk can increase rapidly
MemoryMunchies(57523) malloc: stack logs being written into /tmp/stack-logs.57523.MemoryMunchies.E2tMo1.index
2010-01-10 16:49:47.564 MemoryMunchies[57523:903] *** -[CFSet release]: message sent to deallocated instance 0x10010d680
Program received signal SIGTRAP, Trace/breakpoint trap.
0x00007fff880ede36 in ___forwarding___ ()
(gdb)
</pre>
<p>At this point, the <code>malloc_history</code> command line tool will still work just fine.  However, you can also interrogate malloc state from within gdb itself:</p>
<pre>
(gdb) info malloc 0x10010d680
Alloc: Block address: 0x000000010010d680 length: 48
Stack - pthread: 0x7fff7087cbe0 number of frames: 7
    0: 0x7fff84b4ea6e in malloc_zone_malloc
    1: 0x7fff8806e445 in _CFRuntimeCreateInstance
    2: 0x7fff8806e230 in CFBasicHashCreate
    3: 0x7fff8808af01 in CFSetCreateMutable
    4: 0x7fff880c809e in -[__NSPlaceholderSet initWithCapacity:]
    5: 0x100000e02 in main at /tmp/MemoryMunchies/MemoryMunchies.m:7
    6: 0x100000d70 in start
</pre>
<p>Note that if there are multiple allocation events at that address, the events will be printed in <em> chronological order</em>.  That is, oldest &#8212; and most interesting &#8212; events will be last.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.friday.com/bbum/2010/01/10/using-malloc-to-debug-memory-misuse-in-cocoa/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>objc_msgSend() Tour Part 3: The Fast Path</title>
		<link>http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-3-the-fast-path/</link>
		<comments>http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-3-the-fast-path/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 17:27:17 +0000</pubDate>
		<dc:creator>bbum</dc:creator>
				<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://www.friday.com/bbum/?p=1665</guid>
		<description><![CDATA[Table of Contents

objc_msgSend() Tour Part 1: The Road Map
objc_msgSend() Tour Part 2: Setting the Stage
objc_msgSend() Tour Part 3: The Fast Path
objc_msgSend() Tour Part 4: Method Lookup &#038; Some Odds and Ends

In any case, with the foundation set &#8212; with the id of the object to be targeted in %rdi and the selector of the method [...]]]></description>
			<content:encoded><![CDATA[<p><b>Table of Contents</b></p>
<ol>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-part-1-the-road-map/">objc_msgSend() Tour Part 1: The Road Map</a></li>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-2-setting-the-stage/">objc_msgSend() Tour Part 2: Setting the Stage</a></li>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-3-the-fast-path/">objc_msgSend() Tour Part 3: The Fast Path</a></li>
<li><a href="http://www.friday.com/bbum/2010/02/04/objc_msgsend-tour-part-4-method-lookup-some-odds-and-ends/">objc_msgSend() Tour Part 4: Method Lookup &#038; Some Odds and Ends</a></li>
</ol>
<p>In any case, with the foundation set &#8212; with the id of the object to be targeted in <code>%rdi</code> and the selector of the method to be invoked in <code>%rsi</code> &#8212; we can jump into <code>objc_msgSend()</code> and understand exactly what happens instruction by instruction.  Or more specifically, the compiler issues a <code>call</code> into <code>objc_msgSend()</code> (which sets up a stackframe for <code>objc_msgSend()</code> which, through tail call optimization, turns into the stackframe for the called method) and the method implementation that <code>objc_msgSend()</code> jumps to will issue a <code>ret</code> instruction to unwind the stack back to the original caller&#8217;s frame.</p>
<p>It is pretty easy to correlate the disassembly with the comments and code in the <a href="http://www.opensource.apple.com/source/objc4/objc4-437.1/runtime/Messengers.subproj/objc-msg-x86_64.s">original source file</a>. However, if you ever need to step through the messenger (<code>si</code> steps by instruction in gdb), this will be easier to follow as this is closer to the reality during a debug session.</p>
<p>For almost all method dispatches, dispatch takes what is called the &#8220;fast path&#8221;.  That is, <code>objc_msgSend()</code> finds the implementation in the method cache and passes control to the implementation.   Since this is the most common path, it is a good opportunity to break the tour of <code>objc_msgSend()</code> into two parts;  the fast path and the slow path (with administrivia).</p>
<p><span id="more-1665"></span>
<ol>
<li><strong>Check for ignored selectors (GC) and short-circuit.</strong>
<pre>
// this is the first instruction of objc_msgSend
0x000050f4  cmpq        $0xfffeb010,%rsi
0x000050fb  jeq         0x00005240                    return;
</pre>
<p>The <code>cmpq</code> instruction compares the selector of the method call in register <code>%rsi</code> with the value <code>$0xfffeb010</code>.  If equal, then a jump to a couple of instruction below is made.  Those instructions effectively return <code>self</code> to the caller as the result of the message send.</p>
<p>Under GC, the selectors <code>retain</code>, <code>release</code>, <code>autorelease</code>, <code>retainCount</code> and <code>dealloc</code> are re-mapped to the ignored selector.  Thus, when any of these methods are invoked under GC, <code>objc_msgSend()</code> very quickly returns <code>self</code> without otherwise doing anything.  In dual-mode code, a great percentage of method calls are these ignored selectors and, thus, this makes dual-mode code faster (while not significantly penalizing non-GC code;  a fraction of a percent overhead in a typical application).
</li>
<li><strong>Check for nil target.</strong></li>
<pre>
0x00005101  testq       %rdi,%rdi
0x00005104  jeq         0x0000521b
</pre>
<p>The <code>testq</code> instruction is effectively an AND of the operand without storing the resulting bits. &#8220;Odd&#8221;, you say, &#8220;why AND something with itself?&#8221;.   As it turns out, this is the fastest way to test to see if something is 0.   Effectively, this is testing the target of the method invocation &#8212; the <code>self</code> parameter &#8212; to see if it is zero.  If it is zero, the zero status flag (a bit in the CPU&#8217;s status register) will be set and the <code>JEQ</code> or <code>jump if equal</code> will check the zero flag and make the jump if it is set.</p>
<p>What happens at <code>0x0000521b</code> is explained below.</p>
<li><strong>Find the IMP on the class of the target and jump to it</strong></li>
<pre>
0x0000510a  movq        (%rdi),%r11
</pre>
<p>Now we are into the actual dispatch process.  The first step is to grab the class of the target object.  To do this, the contents of register <code>%rdi</code> are dereferenced and the result is put into <code>%r11</code>.  Remember that the first instance variable in <code>NSObject</code> is the object&#8217;s <code>isa</code> pointer where the <code>isa</code> is really just a pointer to the class of the object!</p>
<p>Thus, this code grabs a pointer to the class of the object (or the metaclass of the class, if we are messaging a class object) and shoves it into <code>%r11</code>.</p>
<p>Once we have that, the search is on!</p>
</ol>
<ol>
<li><strong>Search the class&#8217;s method cache for the method IMP</strong></li>
<p>This next set of instructions is actually the <code>CacheLookup</code> macro, if you are looking at the <a href="http://www.opensource.apple.com/source/objc4/objc4-437.1/runtime/Messengers.subproj/objc-msg-x86_64.s">original source file</a>.</p>
<pre>
0x0000510d  movq        %rcx,0xe0(%rsp)
0x00005112  movq        %r8,0xe8(%rsp)
0x00005117  movq        %r9,0xf0(%rsp)
</pre>
<p>Any time you see a chunk of code that involves a sequence of <code>movq</code> operations with the source operand being registers and the destination being a series of <code>(%rsp)</code> relative destinations, you can pretty much assume that the contents of the registers are being pushed onto the stack for preservation and that you&#8217;ll find pretty much the exact same sequence of instructions with operands reversed near the end of the code block.</p>
<p>In this case, it is preserving registers <code>%r9</code>, <code>%r8</code> and <code>%rcx</code>.  Most likely because those registers are going to be used during cache lookup!</p>
<p>And this is the actual cache lookup code.  It is rather dense.</p>
<pre>
0x0000511c  movq        0x10(%r11),%r8
0x00005120  movl        (%r8),%r9d
0x00005123  shlq        $0x03,%r9
0x00005127  movq        %rsi,%rcx
0x0000512a  andq        %r9,%rcx
0x0000512d  movq        0x10(%r8,%rcx),%r11
0x00005132  testq       %r11,%r11
0x00005135  je          0x0000515c
0x00005137  addq        $0x08,%rcx
0x0000513b  andq        %r9,%rcx
0x0000513e  cmpq        (%r11),%rsi
0x00005141  jne         0x0000512d
</pre>
<p>The source, though, is not quite so dense.  The above is produced by this bit of assembly in a macro:</p>
<pre>
	movq	cache(%r11), %a5 // cache = class->cache
	//
	movl	mask(%a5), %a6d
	shlq	$$3, %a6		 // %a6 = cache->mask < < 3
	mov	$0, %a4			     // bytes = sel
	andq	%a6, %a4		 // bytes &#038;= (mask << 3)
</pre>
<p>This grabs the cache out of the class and then sets up the various bits used to look in the cache for the method entry corresponding to the selector.  The "method triplet" alluded to near the end is a triplet of data containing the selector, the IMP (the function pointer that is the method's implementation), and a C string containing type identifiers for the arguments (and return value) of the method.  The goal of the following code is to find that triplet or jump to the code that loads the cache (the slow path).</p>
</pre>
<pre>
	//
	// search the receiver's cache
	// r11 = method (soon)
	// a4 = bytes
	// a5 = cache
	// a6 = mask < < 3
	// $0 = sel
LMsgSendProbeCache_$1:
	movq	buckets(%a5, %a4), %r11	// method = cache->buckets[bytes/8]
	testq	%r11, %r11			// if (method == NULL)
	je	LCacheMiss$1			//   goto cacheMissLabel
	//
	addq	$$8, %a4			// bytes += 8
	andq	%a6, %a4			// bytes &#038;= (mask < < 3)
	cmpq	method_name(%r11), $0		// if (method_name != sel)
	jne	LMsgSendProbeCache_$1	//   goto loop
	//
	// cache hit, r11 = method triplet
	//
</pre>
<p>This is the actual cache lookup code.  It loops across the cache and searches for an entry that has the same SEL as the desired selector.  Note that the selector <em>is</em> a C string, but the selectors are also uniqued, thus allowing the cache lookup to simply compare the string address -- the SEL -- with the one in the cache entry (the <code>cmpq</code> instruction).   If a NULL is encountered, the cache has been exhausted and, thus, execution jumps to the cache miss handler (the <code>LCacheMiss$1</code> label).</p>
<p>This assembly looks a little different than most because it is actually a macro and, thus, is expanded into the instruction stream when used.  Thus, when you see things like <code>$0</code> and <code>$1</code> those are actually the parameters passed to the macro.  Because jumping to a label is a common task and because the macro is expanded multiple times, the label contains an argument such that the label can be made unique per use.</p>
</pre>
<pre>
0x00005143  movq        0xe0(%rsp),%rcx
0x00005148  movq        0xe8(%rsp),%r8
0x0000514d  movq        0xf0(%rsp),%r9
</pre>
<p>Restore the previously preserved preserved register values.</p>
<pre>
0x00005152  movq        0x10(%r11),%r11
0x00005156  cmpq        %r11,%r11
0x00005159  jmp         *%r11d
</pre>
<p>IMP was found! Or, actually, the address of the structure containing the cache entry for the method &#8212; the method triplet &#8212; was put into <code>%r11</code>.   The <code>movq</code> with source <code>0x10(%r11)</code> dereferences the address in <code>%r11</code> and copies a quad-words worth of data from that address plus an offset of <code>0x10</code>, which is where the IMP is stored.</p>
<p><code>jmp</code> is an unconditional jump.  The IMP that was stored into <code>%r11</code> <em>will</em> be jumped to.  So, why the comparison-to-same without testing in the line prior?  That instruction clears and sets various status flags that are used by the x86_64 ABI to determine what kind of call is being made.</p>
<p>If you were to look at <a href="http://www.opensource.apple.com/source/objc4/objc4-437.1/runtime/Messengers.subproj/objc-msg-x86_64.s">the source</a>, you would see the comment <code>// set nonstret (eq) for forwarding</code>.   &#8220;nonstret&#8221; refers to <em>non-structure return</em>.  The Objective-C forwarding mechanism needs to know whether the method returns a structure because, if so, the <code>self</code> and <code>_cmd</code> arguments will be in <em>different registers</em>.  Normally, the C compiler takes care of these shenanigans automatically (including when to turn method calls into calls to <code>objc_msgSend_stret()</code> or <code>objc_msgSend_fpret()</code>), but the forwarding mechanism has to be able to take apart the stack frame and, thus, needs to have a means of detecting which function ABI is in use.</p>
<p>Greg Parker, as often is the case, has a brilliant post discussion <a href="http://www.sealiesoftware.com/blog/archive/2008/10/30/objc_explain_objc_msgSend_stret.html">why <code>objc_msgSend_stret()</code> exists</a>.  There is also &#8212; and equally as <a href="http://www.sealiesoftware.com/blog/archive/2008/11/16/objc_explain_objc_msgSend_fpret.html">well described on Greg&#8217;s weblog</a> &#8212; <code>objc_msgSend_fpret()</code> that is used to handle certain kinds of floats/double (the set changes per architecture).</p>
</ol>
<p>What follows is the rest of the instruction stream that is used to handle the &#8220;slow path&#8221;.  That is, is used to fully resolve methods when not found in the cache.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-3-the-fast-path/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>objc_msgSend() Tour Part 2: Setting the Stage</title>
		<link>http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-2-setting-the-stage/</link>
		<comments>http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-2-setting-the-stage/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 17:16:49 +0000</pubDate>
		<dc:creator>bbum</dc:creator>
				<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://www.friday.com/bbum/?p=1663</guid>
		<description><![CDATA[Table of Contents

objc_msgSend() Tour Part 1: The Road Map
objc_msgSend() Tour Part 2: Setting the Stage
objc_msgSend() Tour Part 3: The Fast Path
objc_msgSend() Tour Part 4: Method Lookup &#038; Some Odds and Ends

Objective-C is, ultimately, a simple set of extensions to C that provide an object oriented coding and runtime model.   Objective-C fully embraces C [...]]]></description>
			<content:encoded><![CDATA[<p><b>Table of Contents</b></p>
<ol>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-part-1-the-road-map/">objc_msgSend() Tour Part 1: The Road Map</a></li>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-2-setting-the-stage/">objc_msgSend() Tour Part 2: Setting the Stage</a></li>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-3-the-fast-path/">objc_msgSend() Tour Part 3: The Fast Path</a></li>
<li><a href="http://www.friday.com/bbum/2010/02/04/objc_msgsend-tour-part-4-method-lookup-some-odds-and-ends/">objc_msgSend() Tour Part 4: Method Lookup &#038; Some Odds and Ends</a></li>
</ol>
<p>Objective-C is, ultimately, a simple set of extensions to C that provide an object oriented coding and runtime model.   Objective-C fully embraces C and leverages the C calling ABI throughout.   Every method call is really just a C function call with <code>objc_msgSend()</code> acting as the preamble that figures out exactly <em>which</em> C function &#8212; which method &#8212; to call!</p>
<p>Thus, it is helpful to understand how <code>objc_msgSend()</code> is called and how that relates to C.  That is, how does the compiler translate <code>[someObject doSomething: 0x2a]</code> into a call.</p>
<p>What follows is a bit of code that makes a [totally bogus] simple method call followed by the assembly generated.</p>
<pre>
Code:
@interface NSObject(foo)
- (id) doSomething: (NSUInteger) index;
@end
...
    NSObject *b;
    NSArray *a;
    b = [a doSomething: 0x2a]; // line 11
Assembly:
    .loc 1 11 0
    movq	-16(%rbp), %rdi
    movq	L_OBJC_SELECTOR_REFERENCES_0(%rip), %rsi
    movl	$42, %edx
    call	_objc_msgSend
    movq	%rax, -8(%rbp)
</pre>
<p><span id="more-1663"></span>If you went and poked about in the <a href="http://www.intel.com/technology/intel64/index.htm">x86_64</a> <a href="http://www.amd.com/us-en/Processors/DevelopWithAMD/0,,30_2252_875_7044,00.html">ABI</a> specification (either of those links will work), you would recognize the above as code that sets up a call to a function &#8212; to _<code>objc_msgSend()</code> &#8212; and then stores the return value a local variable.</p>
<p>That is, <code>objc_msgSend()</code> and, by inference of being tail call optimized and not screwing with registers or stack layout, the method implementations themselves are just standard C functions that follow standard C ABI conventions.</p>
<p>Or, to put it another way, any method can be rewritten as an equivalent C function.  The equivalent C function for the <code>doSomething:</code> method above could be declared as:</p>
<pre>
id doSomething(id self, SEL _cmd, NSUInteger index) { ... }
</pre>
<p>And, sure enough, if we call that function, we get functionally equivalent assembly code generated:</p>
<pre>
    b = doSomething(a, @selector(doSomething:), 0x2b); // line 16
    .loc 1 16 0
    movq	L_OBJC_SELECTOR_REFERENCES_0(%rip), %rsi
    movq	-16(%rbp), %rdi
    movl	$43, %edx
    call	_doSomething
    movq	%rax, -8(%rbp)
</pre>
<p>In particular, on the x86_64 architecture for this particular simple function or method call, the arguments (again, this is only for a simple set of non-struct arguments and return values) will fall into a series of registers in the CPU across the call boundary.</p>
<p>Specifically, the <code>self</code> parameter will be found in <code>%rdi</code>, <code>_cmd</code> in <code>%rsi</code>, and the first declared argument in <code>%edx</code>, followed by <code>%ecx</code>, <code>%r8d</code>, <code>%r9d</code>, and then arguments are pushed onto the stack.  Once again, this assumes that the arguments are all of simple type &#8212; integers, ids, pointers, etc&#8230; &#8212; and the rules change with structures and other non-trivial types.   Actually, this is another good reason for objc_msgSend to not mess with the stack and registers as the ABI rules are both rather complex and there simply isn&#8217;t enough information available at runtime to go off changing argumentation across the messaging boundary (much less do so efficiently)!</p>
<p>We now have enough information to know what state the CPU is in when the call to <code>objc_msgSend()</code> is made.  Next up will be the most typical method dispatch.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-2-setting-the-stage/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>objc_msgSend() Tour Part 1: The Road Map</title>
		<link>http://www.friday.com/bbum/2009/12/18/objc_msgsend-part-1-the-road-map/</link>
		<comments>http://www.friday.com/bbum/2009/12/18/objc_msgsend-part-1-the-road-map/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 17:11:05 +0000</pubDate>
		<dc:creator>bbum</dc:creator>
				<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://www.friday.com/bbum/?p=1657</guid>
		<description><![CDATA[What follows (across this and 3 more posts, maybe more) is a rather detailed tour of objc_msgSend() as implemented in Mac OS X 10.6.2.  Rather detailed in that every instruction will be explained.  Even though it is relatively few instructions, there is a considerable amount of background information that is helpful to understanding [...]]]></description>
			<content:encoded><![CDATA[<p>What follows (across this and 3 more posts, maybe more) is a rather detailed tour of <code>objc_msgSend()</code> as implemented in Mac OS X 10.6.2.  <em>Rather detailed</em> in that every instruction will be explained.  Even though it is relatively few instructions, there is a considerable amount of background information that is helpful to understanding the <code>objc_msgSend()</code> instruction stream.</p>
<p>The motivation behind these posts is entirely selfish.  I find the best way for me to learn something is to know it well enough to be able to explain any detail to a room full of folks in full-blown student mode.</p>
<p><b>Table of Contents</b></p>
<ol>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-part-1-the-road-map/">objc_msgSend() Tour Part 1: The Road Map</a></li>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-2-setting-the-stage/">objc_msgSend() Tour Part 2: Setting the Stage</a></li>
<li><a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-3-the-fast-path/">objc_msgSend() Tour Part 3: The Fast Path</a></li>
<li><a href="http://www.friday.com/bbum/2010/02/04/objc_msgsend-tour-part-4-method-lookup-some-odds-and-ends/">objc_msgSend() Tour Part 4: Method Lookup &#038; Some Odds and Ends</a></li>
</ol>
<hr />
<p><span id="more-1657"></span>For a variety of reasons, I oft find myself staring at streams of x86_64 instructions.  This is often the stream of instructions that sit at the very core of Objective-C and dispatch each and every method call.  That is, <code>objc_msgSend()</code>.</p>
<p>Well, technically, a handful of different versions of <code>objc_msgSend()</code>, each written to handle the calling conventions required to deal with various return types under the x86_64 ABI (Application Binary Interface).  Oh, and the vtable dispatch stuff (different post).</p>
<p>Obviously, <code>objc_msgSend()</code> is called 10s of millions of times simply booting the system and launching some apps.  Thus, every cycle counts and, no surprise, <code>objc_msgSend()</code> is written in hand tuned assembly.  Of all of the other performance optimizations and implementation details in this code, there are three that I find particularly notable.</p>
<p><strong>Don&#8217;t Mess With Registers (unless absolutely necessary)</strong><br />
<strong>Tail Call Optimized</strong><br />
<strong>Don&#8217;t Mess with the Argument List</strong></p>
<p>These are really all three part of the same thing (i.e. some arguments are in registers, for example).  <code>objc_msgSend()</code> is designed to dynamically determine the implementation of a method &#8212; the function pointer that is the IMP tied to the selector on the targeted instance &#8212; <em>without changing any of the caller/callee state</em>.   This enables a tail-call optimization that allows <code>objc_msgSend()</code> to jump [JMP] directly to the implementation of a method.</p>
<p>This is also the reason why you don&#8217;t see <code>objc_msgSend()</code> in backtraces save for when a crash occurs in <code>objc_msgSend()</code>.  Given that there were several 10s of millions of invocations of <code>objc_msgSend()</code> prior to the one that crashed, you can pretty much always assume that the crash is because of a bad pointer being passed to <code>objc_msgSend()</code> and <em>not</em> due to a bug in <code>objc_msgSend()</code> itself.  Of course, if you find yourself crashing in <code>objc_msgSend()</code>, <a href="http://www.sealiesoftware.com/blog/archive/2008/09/22/objc_explain_So_you_crashed_in_objc_msgSend.html">go read and then re-read this</a>.</p>
<p>This relative handful of instructions &#8212; 76 in the disassembly below (taken on Snow Leopard 10.6.2 &#8212; <a href="http://www.opensource.apple.com/source/objc4/objc4-437.1/">objc-437.1</a>), most of which are not executed in a typical method dispatch &#8212; does an awful lot of stuff upon each invocation.</p>
<p>Namely:</p>
<ol>
<li>Check for ignored selectors (GC) and short-circuit.</li>
<li>Check for nil target.</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;If nil &#038; nil receiver handler configured, jump to handler</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;If nil &#038; no handler (default), cleanup and return.</li>
<li>Find the IMP on the class of the target and jump to it</li>
</ol>
<ol>
<li>Search the class&#8217;s method cache for the method IMP</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;If found, jump to it.</li>
<li>Not found: lookup the method IMP in the class itself</li>
<li>&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;If found, jump to it.
</li>
<li>If not found, jump to forwarding mechanism.</li>
</ol>
<p>The next part will set the stage for diving into the actual <code>objc_msgSend()</code> stream.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.friday.com/bbum/2009/12/18/objc_msgsend-part-1-the-road-map/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>DPhyllotaxis</title>
		<link>http://www.friday.com/bbum/2009/10/25/dphyllotaxis/</link>
		<comments>http://www.friday.com/bbum/2009/10/25/dphyllotaxis/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 04:10:23 +0000</pubDate>
		<dc:creator>bbum</dc:creator>
				<category><![CDATA[Entertainment]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://www.friday.com/bbum/?p=1574</guid>
		<description><![CDATA[
 Ultimately, the whole point of resurrecting my old screensaver code was to finally port DPhyllotaxis to Snow Leopard.
Beyond being, perhaps, the most over-engineered screen saver ever for what ultimately draws colored dots, I wrote this as a sort of virtual flower for my then-girlfriend, now-wife-of-more-than-a-decade, Christine.
The underlying algorithm on this one is based entirely [...]]]></description>
			<content:encoded><![CDATA[<div class="imgLeft"><img src="http://www.friday.com/bbum/wp-content/uploads/2009/10/Screenalicious-DPhyllotaxis-200910298-205041.539.png" alt="Screenalicious - DPhyllotaxis - 200910298 205041.539.png" border="0" width="475" height="414" /></div>
<p> Ultimately, the whole point of <a href="http://www.friday.com/bbum/2009/10/19/spiroscales-source-for-snow-leopard-available/">resurrecting my old screensaver code</a> was to finally port DPhyllotaxis to Snow Leopard.</p>
<p>Beyond being, perhaps, the most over-engineered screen saver ever for what ultimately draws colored dots, I wrote this as a sort of virtual flower for my then-girlfriend, now-wife-of-more-than-a-decade, Christine.</p>
<p>The underlying algorithm on this one is based entirely on <a href="http://en.wikipedia.org/wiki/Phyllotaxis">phyllotaxis and the phyllotactic pattern of growth</a> seen across so much of the plant world.  The most well known example being the layout of seeds in a sunflower and that particular form of phyllotaxis is exactly what this screensaver mimics.</p>
<p>The color calculation in this particular screen saver is, frankly, goofy.  Every floret &#8212; every dot &#8212; is actually rendered. The brightness is determined by calculating a color once, grabbing the red component and then calculating the color again using a slightly different algorithm and using the previous red value as the new brightness.  Rather silly, but the results are pleasant enough.<br />
<br clear="left"/></p>
<div class="imgRight"><img src="http://www.friday.com/bbum/wp-content/uploads/2009/10/Screenalicious-DPhyllotaxis-200910298-205114.991.png" alt="Screenalicious - DPhyllotaxis - 200910298 205114.991.png" border="0" width="475" height="414" /></div>
<p>When I originally wrote this in 1994-ish, it used Display PostScript to do all the drawing.   Specifically:</p>
<pre>/* this should not be done here */
PSarc(cp.x, cp.y, 15. + (11. * pp.r), 0, 360);
PSgsave();
PSfill();
PSgrestore();
NXSetColor(NX_COLORBLACK);
PSstroke();
</pre>
<p>I have no idea why, 15 years ago, I thought it important to note that &#8220;this should not be done here&#8221;. None. So, in the ported code, the comment is gone.</p>
<pre>CGFloat floretDiameter = 10. + (11. * pp.r);
CGFloat floretRadius = floretDiameter / 2.;
NSRect floretRect =
    NSMakeRect(cp.x - floretRadius,
    cp.y - floretRadius,
    floretDiameter, floretDiameter);
NSBezierPath *floretPath = [NSBezierPath
    bezierPathWithOvalInRect: floretRect];

[floretPath fill];

[[NSColor blackColor] set];
[floretPath stroke];
</pre>
<p>There are, of course, many ways to make the above a ton faster.  Save for reducing power usage by going a more efficient route, it just doesn&#8217;t matter for this particular use case as I already had to slow down the animation rate considerably.</p>
<p>Seems there has been a bit of performance jump between the 25MHZ 68040 this was originally written on and the 2GHZ Core 2 Duo machine I used for the porting work.</p>
<p>Code is in the same repository as the other <a href="http://svn.red-bean.com/bbum/trunk/ScreenSavers/">screen savers</a>.  I also tossed a <a href="http://www.friday.com/bbum/wp-content/uploads/2009/10/DPhyllotaxis.saver.zip" title="DPhyllotaxis.saver.zip">pre-built binary on the server</a>.  Only tested on 64-bit Snow Leopard, but it <s>might</s> should also work on 10.5 ppc/i386.<br />
<br clear="right"/></p>
]]></content:encoded>
			<wfw:commentRss>http://www.friday.com/bbum/2009/10/25/dphyllotaxis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>+initialize Can Be Executed Multiple Times (+load not so much)</title>
		<link>http://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not-so-much/</link>
		<comments>http://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not-so-much/#comments</comments>
		<pubDate>Sun, 06 Sep 2009 17:47:07 +0000</pubDate>
		<dc:creator>bbum</dc:creator>
				<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://www.friday.com/bbum/?p=1523</guid>
		<description><![CDATA[Some confusion on StackOverflow led to a massive string of comments.   This is a question that comes up often, so here is some google fodder.
In Objective-C, a class can implement +initialize.  This method will be invoked the first time the class is touched, prior to any other methods (other than +load).
The documentation [...]]]></description>
			<content:encoded><![CDATA[<p>Some <a href="http://stackoverflow.com/questions/1385410/objective-c-why-do-i-have-to-call-both-alloc-and-init-everytime">confusion on StackOverflow</a> led to a massive string of comments.   This is a question that comes up often, so here is some google fodder.</p>
<p>In Objective-C, a class can implement <code>+initialize</code>.  This method will be invoked the first time the class is touched, prior to any other methods (other than <code>+load</code>).</p>
<p>The documentation says:</p>
<blockquote><p>The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. </p></blockquote>
<p>Which is exactly true.  But your <code>+initialize</code> methods can still be executed more than once!</p>
<p>Specifically, if a subclass does not implement <code>+initialize</code> but its superclass does, then that superclass&#8217;s <code>+initialize</code> will be invoked once per non-implementing subclass <em>and</em> once for itself.</p>
<p>An example (Foundation Tool, Garbage Collected):</p>
<pre>@interface Abstract: NSObject
@end
@implementation Abstract
+ (void) initialize
{
    NSLog(@"Initializing %@", self);
}

+ (void) load
{
    NSLog(@"Loading");
}
@end

@interface Sub : Abstract
@end
@implementation Sub
@end

int main (int argc, const char * argv[]) {
    [Sub class];
    return 0;
}
</pre>
<p>This will output:</p>
<pre>ArgyBargy[3720:903] Loading
ArgyBargy[3720:903] Initializing Abstract
ArgyBargy[3720:903] Initializing Sub
</pre>
<p>Which is why most <code>+initialize</code> methods are implemented as:</p>
<pre>@implementation MyClass
+ (void) initialize
{
    if (self == [MyClass class]) {
        // ... do +init stuff here ...
    }
}
...
@end
</pre>
<p>Now, categories can seriously screw things up (as usual).  Namely, if you implement <code>+initialize</code> in a category, it will override the classes <code>+initialize</code>.   However, a category provided <code>+load</code> will <em>not</em>;  both the category&#8217;s and the class&#8217;s <code>+load</code> methods will be invoked.</p>
<p>If you were to add the following category to the Sub/Abstract/NSObject example above:</p>
<pre>@interface Abstract(Cat)
@end
@implementation Abstract(Cat)
+ (void) load
{
    NSLog(@"Category +load");
}
+ (void) initialize
{
    NSLog(@"Category +initialize %@", self);
}
@end
</pre>
<p>The program will spew:</p>
<pre>ArgyBargy[3919:903] Loading
ArgyBargy[3919:903] Category +load
ArgyBargy[3919:903] Category +initialize Abstract
ArgyBargy[3919:903] Category +initialize Sub
</pre>
<p>Keep in mind, as well, that the runtime sends <code>+initialize</code> &#8220;in a thread-safe manner&#8221;.  That implies that there is a lock involved somewhere within which then also implies that you better not block on a lock in your <code>+initialize</code> because whoever is supposed to unlock the lock might end up blocking on <code>+initialize</code>s lock.</p>
<p>Or, to put it more bluntly, <strong><em>do not do any heavy lifting in <code>+initialize</code></em></strong>.   Keep it super simple &#038; fast.</p>
<p>For me, <code>+initialize</code> is to be used only as a method of last resort.  Well, 2nd to last.  Last resort is a constructor attributed function (or <code>+load</code>).<span id="more-1523"></span>In the comments, James says:</p>
<blockquote><p>+initialize is a great place to do heavy lifting. &#8230; Your objection about not performing any locks in +initialize is non-sensical. The runtime won&#8217;t allow any other other threads to send a message to the class until the +initialize message returns.</p></blockquote>
<p>That claim is wrong.</p>
<p>While it is a great place to, say, initialize very simple global state&#8211;  string constants, the date, etc&#8230; &#8212; <strong>+initialize</strong> is a horrible place to do any kind of heavy lifting for several reasons.</p>
<p>Most critically, it is impossible to know what order the classes will be <code>+initialize</code>&#8216;d and said order <em>will change</em> across system configurations and, even, software updates.  This leads to a need to do some kind of exclusion locking or something such that the initialization code paths are only followed once.  But, more often than not, &#8220;heavy lifting&#8221; in the <code>+initialize</code> will trigger other classes to be initialized.</p>
<p>End result?  A mess of interleaved locks whose complexity quickly grows out of control.</p>
<p>Here is a dead simple example of a <code>+initialize</code> deadlock:</p>
<pre>#import &lt;Foundation/Foundation.h>

@interface Bleep : NSObject
@end
@interface Blorp : NSObject
@end

static NSLock *initializationLock;

@implementation Bleep
+ (void) initialize
{
    NSLog(@"%s", class_getName(self));
    [initializationLock lock];
    NSLog(@"%@", [Blorp new]);
    [initializationLock unlock];
}
@end

@implementation Blorp
+ (void) initialize
{
    NSLog(@"%s", class_getName(self));
    [initializationLock lock];
    NSLog(@"%@", [Bleep new]);
    [initializationLock unlock];
}
@end

int main (int argc, const char * argv[]) {
    initializationLock = [NSLock new];
    [Blorp new];
    return 0;
}
</pre>
<p>Conveniently, the runtime detects the deadlock for us:</p>
<pre>
209 BleepBlorb[33953:903] Blorp
213 BleepBlorb[33953:903] Bleep
214 BleepBlorb[33953:903] *** -[NSLock lock]: deadlock (&lt;NSLock: 0x20000f340&gt; '(null)')
214 BleepBlorb[33953:903] *** Break on _NSLockError() to debug.
</pre>
<p>And the backtrace at the point of deadlock is interesting beyond the obvious failure:</p>
<pre>#0  semaphore_wait_signal_trap ()
#1  pthread_mutex_lock ()
#2  -[NSLock lock] ()
#3  +[Bleep initialize] (self=0x100001120, _cmd=0x7fff8790a148) at /tmp/BleepBlorb/BleepBlorb.m:15
#4  _class_initialize ()
#5  prepareForMethodLookup ()
#6  lookUpMethod ()
#7  objc_msgSend ()
#8  +[Blorp initialize] (self=0x1000010d0, _cmd=0x7fff8790a148) at /tmp/BleepBlorb/BleepBlorb.m:26
#9  _class_initialize ()
#10 prepareForMethodLookup ()
#11 lookUpMethod ()
#12 objc_msgSend ()
#13 main (argc=1, argv=0x7fff5fbff7e0) at /tmp/BleepBlorb/BleepBlorb.m:37
</pre>
<p>In particular, it shows that the runtime, in and of itself, can trigger class initialization as a part of method lookup, thus implying even less control over initialization order than one might assume.</p>
<p>Now, of course, this is a contrived example.  However, this particular pattern of dysfunctionality is quite easy to grow into as the complexity of initialization increases.   Worse, it can be equally as easy to end up in a situation where the deadlock only occurs some of the time;  only on some app launches on some subset of customers machines.</p>
<p>This isn&#8217;t just conjecture. I have intermittently spent quite a few hours at a time debugging this exact kind of deadlock across various applications (that shall remain nameless&#8211; popular apps, they were).</p>
<p>For the record, <code>+load</code> is an even worse time to do heavy lifting.  The runtime environment is in an extremely non-deterministic state at that time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not-so-much/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Basic Blocks</title>
		<link>http://www.friday.com/bbum/2009/08/29/basic-blocks/</link>
		<comments>http://www.friday.com/bbum/2009/08/29/basic-blocks/#comments</comments>
		<pubDate>Sat, 29 Aug 2009 06:38:02 +0000</pubDate>
		<dc:creator>bbum</dc:creator>
				<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.friday.com/bbum/?p=1501</guid>
		<description><![CDATA[Now that Snow Leopard has shipped, the Blocks Programming Topics is available from developer.apple.com.  Go have a read;  it is a great primer for Blocks.
This post is focused solely on the core syntax of Blocks; declaring a block and calling a block.
Blocks are closures for C.
That is, a block is an anonymous inline [...]]]></description>
			<content:encoded><![CDATA[<p>Now that Snow Leopard has shipped, the <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html">Blocks Programming Topics</a> is available from developer.apple.com.  Go have a read;  it is a great primer for Blocks.</p>
<p>This post is focused solely on the core syntax of Blocks; declaring a block and calling a block.</p>
<p><strong><em>Blocks are <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">closures</a> for C.</em></strong></p>
<p>That is, a block is an anonymous inline collection of code that (Note: <em>lexical scope</em> means <em>function or method or {}-surrounded collection of statements</em>:</p>
<ul>
<li>has a typed argument list just like a function</li>
<li>has an inferred or declared return type</li>
<li>can capture state from the lexical scope within which it is defined</li>
<li>can optionally modify the state of the lexical scope</li>
<li>can share the potential for modification with other blocks defined within the same lexical scope</li>
<li>can continue to share and modify state defined within the lexical scope [the stack frame] <em>after the lexical scope [the stack frame] has been destroyed</em></li>
</ul>
<p>Blocks is available in GCC and Clang as shipped with the <a href="http://www.apple.com/macosx/">Snow Leopard</a> <a href="http://www.apple.com/macosx/developers/">Xcode developer tools</a>.  The Blocks runtime is open source and can be found within <a href="http://llvm.org/svn/llvm-project/compiler-rt/trunk/">LLVM&#8217;s compiler-rt subproject repository</a>.  Blocks have also been presented to the C standards working group as <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1370.pdf">N1370: Apple&#8217;s Extensions to C</a> (which also includes Garbage Collection).</p>
<p>As Objective-C and C++ are both derived from C, Blocks are designed to work fine with all three languages.  Thus, the syntax reflects this goal.</p>
<p>A block is introduced using the <code>^</code> &#8212; the caret &#8212; character.   The <code>^</code> was chosen as it had no unary form (and C++ couldn&#8217;t operator overload it).</p>
<p>For the purposes of an excruciatingly simple example, how about a block that multiplies two numbers?</p>
<p><span id="more-1501"></span>Declaring a variable that could refer to such a Block would be done with something akin to a function pointer:</p>
<pre>    int (^multiplyIt1)(int, int);
</pre>
<p>Of course, if one were to have a slew of different blocks that could multiply two ints in a slew of novel and innovative ways, the type of the Block could be captured in a typedef:</p>
<pre>
    typedef int (^MultiplyItBlockType)(int, int);
    ....
    MultiplyItBlockType multiplyIt2;
</pre>
<p>Capturing a bit of code &#8212; a unit of work &#8212; in a block and assigning it to one of the above variables is as follows:</p>
<pre>    multiplyIt1 = ^(int x, int y) { return x * y; };
</pre>
<p>Since a block typed variable is simply a reference to a chunk of code &#8212; a unit of work &#8212; then simple assignments work, too:</p>
<pre>    multiplyIt2 = multiplyIt1;
</pre>
<p>To execute a Block, it is called just like a function:</p>
<pre>
    int result = multiplyIt1(7,6);
    printf("multiplyIt1(7,6) = %d\n", result);
</pre>
<p>Which spits out <code>multiplyIt1(7,6) = 42</code>.</p>
<p>Just like function pointer syntax, it is possible to declare types that are rather more complex.  Blocks that take blocks as arguments or return blocks?  Sure.  Works fine.   Functions that return arrays of blocks that return arrays of function pointers?  Yup.  Compiler will correctly eat that too.</p>
<p>Whatever C perversion you can imagine, Blocks should play nicely.  There are some rough edges with certain C++ perversions, though.</p>
<p>Embracing typedefs can reduce the insanity factor.</p>
<hr />
<p>Objective-C is a simple set of extensions to C.  Whatever C provides, Objective-C does to.  And this includes blocks.</p>
<p>Defining a method that takes a block as an argument works just like declaring a method that takes a function pointer as an argument:</p>
<pre>
- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block;
</pre>
<p>The above is one of the many new bits of API in Snow Leopard that use Blocks.</p>
<p>A style tip;  when declaring a function or method that takes a Block as an argument, always try to limit it to just one Block argument and always make said Block argument the last argument.   It makes the code easier to read and write at the call site:</p>
<pre>
    NSArray *frameworks = [NSBundle allFrameworks];
    [frameworks enumerateObjectsUsingBlock:^(id aFramework, NSUInteger i, BOOL *stop) {
        NSLog(@"Framework path: %@", [aFramework bundlePath]);
    }];
</pre>
<p>Just like all other C types, Blocks can be used as instance variables and/or properties.</p>
<p>And there you have Basic Blocks.  Next up?  The innards of Blocks&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.friday.com/bbum/2009/08/29/basic-blocks/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Booting a MacBook Pro from an SDHC Card</title>
		<link>http://www.friday.com/bbum/2009/08/07/booting-a-macbook-pro-from-an-sdhc-card/</link>
		<comments>http://www.friday.com/bbum/2009/08/07/booting-a-macbook-pro-from-an-sdhc-card/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 06:23:53 +0000</pubDate>
		<dc:creator>bbum</dc:creator>
				<category><![CDATA[Hacks]]></category>
		<category><![CDATA[Mac OS X]]></category>

		<guid isPermaLink="false">http://www.friday.com/bbum/?p=1452</guid>
		<description><![CDATA[


I recently picked up an ExpressCard/34 SD reader along with a Transcend 16GB SDHC card.   The reader was to ease the transfer of photos from a digital camera and the high-cap SDHC card ensures I can take plenty of photos without shuffling about cards.
With the recent announcement of SD-slot-ness MacBook Pros (drool) that [...]]]></description>
			<content:encoded><![CDATA[<div class="imgLeft"><iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;nou=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=billbumgarner-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=B000ZH7J9S" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe><br />
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=000000&#038;IS2=1&#038;nou=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=billbumgarner-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;md=10FE9736YVPPT7A0FBG2&#038;asins=B001ECQVTM" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<p>I recently picked up an ExpressCard/34 SD reader along with a Transcend 16GB SDHC card.   The reader was to ease the transfer of photos from a digital camera and the high-cap SDHC card ensures I can take plenty of photos without shuffling about cards.</p>
<p>With the recent announcement of <a href="http://www.apple.com/macbookpro/">SD-slot-ness MacBook Pros</a> (drool) that can boot from the SD slot, it made me wonder if a previous generation MacBook Pro could do so, too.</p>
<p>And it can!  Which isn&#8217;t totally surprising.  SD ExpressCard readers effectively act like USB drives and most (all?? I don&#8217;t know) Intel macs can boot from USB devices.</p>
<p>On the click through is instructions for formatting an SD car correctly and slapping down a bootable image.</p>
<p>Given the relatively low prices of SD cards, I&#8217;m making a habit of carrying around a &#8220;rescue card&#8221;.  Tiny enough to not be noticeable, can be reformatted to use as photo-space trivially, one hell of a lot of tougher than optical media, and will prove to be indispensable if I ever need it.<br />
<br clear="left"/><br />
<span id="more-1452"></span><br />
Out of the box, an SD card will be formatted with an MS-DOS (FAT) filesystem.</p>
<p>Useless (except for in digital cameras).</p>
<p>But it isn&#8217;t enough to just reformat it to be an HFS+ Journaled filesystem.  You also need to change the partitioning table.</p>
<p>To do so:</p>
<ul>
<li>Launch Disk Utility</li>
<li>Insert the SD card</li>
<li>Select the volume (labeled <strong>16.06 GB Generic STORAGE DEVICE Media</strong> in my case)</li>
<li>Select the <em>Partition</em> tab</li>
<li>Select <em>1 Partition</em> from the Volume Scheme.  Even if there is only one partition, selecting <em>1 Partition</em> will enable the all critical <em>Options&#8230;</em> button at the bottom</li>
<li>Click <em>Options&#8230;</em> and select <em>GUID Partition Table</em>.</li>
<li>Make sure the partition will be formatted as <em>Mac OS Extended (Journaled)</em></li>
<li>Click <strong>Apply</strong></li>
</ul>
<p>You now have an SDHC card ready to be made bootable.  From here, you could install Mac OS X to the card, install something like a DiskWarrior bootable image to the card, copy an already bootable partition to the card or blast down a bootable DMG to the card.</p>
<p>Disk Utility makes it trivial to clone whole volumes from one partition to another.  If you do so, make sure and check <em>erase destination</em> as that will ensure that Disk Utility uses a block based copy and, thus, is about a zillion and twenty times faster.</p>
<p>If you have a bootable disk image around, you can easily use Disk Utility to restore the image to the partition or you can use the command line:</p>
<pre>sudo asr -source /path/to/bootable.dmg -target /Volumes/SDCard -erase -noverify -noprompt
</pre>
<p>Then, reboot your mac and hold down the option key.  The newly created boot partition should show up.</p>
<p>It is fast enough to boot for installation, recovery, or intermittent use.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.friday.com/bbum/2009/08/07/booting-a-macbook-pro-from-an-sdhc-card/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
