Skip to content

Instantly share code, notes, and snippets.

@baarde
Created February 26, 2018 17:17
Show Gist options
  • Save baarde/fc7b4d53723a946971ee6c2b981b6b4e to your computer and use it in GitHub Desktop.
Save baarde/fc7b4d53723a946971ee6c2b981b6b4e to your computer and use it in GitHub Desktop.
NSBundle (XYZCurrent)
#import <Foundation/Foundation.h>
#import <execinfo.h>
#import <dlfcn.h>
static NSBundle *XYZBundleForAddressPointer(const void *pointer);
static NSBundle *XYZBundleForExecutablePath(NSString *execPath);
static NSString *XYZBundlePathFromExecutablePath(NSString *execPath);
static NSString *XYZFrameworkPathFromLibraryPath(NSString *libraryPath);
@implementation NSBundle (XYZCurrent)
+ (nonnull NSBundle *)current
{
void *pointers[] = {NULL, NULL};
backtrace(pointers, 2);
const void *pointer = pointers[1];
return XYZBundleForAddressPointer(pointer) ?: [self mainBundle];
}
@end
static NSBundle *XYZBundleForAddressPointer(const void *pointer) {
if (pointer == NULL) {
return nil;
}
Dl_info info;
int ret = dladdr(pointer, &info);
if (ret == 0 || info.dli_fname == NULL) {
return nil;
}
NSString *execPath = [NSString stringWithUTF8String:info.dli_fname];
if (execPath == nil) {
return nil;
}
return XYZBundleForExecutablePath(execPath);
}
static NSBundle *XYZBundleForExecutablePath(NSString *execPath) {
NSString *bundlePath =
XYZFrameworkPathFromLibraryPath(execPath) ?:
XYZBundlePathFromExecutablePath(execPath);
if (bundlePath == nil) {
return nil;
}
return [NSBundle bundleWithPath:bundlePath];
}
static NSString *XYZBundlePathFromExecutablePath(NSString *execPath) {
return nil;
}
static NSString *XYZFrameworkPathFromLibraryPath(NSString *libraryPath) {
return nil;
}
@n-b
Copy link

n-b commented Feb 26, 2018

something like:

let path = executablePath
while (path not empty) {
 if bundle = bundleWithPath(path) {
  if bundle.isLoaded && bundle.executablePath == executablePath {
   return bundle
  } else {
   path = path.byDeletingLastPathComponent
 }
}
fatalError("crap")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment