Skip to content

Instantly share code, notes, and snippets.

@kbinani
Last active September 12, 2019 01:22
Show Gist options
  • Save kbinani/5591832 to your computer and use it in GitHub Desktop.
Save kbinani/5591832 to your computer and use it in GitHub Desktop.
GetModuleFileName (WinAPI) equivalent implementation for OSX
#include <mach-o/dyld.h>
#include <mach-o/getsect.h>
#include <dlfcn.h>
#include <string>
std::string GetModuleFileName(const void *module)
{
if (!module) { return std::string(); }
uint32_t count = _dyld_image_count();
for (uint32_t i = 0; i < count; ++i) {
const mach_header *header = _dyld_get_image_header(i);
if (!header) { break; }
char *code_ptr = NULL;
if ((header->magic & MH_MAGIC_64) == MH_MAGIC_64) {
uint64_t size;
code_ptr = getsectdatafromheader_64((const mach_header_64 *)header, SEG_TEXT, SECT_TEXT, &size);
} else {
uint32_t size;
code_ptr = getsectdatafromheader(header, SEG_TEXT, SECT_TEXT, &size);
}
if (!code_ptr) { continue; }
const uintptr_t slide = _dyld_get_image_vmaddr_slide(i);
const uintptr_t start = (const uintptr_t)code_ptr + slide;
Dl_info info;
if (dladdr((const void *)start, &info)) {
if (dlopen(info.dli_fname, RTLD_NOW) == module) {
return std::string(info.dli_fname);
}
}
}
return std::string();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment