Skip to content

Instantly share code, notes, and snippets.

@randombrein
Created April 5, 2015 20:14
Show Gist options
  • Save randombrein/55bf820d916dbcd8dd08 to your computer and use it in GitHub Desktop.
Save randombrein/55bf820d916dbcd8dd08 to your computer and use it in GitHub Desktop.
/*
We have to jump through some serious hoops to get the bundle of the caller;
[self class] doesn't work reliably when our classes are generated at the runtime.
Instead, we fetch the return address, look up the container image,
and attempt to match it against a loaded bundle.
*/
NSBundle *bundle = nil;
void *p = __builtin_return_address(0);
if (p != NULL) {
/* Fetch symbol/image info for our caller */
Dl_info di;
if(dladdr(p, &di) == 0) {
NSLog(@"Could not find image information for the caller's address (%p): %s",
p, dlerror());
}
if(di.dli_sname == NULL) {
NSLog(@"Could not find image path for the caller's address (%p)", p);
abort();
}
/* Try to find a matching bundle */
NSString *execPath = [NSString stringWithCString: di.dli_fname encoding:NSUTF8StringEncoding];
NSArray *allBundles = [[NSBundle allFrameworks] arrayByAddingObjectsFromArray:[NSBundle allBundles]];
for(NSBundle *b in allBundles) {
if(![b.executablePath isEqualToString:execPath]) {
continue;
}
bundle = b;
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment