Getting a mach-o plug-in bundle's path from within a dylib

598 views Asked by At

I'm trying to get the executable path of a plug-in bundle which is loaded by another process, when running a dylib module.

When running a non-plug-in bundle e.g. a regular application, it's easy enough to call [[NSBundle mainBundle] executablePath]. However, with a plug-in bundle this returns the path for the hosting app, not of the plug-in bundle.

In that case, the following tricky code can be used to get the executable's path:

#include <dlfcn.h>

const char* getExecutableFile()
{
    Dl_info exeInfo;
    dladdr((void*) getExecutableFile, &exeInfo);
    return exeInfo.dli_fname;
}

This returns the correct bundle executable's path, except when calling this function from within a function exported by a dylib, which returns the dylib's path.

Is there any way to get the bundle executable's path consistently even from within a call to a function in a different module?

1

There are 1 answers

5
Technologeeks On

You can do that if you use the dyld APIs directly. In fact, it's pretty easy. The following code dumps all the images, with their offsets (and ASLR value).

#include <mach-o/dyld.h>

// List all mach-o images in a process
uint32_t i;
uint32_t ic = _dyld_image_count();
printf ("Got %d images\n",ic); for (i = 0; i < ic; i++)
{
    printf ("%d: %p\t%s\t(slide: %p)\n", i, 
            _dyld_get_image_header(i),
           _dyld_get_image_name(i), 
            _dyld_get_image_slide(i));

}

So naturally, you can strstr() your bundle name in the char * returned by dyld_get_image_name(), and you'll get the full path of it.

Reference: "Mac OS X and iOS Internals" (Wiley, 2012), pg 123.