有没有办法检测正在编译的代码是在框架、捆绑包还是动态库中?
原因是因为崩溃报告器库需要在获取结构变量的地址之前知道结构变量是否存在。
即:
#ifdef MH_EXECUTE_SYM
return (uint8_t*)&_mh_execute_header;
#else
return (uint8_t*)&_mh_dylib_header;
#endif
问题是MH_EXECUTE_SYM
、MH_BUNDLE_SYM
、MH_DYLIB_SYM
总是为每种可执行文件、捆绑包、框架定义。
所以我需要一种方法来确定要获取哪个结构变量的地址。有什么想法吗?
看起来您真的只想获取指向相应mach_header_64
(或在 32 位系统上mach_header
)的指针。
如果您有指针,则可以使用 dladdr
函数找出它是从哪个(如果有)mach-o 加载的。该函数填充了一个Dl_info
结构,其中包括指向 mach-o mach_header_64
的指针。
// For TARGET_RT_64_BIT:
#import <TargetConditionals.h>
// For dladdr:
#import <dlfcn.h>
// For mach_header and mach_header_64:
#import <mach-o/loader.h>
#ifdef TARGET_RT_64_BIT
struct mach_header_64 *mach_header_for_address(const void *address) {
Dl_info info;
if (dladdr(address, &info) == 0) {
// address doesn't point into a mach-o.
return 0;
}
struct mach_header_64 *header = (struct mach_header_64 *)info.dli_fbase;
if (header->magic != MH_MAGIC_64) {
// Something went wrong...
return 0;
}
return header;
}
#else
struct mach_header mach_header_for_address(const void *address) {
Dl_info info;
if (dladdr(address, &info) == 0) {
// address doesn't point into a mach-o.
return 0;
}
struct mach_header *header = (struct mach_header *)info.dli_fbase;
if (header->magic != MH_MAGIC) {
// Something went wrong...
return 0;
}
return header;
}
#endif