美文网首页
iOS/MacOS lazy bind

iOS/MacOS lazy bind

作者: dcharles | 来源:发表于2017-05-09 13:41 被阅读152次

iOS由MacOS系统修改而来,所以很多机制是相同的,与Android-Linux相比相似性更高。iOS符号分为自动non-lazy和lazy绑定符号,non-lazy符号位于Mach-O文件__DATA Segment 的__nl_symbol_ptr section,lazy符号位于__DATA Segment 的__la_symbol_ptr section。对于non-lazy的符号绑定时机为动态库加载(load),lazy符号的绑定时机则与Linux相同即函数第一次被调用。

测试代码

#include <stdio.h>

int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n");
    printf("Hello World Again!\n");
    return 0;
}

lldb 调试

反汇编main函数

+34为调用第一个printf函数,+51第二次调用printf函数。
二进制文件DATA段有两个section

DATA Segment

不用展开也应该能猜到是哪两个sction,section[0]为__nl_symbol_ptr section[1]为__la_symbol_ptr 。回到汇编代码,printf函数的地址无论第一次还是第二次都是0x100000f66,这个地址来自哪呢?

add.PNG

由上图可知,0x100000f66值为__TEXT Segment中的__stub section。
该section的作用解释如下

  • section (__TEXT,__stubs) - section contains stubs with prefix imp___stubs__. That stubs are used in the code of __text section to compile procedures with external dependencies, such as system NSLog. dyld (dynamic linker) will replace such stubs on runtime with actual place in dynamic library.
    大意就是该section保存的是编译过程中的外部依赖,在运行时动态链接器dyld将其替换为实际位置 PS:灵魂翻译

call下断,si进去



程序jmpq 0x0000000100000f7c,在__la_symbol_ptr section address中符号的地址为0x0000000100001010

ladd.PNG 值相等

继续调试

Screen Shot 2017-05-09 at 1.22.04 PM.png
0x0000000100000f7c仅将0x0压栈后就jmp回0x100000f6c,printf函数的地址查询最终是通过dyld_stub_binder函数实现。dyld_stub_binder中符号查找原理可以参考fishhook
调用dyld_stub_binder前堆栈信息

第二次调用printf

Screen Shot 2017-05-09 at 1.37.54 PM.png

绑定结束,从此可以直接调用相应函数

返汇编

参考:

相关文章

网友评论

      本文标题:iOS/MacOS lazy bind

      本文链接:https://www.haomeiwen.com/subject/nhpbtxtx.html