iOS中线程Call Stack的捕获和解析(二)

原创 2015年11月18日 16:36:55

上接iOS中线程Call Stack的捕获和解析(一)

1. 部分参考资料

做这一块时也是查阅了很多链接和书籍,包括但不限于:

以及很多Google Search。

2. 相关API和数据结构

由于我们在上面回溯线程调用栈拿到的是一组地址,所以这里进行符号化的输入输出应该分别是地址和符号,接口设计类似如下:

- (NSString *)symbolicateAddress:(uintptr_t)addr;

不过在实际操作中,我们需要依赖于dyld相关方法和数据结构:

/*
 * Structure filled in by dladdr().
 */
typedef struct dl_info {
        const char      *dli_fname;     /* Pathname of shared object */
        void            *dli_fbase;     /* Base address of shared object */
        const char      *dli_sname;     /* Name of nearest symbol */
        void            *dli_saddr;     /* Address of nearest symbol */
} Dl_info;

extern int dladdr(const void *, Dl_info *);
DESCRIPTION
     These routines provide additional introspection of dyld beyond that provided by dlopen() and dladdr()

     _dyld_image_count() returns the current number of images mapped in by dyld. Note that using this count
     to iterate all images is not thread safe, because another thread may be adding or removing images dur-ing during
     ing the iteration.

     _dyld_get_image_header() returns a pointer to the mach header of the image indexed by image_index.  If
     image_index is out of range, NULL is returned.

     _dyld_get_image_vmaddr_slide() returns the virtural memory address slide amount of the image indexed by
     image_index. If image_index is out of range zero is returned.

     _dyld_get_image_name() returns the name of the image indexed by image_index. The C-string continues to
     be owned by dyld and should not deleted.  If image_index is out of range NULL is returned.

又为了要判断此次解析是否成功,所以接口设计演变为:

bool jdy_symbolicateAddress(const uintptr_t addr, Dl_info *info)

Dl_info用来填充解析的结果。

3. 算法思路

对一个地址进行符号化解析说起来也是比较直接的,就是找到地址所属的内存镜像,然后定位该镜像中的符号表,最后从符号表中匹配目标地址的符号。

mach_o_segments(图片来源于苹果官方文档)

以下思路是描述一个大致的方向,并没有涵盖具体的细节,比如基于ASLR的偏移量:

        // 基于ASLR的偏移量https://en.wikipedia.org/wiki/Address_space_layout_randomization

        /**

         * When the dynamic linker loads an image, 

         * the image must be mapped into the virtual address space of the process at an unoccupied address.

         * The dynamic linker accomplishes this by adding a value "the virtual memory slide amount" to the base address of the image.

         */

3.1 寻找包含地址的目标镜像

起初看到一个API还有点小惊喜,可惜iPhone上用不了:

extern bool _dyld_image_containing_address(const void* address)
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_3,__MAC_10_5,__IPHONE_NA,__IPHONE_NA);

所以得自己来判断。

怎么判断呢?

A segment defines a range of bytes in a Mach-O file and the addresses and memory protection attributes at which those bytes are mapped into virtual memory when the dynamic linker loads the application. As such, segments are always virtual memory page aligned. A segment contains zero or more sections.

通过遍历每个段,判断目标地址是否落在该段包含的范围内:

/*
 * The segment load command indicates that a part of this file is to be
 * mapped into the task's address space.  The size of this segment in memory,
 * vmsize, maybe equal to or larger than the amount to map from this file,
 * filesize.  The file is mapped starting at fileoff to the beginning of
 * the segment in memory, vmaddr.  The rest of the memory of the segment,
 * if any, is allocated zero fill on demand.  The segment's maximum virtual
 * memory protection and initial virtual memory protection are specified
 * by the maxprot and initprot fields.  If the segment has sections then the
 * section structures directly follow the segment command and their size is
 * reflected in cmdsize.
 */
