Chinaunix首页 | 论坛 | 博客
  • 博客访问: 430756
  • 博文数量: 127
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 810
  • 用 户 组: 普通用户
  • 注册时间: 2013-07-02 20:51
文章分类

全部博文(127)

文章存档

2018年(6)

2015年(18)

2014年(33)

2013年(70)

分类: LINUX

2013-07-06 11:47:15

原文地址:函数堆栈结构 作者:wwm

 

要重点分析函数的栈结构。要了解由于体系设计的问题,堆栈指针向内存低方向增长,但是数据复制操作等,则是往高内存增长。

当函数调用时候,首先把参数从右往左入栈(通常),然后把当前的指令地址压入堆栈--------------这一部分在函数调用外部进行

函数体内 ,首先要保存ebp,压入堆栈三后,把当前的sp作为该函数的帧指针FP,依据FP界定该函数区域-------------这部分通常在被调函数内处理

FP往低地址便开始存放该函数的局部变量。

 

例子源代码:

#include

int fun(int a,int b);

int main(void)

{

int a;

a =fun(1,2);

return a;

}

int fun(int a,int b)

{

        int c;

        c =a+b;

return c;

}

 

[root@localhost test]# gcc –g tiny.c

对应汇编代码:

[root@localhost test]# gdb a.out  -q

(gdb) disass main

Dump of assembler code for function main:

0x080482f4 :    push   %ebp //保存ebp基地址

0x080482f5 :    mov    %esp,%ebp//设置函数的栈FP

0x080482f7 :    sub    $0x8,%esp

0x080482fa :    and    $0xfffffff0,%esp

0x080482fd :    mov    $0x0,%eax

0x08048302 :   sub    %eax,%esp

0x08048304 :   sub    $0x8,%esp

0x08048307 :   push   $0x2  //参数2压栈

0x08048309 :   push   $0x1   //参数1压栈

0x0804830b :   call   0x804831b //调用call

0x08048310 :   add    $0x10,%esp

0x08048313 :   mov    %eax,0xfffffffc(%ebp) //取函数返回值到a变量

0x08048316 :   mov    0xfffffffc(%ebp),%eax

0x08048319 :   leave 

0x0804831a :   ret   

End of assembler dump.

(gdb) disass fun

Dump of assembler code for function fun:

0x0804831b :     push   %ebp

0x0804831c :     mov    %esp,%ebp

0x0804831e :     sub    $0x4,%esp

0x08048321 :     mov    0xc(%ebp),%eax

0x08048324 :     add    0x8(%ebp),%eax

0x08048327 :    mov    %eax,0xfffffffc(%ebp)

0x0804832a :    mov    0xfffffffc(%ebp),%eax

0x0804832d :    leave  //返回原指令

0x0804832e :    ret   

End of assembler dump.

阅读(950) | 评论(0) | 转发(0) |
0

上一篇:浅析Linux下core文件

下一篇:内存对齐问题

给主人留下些什么吧!~~