首页 > 系统服务 > 详细

linux内核分析作业:以一简单C程序为例,分析汇编代码理解计算机如何工作

时间:2016-02-27 20:42:06      阅读:168      评论:0      收藏:0      [点我收藏+]

一、实验

使用gcc –S –o main.s main.c -m32

命令编译成汇编代码,如下代码中的数字请自行修改以防与他人雷同

 1 int g(int x)
 2 {
 3   return x + 3;
 4 }
 5 int f(int x)
 6 {
 7   return g(x);
 8 }
 9 int main(void)
10 {
11   return f(8) + 1;
12  }

修改过后源代码:

技术分享

经过编译过的原始汇编代码:

技术分享

简单地汇编代码:

 1 g:
 2     pushl    %ebp
 3     movl    %esp, %ebp
 4     movl    8(%ebp), %eax
 5     addl    $4, %eax
 6     popl    %ebp
 7     ret
 8 f:
 9     pushl    %ebp
10     movl    %esp, %ebp
11     subl    $4, %esp
12     movl    8(%ebp), %eax
13     movl    %eax, (%esp)
14     call    g
15     leave
16     ret
17 main:
18     pushl    %ebp
19     movl    %esp, %ebp
20     subl    $4, %esp
21     movl    $2, (%esp)
22     call    f
23     addl    $3, %eax
24     leave
25     ret

堆栈变化图:

技术分享

技术分享

在汇编代码中分析堆栈变化:

 1 g:
 2     pushl    %ebp      
 3     movl    %esp, %ebp   
 4     movl    8(%ebp) ,%eax 
 5     addl    $4, %eax ;eax + 4 = 6
6 popl %ebp ; 7 ret 8 f: 9 pushl %ebp ;ebp1入栈 ebp指向1 esp指向4 10 movl %esp, %ebp ;ebp = esp =4 11 subl $4, %esp ; 12 movl 8(%ebp), %eax 13 movl %eax, (%esp) 14 call g 15 leave 16 ret 17 main: 18 pushl %ebp ;ebp0入栈 ebp指向0 esp指向1 19 movl %esp, %ebp ;ebp = esp =1 20 subl $4, %esp ; esp-4 esp指向2 21 movl $2, (%esp) ;2入栈 22 call f ;调用f函数 23 addl $3, %eax ;eax+3 24 leave ; esp = ebp = 1 esp0出栈 ebp = 0 ebp-4 = 0 25 ret

 

linux内核分析作业:以一简单C程序为例,分析汇编代码理解计算机如何工作

原文:http://www.cnblogs.com/20135327leme/p/5223422.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!