Skip to content

Instantly share code, notes, and snippets.

@bdash
Created October 20, 2015 19:30
Show Gist options
  • Save bdash/906bddc3d5ece607b4af to your computer and use it in GitHub Desktop.
Save bdash/906bddc3d5ece607b4af to your computer and use it in GitHub Desktop.
Test of backtrace and dladdr with C++ lambdas
// c++ -framework Foundation -std=c++14 -o dladdr-lambda-test dladdr-lambda-test.mm
#import <Foundation/Foundation.h>
#include <cxxabi.h>
#include <dlfcn.h>
#include <execinfo.h>
@interface MyObject : NSObject
@end
@implementation MyObject
+ (void)doStuff
{
[] {
void* callstack[128];
int i, frames = backtrace(callstack, 128);
for (i = 0; i < frames; ++i) {
if ((intptr_t)callstack[i] == 1)
continue;
const char* mangledName;
const char* demangledName;
Dl_info info;
if (dladdr(callstack[i], &info) && info.dli_sname)
mangledName = info.dli_sname;
if (mangledName)
demangledName = abi::__cxa_demangle(mangledName, nullptr, nullptr, nullptr);
if (mangledName || demangledName)
printf("0x%016lx %s + %ld\n", (intptr_t)callstack[i], demangledName ? demangledName : mangledName, (intptr_t)callstack[i] - (intptr_t)info.dli_saddr);
else
printf("?\n");
}
}();
}
@end
int main(int argc, char** argv)
{
[MyObject doStuff];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment