C语言调用函数过程详解
Sunny.man
使用环境:
gcc 版本 4.1.2(Red Hat 4.1.2-42)
示例源代码
int foo(int a,int b)
{
int a1=0x123;
return a1+a+b;
}
int main()
{
foo(2,3);
return 0;
}
运行程序
命令:gdb a.out
Start
Disassemble
汇编函数清单
4.1main函数的汇编
0x0804836c : lea 0x4(%esp),%ecx
0: and $0xfffffff0,%esp
0: pushl 0xfffffffc(%ecx)
0: push %ebp
0: mov %esp,%ebp
0: push %ecx
0x0804837a : sub $0x8,%esp
0x0804837d : movl $0x3,0x4(%esp)
0: movl $0x2,(%esp)
0x0804838c : call 0x8048354
0: mov $0x0,%eax
0: add $0x8,%esp
0: pop %ecx
0x0804839a : pop %ebp
0x0804839b : lea 0xfffffffc(%ecx),%esp
0x0804839e : ret
4.2Foo函数的汇编
0: push %ebp
0: mov %esp,%ebp
0: sub $0x10,%esp
0x0804835a : movl $0x123,0xfffffffc(%ebp)
0: mov 0x8(%ebp),%eax
0: add 0xfffffffc(%ebp),%eax
0: add 0xc(%ebp),%eax
0x0804836a : leave
0x0804836b : ret
程序执行时分析
(gdb) info registers
eax 0xbf820894 -1081997164
ecx 0xbf820810 -1081997296
edx 0x1 1
ebx 0x56eff4 5697524
esp 0xbf8207ec 0xbf8207ec
ebp 0xbf8207f8 0xbf8207f8
esi 0x42cca0 4377760
edi 0x0 0
eip 0x804837d 0x804837d
eflags 0x200292 [ AF SF IF ID ]
cs 0x73 115
ss 0x7b 123
ds 0x7b 123
es 0x7b 123
fs 0x0 0
gs 0x33 51
注:此时已经执行到main的第14行下一条指令是movl $0x3,0x4(%esp)此时的esp是0xbf8207ec。
5.1分析esp=0xbf8207ec的来历
(gdb) x/20 $esp
0xbf8207ec: 0x0056e