ios获取主程序main函数入口地址

76 阅读1分钟
#import <mach-o/dyld.h>

__attribute__((constructor))
static void initialize(void) {
    for (uint32_t i = 0; i < _dyld_image_count(); i++) {
        const struct mach_header_64 *header = (const struct mach_header_64 *)_dyld_get_image_header(i);
        if (header->filetype == MH_EXECUTE) {
            const uint8_t *p = (const uint8_t *)(header + 1);
            for (uint32_t j = 0; j < header->ncmds; j++) {
                const struct load_command *cmd = (const struct load_command *)p;
                if (cmd->cmd == LC_MAIN) {
                    const struct entry_point_command *entry = (const struct entry_point_command *)cmd;
                    uint64_t entry_point_offset = entry->entryoff;
                    uint64_t entry_point_address = entry_point_offset + (uint64_t)header;
                    NSLog(@"entry_point_address: 0x%llx", entry_point_address);
                    return;
                }
                p += cmd->cmdsize;
            }
        }
    }
}