iOS防护----获取Mach-O代码段位置以及大小

代码不复杂,原理是动态解析自身内存里面的macho文件,根据macho文件格式找到代码段LC_SEGMENT_64(_TEXT)然后就能得到__text的开始位置以及大小:

#include 

struct segmentRange
{
    unsigned long long start;
    unsigned long long end;
};

void getTextSegmentAddr(struct segmentRange *txtSegRange)
{
    if (txtSegRange==NULL)
        return;

    txtSegRange->start=0;

    const struct mach_header_64 *mach_hdr = (struct mach_header_64 *)_dyld_get_image_header(0);
    
    const struct load_command *cmds = (const struct load_command *)(mach_hdr + 1);
    uint32_t cmdsleft;
    const struct load_command *lc;

    for(lc = cmds, cmdsleft = mach_hdr->ncmds; cmdsleft-- && (0 == txtSegRange->start);) {
        if(lc->cmd == LC_SEGMENT_64) {
            
            const struct segment_command_64 *sc = (struct segment_command_64 *) lc;
            const struct section_64 *sect = (struct section_64 *) ((uint8_t*)sc + sizeof(struct segment_command_64));
            
            for(uint32_t sect_idx = 0; sect_idx < sc->nsects; sect_idx++) {
                if(!strcmp("__TEXT", sect->segname) && !strcmp("__text", sect->sectname)) {
                    unsigned long long memAddr = (sc->vmaddr + _dyld_get_image_vmaddr_slide(0) + sect->offset - sc->fileoff);
                    
                    txtSegRange->start = memAddr;
                    txtSegRange->end = memAddr + sect->size;
                    
                    printf("Found __text Section of %s, addr 0x%llu, size %llu, offset 0x%u, start address 0x%llu, end address 0x%llu \n", _dyld_get_image_name(0), sect->addr, sect->size, sect->offset, memAddr, memAddr + sect->size);
                    
                    break;
                 }
                 sect++;
            }
        }
        lc = (void *) ((char *) lc + lc->cmdsize);
    }
}

你可能感兴趣的:(iOS应用程序安全)