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?
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).
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.