Getting a useful stack trace from NSException#callStackReturnAddresses

Its always been a little painful when you get an exception and the debugger decides not to cooperate, leaving you with something like:

Stack Trace

Thanks!

As far as I could work out, traditional methods of grabbing a symbolic stack trace don’t work on the iPhone. (If I am remembering right, I don’t think NSStackTraceKey exists in UIKit.)

A little while ago I hacked the GTMStackTrace from google-toolbox-for-mac, to lookup the symbolic stack trace from the call stack return addresses (NSException#callStackReturnAddresses introduced in 10.5) and print it out using NSSetUncaughtExceptionHandler. Life has been a little bit easier ever since. Thankfully, the awesome people who work on GTM added it in themselves (see GTMStackTrace.h#61). Here is how you might set it up, in main.m:

For me, DEBUG is set in GCC_PREPROCESSOR_DEFINITIONS via the awesome GTM xcconfg files, which you should also be using. Hopefully, you should get a trace that looks like:

And the source of the exception usually starts around the 5th line.

6 Responses to “Getting a useful stack trace from NSException#callStackReturnAddresses”

  1. Alex Says:

    Hi,

    This would be great! How can I get GTM set up in my iPhone app (with as small a footprint as possible please).

    Thanks

  2. Ben’s Dev Blog » Blog Archive » Stack Traces for iPhone development Says:

    [...] Hanford posted a great example of using the Google Toolbox for Mac to print human readable stack [...]

  3. cosmix Says:

    Actually, atos works for the iPhone, at least when you have a debug binary of your app.

    For those times when the debugger doesn’t play nice, you can use the cryptic stack trace: take the lower addresses (usually, as in the example above, those that are five or six digits long) that actually correspond to your symbols (as opposed to the system functions that are using much higher addresses), convert to hex and run atos with ‘-arch armv6′ on the debug executable (found in build/Debug-iphoneos).

  4. gabe Says:

    Oh right on. Yeah I guess I was referring to how you can’t use NSTask in an iphone project, and the advantage of running with the GTMStackTrace stuff is that you can have it automatically dump the trace instead of having to manually run atos after the fact.

  5. AZ Says:

    Works great. Really.

  6. August Atlanta iPhone User Group Meeting Follow-up | Atlanta iPhone & iTouch Developers Says:

    [...] I had more information about this stack trace!” – come back here and follow the link to:  GTM stacktrace information.  Its a guide to using Google Toolbox for Mac.  This is the same toolbox that provides a simpler [...]