简单c程序汇编代码分析

时间:2021-03-14 00:56:00

c源代码如下:

#include <stdio.h>
#include <stdlib.h>

int test()
{
int arg1 = 3;
int arg2 = 7;

int diff = arg2 - arg1;

return diff;
}

int main()
{
int res;

res = test();

printf("res=%d\n", res);

return 0;
}

首先使用gcc test.c -g对上面的代码进行编译,自动生成目标文件a.out;然后使用objdump -S a.out查看汇编代码,截取片断如下:

int test()
{
80483e4: 55 push %ebp 保存帧指针,帧指针入栈
80483e5: 89 e5 mov %esp,%ebp 使帧指针指向栈指针
80483e7: 83 ec 10 sub $0x10,%esp 申请16字节的栈空间
int arg1 = 3;
80483ea: c7 45 fc 03 00 00 00 movl $0x3,-0x4(%ebp) 把3入栈
int arg2 = 7;
80483f1: c7 45 f8 07 00 00 00 movl $0x7,-0x8(%ebp) 把7入栈

int diff = arg2 - arg1;
80483f8: 8b 45 fc mov -0x4(%ebp),%eax 取出3,放入寄存器%eax
80483fb: 8b 55 f8 mov -0x8(%ebp),%edx 取出7,放入寄存器%edx
80483fe: 89 d1 mov %edx,%ecx 把寄存器%edx的值交给寄存器%ecx
8048400: 29 c1 sub %eax,%ecx 寄存器%ecx的值减去寄存器%eax的值,再放入寄存器%ecx
8048402: 89 c8 mov %ecx,%eax 把寄存器%ecx的值交给寄存器%eax
8048404: 89 45 f4 mov %eax,-0xc(%ebp) 寄存器%eax的值保存在栈上,diff是局部变量,他的值是存储在栈上的

return diff;
8048407: 8b 45 f4 mov -0xc(%ebp),%eax 从栈取出diff,交给寄存器%eax,这样寄存器%eax保存的就是函数返回值了
}
804840a: c9 leave 准备栈,这里应该是恢复到之前的栈,即要恢复%esp和%ebp
804840b: c3 ret 返回到call调用之后的那个地址继续执行,即返回到804841a

0804840c <main>:


int main()
{
804840c: 55 push %ebp
804840d: 89 e5 mov %esp,%ebp
804840f: 83 e4 f0 and $0xfffffff0,%esp
8048412: 83 ec 20 sub $0x20,%esp
int res;

res = caller();
8048415: e8 ca ff ff ff call 80483e4 <test> 调用test函数
804841a: 89 44 24 1c mov %eax,0x1c(%esp) 将返回值入栈

printf("res=%d\n", res);
804841e: b8 00 85 04 08 mov $0x8048500,%eax
8048423: 8b 54 24 1c mov 0x1c(%esp),%edx
8048427: 89 54 24 04 mov %edx,0x4(%esp)
804842b: 89 04 24 mov %eax,(%esp)
804842e: e8 e9 fe ff ff call 804831c <printf@plt>

return 0;
8048433: b8 00 00 00 00 mov $0x0,%eax
}
8048438: c9 leave
8048439: c3 ret
804843a: 90 nop