Linux栈帧
相关寄存器&指令
寄存器
rax(accumulator):return value
rbx(base)
rcx(count):4st argument
rdx(data):3st argument
rsi(source index):2st argument
rdi(destination index):1st argument
rbp(base pointer)
rsp(stack pointer)
r8:5st argument
r9:6st argument
r10-r15
rip(instruction pointer)
rflags
传参顺序
前6个参数使用rdi、rsi、rdx、rcx、r8、r9,第7个及以后参数使用栈
call指令
相当于执行以下指令:
push %rip
jmp
ret指令
相当于执行以下指令:
pop %rip
leave指令
相当于执行以下指令:
mov %rbp,%rsp
pop %rbp
nop指令
no operation,空指令
指令后缀
b(8位)
w(16位)
l(32位)
q(64位)
c代码
int g(int a, int b)
{return a + b;
}int f(int a, int b)
{return g(a, b);
}int main()
{f(1, 2);return 0;
}
编译&反汇编
gcc test.c -o test -g
objdump -dS test
c&汇编代码
00000000004004ed <g>:
int g(int a, int b)
{4004ed: 55 push %rbp4004ee: 48 89 e5 mov %rsp,%rbp4004f1: 89 7d fc mov %edi,-0x4(%rbp)4004f4: 89 75 f8 mov %esi,-0x8(%rbp)return a + b;4004f7: 8b 45 f8 mov -0x8(%rbp),%eax4004fa: 8b 55 fc mov -0x4(%rbp),%edx4004fd: 01 d0 add %edx,%eax
}4004ff: 5d pop %rbp400500: c3 retq0000000000400501 <f>:int f(int a, int b)
{400501: 55 push %rbp400502: 48 89 e5 mov %rsp,%rbp400505: 48 83 ec 08 sub $0x8,%rsp400509: 89 7d fc mov %edi,-0x4(%rbp)40050c: 89 75 f8 mov %esi,-0x8(%rbp)return g(a, b);40050f: 8b 55 f8 mov -0x8(%rbp),%edx400512: 8b 45 fc mov -0x4(%rbp),%eax400515: 89 d6 mov %edx,%esi400517: 89 c7 mov %eax,%edi400519: e8 cf ff ff ff callq 4004ed <g>
}40051e: c9 leaveq40051f: c3 retq0000000000400520 <main>:int main()
{400520: 55 push %rbp400521: 48 89 e5 mov %rsp,%rbpf(1, 2);400524: be 02 00 00 00 mov $0x2,%esi400529: bf 01 00 00 00 mov $0x1,%edi40052e: e8 ce ff ff ff callq 400501 <f>return 0;400533: b8 00 00 00 00 mov $0x0,%eax
}400538: 5d pop %rbp400539: c3 retq40053a: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1)
栈帧变化过程
不同颜色代表不同函数的栈帧,从上到下依次是__libc_start_main、main、f、g的栈帧
下一级函数的rbp指向上一级函数的rbp