Print a stack trace anytime

Here’s how to print a stack trace from code at any point in your app – no need to wait for a crash report! -

NSLog(@"%@", [NSThread callStackSymbols]);

That requires iOS 4.0+. There are some easy-to-use C functions that do the same thing:

#import <execinfo.h>
#import <unistd.h>

void PrintStackTrace() {
  void *stackAdresses[32];
  int stackSize = backtrace(stackAdresses, 32);
  backtrace_symbols_fd(stackAdresses, stackSize, STDOUT_FILENO);
}

Just call PrintStackTrace to print a stack trace. Pretty straightforward.

As a quick example, calling from your app’s entry point, like this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
  PrintStackTrace();
  [self.window makeKeyAndVisible];
  return YES;
}

will produce debug output like this:

0   Temp22                              0x000027f7 PrintStackTrace + 18
1   Temp22                              0x00002823 -[Temp22AppDelegate application:didFinishLaunchingWithOptions:] + 18
2   UIKit                               0x338dabc5 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 772
3   UIKit                               0x338d6259 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 272
4   UIKit                               0x338a248b -[UIApplication handleEvent:withNewEvent:] + 1114
5   UIKit                               0x338a1ec9 -[UIApplication sendEvent:] + 44
6   UIKit                               0x338a1907 _UIApplicationHandleEvent + 5090
7   GraphicsServices                    0x35d66f03 PurpleEventCallback + 666
8   CoreFoundation                      0x314656ff __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 26
9   CoreFoundation                      0x314656c3 __CFRunLoopDoSource1 + 166
10  CoreFoundation                      0x31457f7d __CFRunLoopRun + 520
11  CoreFoundation                      0x31457c87 CFRunLoopRunSpecific + 230
12  CoreFoundation                      0x31457b8f CFRunLoopRunInMode + 58
13  UIKit                               0x338d5309 -[UIApplication _run] + 380
14  UIKit                               0x338d2e93 UIApplicationMain + 670
15  Temp22                              0x000027b7 main + 70
16  Temp22                              0x0000276c start + 40

The PrintStackTrace stuff is not Xcode-specific and should theoretically also work in other gcc-based C code, although I only personally tested this in iOS so far.

Hope that’s useful!

2 Trackbacks

  1. [...] This post was mentioned on Twitter by Jean Hsu and Tyler Neylon, Tyler Neylon. Tyler Neylon said: How to print a stack trace from code in iOS: http://bit.ly/eDCXZ0 [...]

  2. [...] As mentioned in the blog, it requires iOS 4.0+, which, from my perspective, is everyone. Bynomial Code » Print a stack trace anytime [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*