在平时开发和调试中,经常遇到C调用栈和汇编,所以这里来统一的了解下这部分内容,本章需要一定的汇编基础才能更好的理解。
函数签名
在JavaScript中,我们定义函数和调用函数都是相当自由的:
1 | function func(a, b, c) { |
这样做完全没有问题。但是在C语言中,方法调用却是非常严格的,如果参数类型或者个数不对,就会直接编译失败(隐式转换除外)。
1 | int arg1_func(int a) { |
以上C语言将会直接编译不通过,原因之后再说。这里我们把int(*)(int)
称为这个函数的函数签名
。
为什么我们要了解函数签名
呢?由于C方法的参数传递是和函数签名相关的,而且是编译期就需要确定的。他决定了参数是如何传递给具体方法,并且返回参数是如何返回的。
那么接下来就让我们来了解C语言的参数传递方式。由于不同架构平台拥有不同的处理方式,但大同小异,这里我们就用AArch64
架构来做介绍。
Registers
在了解底层之前,我们需要一点ARM的预备知识,这里做一个简单的介绍,具体ARM汇编可以参考官方文档armasm_user_guide和ABI。
ARM_ASM (4.1节)
In AArch64 state, the following registers are available:
- Thirty-one 64-bit general-purpose registers X0-X30, the bottom halves of which are accessible as
W0-W30. - Four stack pointer registers SP_EL0, SP_EL1, SP_EL2, SP_EL3.
- Three exception link registers ELR_EL1, ELR_EL2, ELR_EL3.
- Three saved program status registers SPSR_EL1, SPSR_EL2, SPSR_EL3.
- One program counter.
ABI (9.1节)
For the purposes of function calls, the general-purpose registers are divided into four groups:
Argument registers (X0-X7)
These are used to pass parameters to a function and to return a result. They can be used as scratch registers or as caller-saved register variables that can hold intermediate values within a function, between calls to other functions. The fact that 8 registers are available for passing parameters reduces the need to spill parameters to the stack when compared with AArch32.
Caller-saved temporary registers (X9-X15)
If the caller requires the values in any of these registers to be preserved across a call to another function, the caller must save the affected registers in its own stack frame. They can be modified by the called subroutine without the need to save and restore them before returning to the caller.
Callee-saved registers (X19-X29)
These registers are saved in the callee frame. They can be modified by the called subroutine as long as they are saved and restored before returning.
Registers with a special purpose (X8, X16-X18, X29, X30)
- X8 is the indirect result register. This is used to pass the address location of an indirect result, for example, where a function returns a large structure.
- X16 and X17 are IP0 and IP1, intra-procedure-call temporary registers. These can be used by call veneers and similar code, or as temporary registers for intermediate values between subroutine calls. They are corruptible by a function. Veneers are small pieces of code which are automatically inserted by the linker, for example when the branch target is out of range of the branch instruction.
- X18 is the platform register and is reserved for the use of platform ABIs. This is an additional temporary register on platforms that don’t assign a special meaning to it.
- X29 is the frame pointer register (FP).
- X30 is the link register (LR).
根据官方文档,这里我们需要知道的是X0-X30个通用寄存器,D0-D31个浮点寄存器,堆栈寄存器SP,和独立不可直接操作的PC寄存器。
其中通用寄存器在C语言的ABI定义中,X29作为栈帧FP,X30作为函数返回地址LR,X0-X7作为参数寄存器,X8为Indirect result location
(和返回值相关),X9-X15为临时寄存器。其他的寄存器和目前我们的内容没有太大的关系,所以不做介绍了。这里有个官方的简要图:
在阅读以下内容需要明确上述的几个寄存器,特别是LR=X30
,FP=X29
,其中W0和X0代表同一个寄存器,只是W是32位,X是64位。
需要了解的存取指令是LDR(load),STR(store),其他存取指令都是以这两个为基础。相关运算可见ABI 6.3.4节
,这里介绍下下面会遇到的运算:
Example | Description |
---|---|
LDR X0, [X1, #8] |
Load from address X1 + 8 |
LDR X0, [X1, #8]! |
Pre-index: Update X1 first (to X1 + #8), then load from the new address |
LDR X0, [X1], #8 |
Post-index: Load from the unmodified address in X1 first, then update X1 (to X1 + #8) |
Stack Frame
在C语言调用过程中,SP
和LR
是成对出现的,他们代表了一个函数的栈区域,也称为栈帧
。
一个栈帧的大概结构如下:
这个结构对我们来说非常重要,也是本次我们讨论的重点。
少参数调用
对于一个函数的调用,入参会放入X0-X7中,返回参数会放在X0中返回,那么我们就来分析下一个简单的例子:
1 | int lessArg(int arg1, char *arg2) { |
调用前:
1 | caller: |
1 | cfunction`lessArg: |
由以上结果看的确按照ABI所描述的,在<=8个参数的时候,参数是放在寄存器中传递。
多参数调用
那么如果参数超过8个呢?据ABI描述是通过堆栈的形式来传递,我们来看下结果:
1 | int moreArg(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, char *arg14) { |
1 | caller: |
从上面可以看出来,arg9以上的入参被存在了SP ~ (SP+0x10)
的位置,也就是当前栈的栈底,下一层栈帧的栈顶。
1 | cfunction`moreArg: |
由此可见,大于8个的参数会被放入栈中SP ~ (SP + count - 8)
,和预期的一样。
struct参数及返回
上面说了基本类型的传递情况,在C语言中,还有一类不定长数据类型可以直接传递,那就是struct。那么我们来看看struct参数是怎么传递的。
小struct
1 | struct SmallStruct { |
1 | caller: |
1 | cfunction`smallStructFunc: |
可见,小型struct,可以直接放在寄存器中传递,和普通基本类型的传递没有太大的区别。
大struct
那么struct足够的大呢,导致不能简单的用寄存器容纳struct的数据?
这里就要涉及到X8的一个特殊身份了(XR, indirect result location),这里我们将X8
记作XR
。
1 | struct BigStruct { |
1 | caller: |
1 | cfunction`bigStructFunc: |
这样返回值就放在了*XR
所在的位置,caller只需要再拷贝到临时变量区中即可。
可以看到,在处理大型struct时,就会出现多次内存拷贝,会对性能造成一定影响,所以这类方法尽量不要直接传递大型struct,可以传递指针或者引用,或者采用inline的方案,在优化期去除函数调用。
struct参数的分界线
根据AAPCS 64的Parameter Passing Rules
节所述:
If the argument is a Composite Type and the size in double-words of the argument is not more than 8 minus NGRN, then the argument is copied into consecutive general-purpose registers, starting at x[NGRN]. The argument is passed as though it had been loaded into the registers from a double-word- aligned address with an appropriate sequence of LDR instructions loading consecutive registers from memory (the contents of any unused parts of the registers are unspecified by this standard). The NGRN is incremented by the number of registers used. The argument has now been allocated.
大致说的是如果X0-X8中剩余的寄存器足够去保存该结构,那么就保存到寄存器,否则保存到栈。
If the type, T, of the result of a function is such that
void func(T arg)
would require that arg be passed as a value in a register (or set of registers) according to the rules in §5.4 Parameter Passing, then the result is returned in the same registers as would be used for such an argument.
返回值也遵守以上规则。
这个文档不是最新的,而且是beta版,暂时没有找到正式版本。而且这里还涉及到很多其他的因素,所以这里也就不深究了。
va_list
以上都是确定参数,那么如果是不确定参数,又是怎么传递的呢?
在AAPCS 64
文档里有明确的说明,但是这里我们从汇编的角度来看这个问题。
1 | int mutableAragsFunc(int arg, ...) { |
在函数入口打断点,打印参数寄存器:
1 | x0 = 0x0000000000000001 |
可以发现除了x0是正确的第一个参数,其他都是随机的,那么说明参数肯定被放到了栈上。
1 | cfunction`main: |
也就是表明被明确定义的参数,是按照上面所说的规则传递,而...
参数全部按照栈方式传递。这从实现原理上也比较容易理解,在取va_arg的时候,只需要将栈指针+sizeof(type)就可以了。
错误的函数签名
那么现在,我们回过头来看看第一个问题。C语言为什么会有函数签名?
函数签名决定了参数以及返回值的传递方式,同时还决定了函数栈帧的分布与大小,所以如果不确定函数签名,我们也就无法知道如何去传递参数了。
那么错误的函数签名会导致什么样的后果呢?运行时是否会崩溃?我们来看:
1 | int arg1_func(int a) { |
首先说结果,结果是一切运行正常,只是结果值有部分是错误的。那么我们来看看汇编代码:
1 | cfunction`arg_test_func: |
所以结果应该是1, 2, 2, 3
。
这里的结果不能代表任何在其他环境下的结果,可以说其结果是难以预测的。这里没有奔溃也只是随机参数并不会带来奔溃的风险。
所以我们是不能用其他函数签名来传递参数的。
obj_msgSend
接下来,我们来说说iOS中最著名的函数obj_msgSend
,可以说,这个函数是objc的核心和基础,没有这个方法,就不存在objc。
根据我们上面的分析,理论上我们不能改变obj_msgSend
的函数签名,来传递不同类型和个数的参数。那么苹果又是怎么实现的呢?
以前我们一直说obj_msgSend
用汇编来写是为了速度,但这并不是主要原因,因为retain,release也是非常频繁使用的方法,为什么不把这几个也改为汇编呢。其实更重要的原因是如果用C来写obj_msgSend
根本实现不了!
我们翻开苹果objc的源码,查看其中arm64.s汇编代码:
1 | _objc_msgSend |
看出于上面其他C方法编译出来的汇编的区别了吗?
那就是obj_msgSend
居然不存在栈帧!同时也没有任何地方修改过X0-X7
,X8
,LR
,SP
,FP
!
而且当找到真正对象上的方法的时候,并不像其他方法一样使用BL
,而是使用了
1 | .macro CacheHit |
也就是说并没有修改LR
。这样做的效果就相当于在函数调用的时候插入了一段代码!更像是c语言的宏。
由于obj_msgSend
并没有改变任何方法调用的上下文,所以真正的objc方法就好像是被直接调用的一样。
可以说,这种想法实在是太精彩了。
objc_msgSend对nil对象的处理
大家都知道,向空对象发送消息,返回的内容肯定都是0。那么这是为什么呢?
还是来看obj_msgSend
的源代码部分,第一行就判断了nil:
1 | cmp x0, #0 // nil check and tagged pointer check |
其中tagged pointer技术并不是我们本期的话题,所以我们直接跳到空对象的处理方法上:
1 | LReturnZero: |
他将可能的保存返回值的寄存器全部写入0!(为什么会有多个寄存器,是因为ARM其实是支持向量运算的,所以在某些条件下会用多个寄存器保存返回值,具体可以去参考ARM官方文档)。
这样我们的返回值就只能是0了!
等等,还缺少一个类型,struct!如果是栈上的返回,上文已经分析过是保存在X8
中的,可是我们并没有看到任何有关X8
的操作。那么我们来写一个demo尝试一下:
1 | void struct_objc_nil(Test *t) { |
首先我们打开编译优化-os
(非优化状态,栈空间会被清0)。其结果居然是:
1 | stack: 50462976,185207048,0,0,0,0, |
struct类型两者的返回并不一致!按照我们阅读源码来推论,随机数值才是正确的结果,这是为什么呢?
我们还是来看汇编,我将关键部分特意标注了出来:
1 | cfunction`struct_objc_nil: |
到这里我们就能够明白了,为什么struct返回值也会变成0。是编译器给我们加入了一段判定的代码!
那么’objc空对象的返回值一定是0’这个判定就需要在一定条件下了。
总结
对这一部分的探索一直持续了很久,一直是迷糊状态,不过经过长时间的多次探索,慢慢思考,总算有一个比较清晰的认识了。可以说底层的东西真的很多很复杂,这里只是其中很小的一方面,其他方面等有时间了另外再写吧。