Last active
September 12, 2019 01:22
-
-
Save kbinani/5591832 to your computer and use it in GitHub Desktop.
GetModuleFileName (WinAPI) equivalent implementation for OSX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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