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.

Revisions

  1. randombrein created this gist Apr 5, 2015.
    35 changes: 35 additions & 0 deletions bundleOfCaller.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    /*
    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;
    }
    }