struct segment_command { /* for 32-bit architectures */
    uint32_t    cmd;        /* LC_SEGMENT */
    uint32_t    cmdsize;    /* includes sizeof section structs */
    char        segname[16];    /* segment name */
    uint32_t    vmaddr;     /* memory address of this segment */
    uint32_t    vmsize;     /* memory size of this segment */
    uint32_t    fileoff;    /* file offset of this segment */
    uint32_t    filesize;   /* amount to map from the file */
    vm_prot_t   maxprot;    /* maximum VM protection */
    vm_prot_t   initprot;   /* initial VM protection */
    uint32_t    nsects;     /* number of sections in segment */
    uint32_t    flags;      /* flags */
};


/**
 * @brief 判断某个segment_command是否包含addr这个地址,基于segment的虚拟地址和段大小来判断
 */
bool jdy_segmentContainsAddress(const struct load_command *cmdPtr, const uintptr_t addr) {
    if (cmdPtr->cmd == LC_SEGMENT) {
        struct segment_command *segPtr = (struct segment_command *)cmdPtr;
        if (addr >= segPtr->vmaddr && addr < (segPtr->vmaddr + segPtr->vmsize)) {
            return true;
        }

这样一来,我们就可以找到包含目标地址的镜像文件了。

3.2 定位目标镜像的符号表

由于符号的收集和符号表的创建贯穿着编译和链接阶段,这里就不展开了,而是只要确定除了代码段_TEXT和数据段DATA外,还有个_LINKEDIT段包含符号表:

The __LINKEDIT segment contains raw data used by the dynamic linker, such as symbol, string, and relocation table entries.

所以现在我们需要先定位到__LINKEDIT段,同样摘自苹果官方文档:

Segments and sections are normally accessed by name. Segments, by convention, are named using all uppercase letters preceded by two underscores (for example, _TEXT); sections should be named using all lowercase letters preceded by two underscores (for example, _text). This naming convention is standard, although not required for the tools to operate correctly.

我们通过遍历每个段,比较段名称是否和__LINKEDIT相同:

usr/include/mach-o/loader.h

#define SEG_LINKEDIT    "__LINKEDIT"

接着来找符号表:

/**

 * 摘自《The Mac Hacker's Handbook》:

 * The LC_SYMTAB load command describes where to find the string and symbol tables within the __LINKEDIT segment. The offsets given are file offsets, so you subtract the file offset of the __LINKEDIT segment to obtain the virtual memory offset of the string and symbol tables. Adding the virtual memory offset to the virtual-memory address where the __LINKEDIT segment is loaded will give you the in-memory location of the string and sym- bol tables.

 */

也就是说,我们需要结合__LINKEDIT segment_command(见上面结构描述)和LC_SYMTAB load_command(见下面结构描述)来定位符号表:

/*
 * The symtab_command contains the offsets and sizes of the link-edit 4.3BSD
 * "stab" style symbol table information as described in the header files
 * <nlist.h> and <stab.h>.
 */
struct symtab_command {
    uint32_t    cmd;        /* LC_SYMTAB */
    uint32_t    cmdsize;    /* sizeof(struct symtab_command) */
    uint32_t    symoff;     /* symbol table offset */
    uint32_t    nsyms;      /* number of symbol table entries */
    uint32_t    stroff;     /* string table offset */
    uint32_t    strsize;    /* string table size in bytes */
};

如上述引用描述,LC_SYMTAB和_LINKEDIT中的偏移量都是文件偏移量,所以要获得内存中符号表和字符串表的地址,我们先将LC_SYMTAB的symoff和stroff分别减去LINKEDIT的fileoff得到虚拟地址偏移量,然后再加上_LINKEDIT的vmoffset得到虚拟地址。当然,要得到最终的实际内存地址,还需要加上基于ASLR的偏移量。

3.3 在符号表中寻找和目标地址最匹配的符号

终于找到符号表了,写到这里有点小累,直接贴下代码:

/**
 * @brief 在指定的符号表中为地址匹配最合适的符号,这里的地址需要减去vmaddr_slide
 */
const JDY_SymbolTableEntry *jdy_findBestMatchSymbolForAddress(uintptr_t addr,
                                                              JDY_SymbolTableEntry *symbolTable,
                                                              uint32_t nsyms) {

    // 1. addr >= symbol.value; 因为addr是某个函数中的一条指令地址,它应该大于等于这个函数的入口地址,也就是对应符号的值;
    // 2. symbol.value is nearest to addr; 离指令地址addr更近的函数入口地址,才是更准确的匹配项;

    const JDY_SymbolTableEntry *nearestSymbol = NULL;
    uintptr_t currentDistance = UINT32_MAX;

    for (uint32_t symIndex = 0; symIndex < nsyms; symIndex++) {
        uintptr_t symbolValue = symbolTable[symIndex].n_value;
        if (symbolValue > 0) {
            uintptr_t symbolDistance = addr - symbolValue;
            if (symbolValue <= addr && symbolDistance <= currentDistance) {
                currentDistance = symbolDistance;
                nearestSymbol = symbolTable + symIndex;
            }
        }
    }

    return nearestSymbol;
}


/*
 * This is the symbol table entry structure for 64-bit architectures.
 */
struct nlist_64 {
    union {
        uint32_t  n_strx; /* index into the string table */
    } n_un;
    uint8_t n_type;        /* type flag, see below */
    uint8_t n_sect;        /* section number or NO_SECT */
    uint16_t n_desc;       /* see <mach-o/stab.h> */
    uint64_t n_value;      /* value of this symbol (or stab offset) */
};

找到匹配的nlist结构后,我们可以通过.n_un.n_strx来定位字符串表中相应的符号名。

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

iOS中线程Call Stack的捕获和解析(一)

这里对上个月做的一个技术项目做部分技术小结,这篇文章描述的功能和我们在使用Xcode进行调试时点击暂停的效果类似。一、获取任意一个线程的Call Stack如果要获取当前线程的调用栈,可以直接使用现有...

iOS崩溃堆栈信息的符号化解析

最近一段时间,在iOS开发调试过程中以及上线之后,程序经常会出现崩溃的问题。简单的崩溃还好说,复杂的崩溃就需要我们通过解析Crash文件来分析了,解析Crash文件在iOS开发中是比较常见的。但在跟开...

来淘宝的这一年:前篇、生活和工作

Jason Lee http://blog.csdn.net/jasonblog http://weibo.com/jasonmblog 我犹豫着要用“这一年”还是“这半年”的字眼。距离...

关于iOS多线程,你看我就够了

在这篇文章中,我将为你整理一下 iOS 开发中几种多线程方案,以及其使用方法和注意事项。当然也会给出几种多线程的案例,在实际使用中感受它们的区别。还有一点需要说明的是,这篇文章将会使用 Swift 和...

iOS查看线程,打印线程的方法

当我们想在断点处查看当前所在线程的时候,可以打印如下方法:  [NSthread callStackSymbols]; ckSymbols

iOS中的图像处理(一)——基础滤镜

最近在稍微做一些整理,翻起这部分的代码,发现是两个多月前的了。 这里讨论的是基于RGBA模型下的图像处理,即将变换作用在每个像素上。 代码是以UIImage的category形式存在的: t...

从NSTimer的失效性谈起(一):关于NSTimer和NSRunLoop

一、NSTimer的失效性在iOS中要设置一个定时器的通常做法是调用如下API:+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)...

iOS中的图像处理(三)——混合运算

有时候,单独对一张图像进行处理是很难或者根本达不到我们想要的效果的。一个好的滤镜效果的诞生,往往要经过很多复杂步骤、细致微调、图片应用效果观察以及很多图层叠加。 我在JSWidget上发现了一些常用...

iOS中的图像处理(二)——卷积运算

关于图像处理中的卷积运算,这里有两份简明扼要的介绍:文一,文二。 其中,可能的一种卷积运算代码如下: - (UIImage*)applyConvolution:(NSArray*)kernel...

通过修改Mach-O中Load Commands进行全局进程劫持

Mach-O格式,是Machobject文件格式的缩写,是一种可执行文件、目标代码、共享程序库、动态加载代码和核心DUMP(摘自度娘),类似于Win环境的PE、Linux环境的ELF。   Load...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)