OGeek|极客世界-中国程序员成长平台

标题: ios - 检测代码是否在 Framework vs. App vs. Bundle [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:00
标题: ios - 检测代码是否在 Framework vs. App vs. Bundle

有没有办法检测正在编译的代码是在框架、 bundle 还是动态库中?

原因是因为崩溃报告库需要在获取结构变量的地址之前知道它是否存在..

IE:

#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 总是为每一种可执行文件、 bundle 、框架定义..

所以我需要一种方法来确定要获取哪个结构变量的地址。有什么想法吗?



Best Answer-推荐答案


看起来您真的只是想获得一个指向适当的 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

关于ios - 检测代码是否在 Framework vs. App vs. Bundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54222359/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4