如何在 iOS 中查找文本段范围
Posted
技术标签:
【中文标题】如何在 iOS 中查找文本段范围【英文标题】:How to find text segment range in iOS 【发布时间】:2014-10-06 19:35:35 【问题描述】:如何在 ios 中找到文本段(AKA 代码段)范围?意思是,文本段的起始地址和结束地址是什么?
我找到了this interesting post,但它在 android 上对我有效,但在 iOS 上无效。
【问题讨论】:
This answer 适用于 linux 和 windows,但不适用于 iOS。 【参考方案1】:经过一些挖掘和专家帮助(感谢 Moshe Kravchik),我得到了所需的解决方案 - 通过解析 mach 标头并检索加载命令、段和部分来获取文本段范围。
#include <mach-o/dyld.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#import <Foundation/Foundation.h>
#define PRINT_STR "Found __text Section of %s, addr 0x%x, size %u, offset 0x%x, calc address 0x%x"
#define LC_SEGMENT_NATIVE LC_SEGMENT
#define segment_command_native segment_command
#define section_native section
struct libRange
uint32_t start;
uint32_t end;
;
void getTextSegmentAddr(struct libRange *txtSegRange)
if (txtSegRange==NULL)
return;
txtSegRange->start=0;
const struct mach_header *mach_hdr;
mach_hdr = _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_NATIVE)
const struct segment_command_native *sc = (void *) lc;
const struct section_native *sect = (void *) (sc + 1);
for(uint32_t sect_idx = 0; sect_idx < sc->nsects; sect_idx++)
if(!strcmp("__TEXT", sect->segname) && !strcmp("__text", sect->sectname))
uint32_t memAddr = (sc->vmaddr + _dyld_get_image_vmaddr_slide(0) + sect->offset - sc->fileoff);
NSLog(@PRINT_STR,_dyld_get_image_name(0), sect->addr, sect->size, sect->offset, memAddr);
txtSegRange->start = memAddr;
txtSegRange->end = memAddr + sect->size;
break;
sect++;
lc = (void *) ((char *) lc + lc->cmdsize);
int main()
struct libRange txtSegRange;
getTextSegmentAddr(&txtSegRange);
return 0;
【讨论】:
以上是关于如何在 iOS 中查找文本段范围的主要内容,如果未能解决你的问题,请参考以下文章
iOS 在UITextView中查找某个Range所在的Rect
如何查找元素是不是立即围绕文本选择范围,如果是,它是啥元素?