0.本週進行了網易 mooc 公開課 《linux內核分析》課程,撰寫此博客,一爲完成做業,二爲記錄學習收穫。linux
命令解釋: push %eax <==> sub $4 ,%esp movl %eax,(%esp) pop % eax <==> movl (%esp),%eax addl $4,%esp call 0x12345 <==> push %eip movl $012345,%eip ret <==> popl %eip enter <==> pushl %ebp movl %esp,%ebp leave <==> movl %ebp,%esp popl %ebp
1.c程序代碼:函數
int g(int x,int y) { return x + y; } int f(int x) { return g(x , 2*x); } int main(void) { return f(2) + 3; }
2.使用gcc –S –o main.s main.c -m32
將C程序彙編成32位彙編代碼:學習
1. g: 2. pushl %ebp 3. movl %esp, %ebp 4. movl 12(%ebp), %eax 5. movl 8(%ebp), %edx 6. addl %edx, %eax 7. popl %ebp 8. ret 9. f: 10. pushl %ebp 11. movl %esp, %ebp 12. subl $8, %esp 13. movl 8(%ebp), %eax 14. addl %eax, %eax 15. movl %eax, 4(%esp) 16. movl 8(%ebp), %eax 17. movl %eax, (%esp) 18. call g 19. leave 20. ret 21. main: 22. pushl %ebp 23. movl %esp, %ebp 24. subl $4, %esp 25. movl $2, (%esp) 26. call f 27. addl $3, %eax 28. leave 29. ret
3.程序分析spa
(1)pushl %ebp
(2)movl %esp, %ebp
(3)subl $4, %esp
(4)movl $2, (%esp)
這裏是將當即數2存到esp指向的內存地址中code
(5)call f
(6)pushl %ebp
(7)movl %esp, %ebp
(8)subl $8, %esp
(9)movl 8(%ebp), %eax
(10)addl %eax, %eax
(11)movl %eax, 4(%esp)
(12)movl 8(%ebp), %eax
(13)movl %eax, (%esp)
(14)call g
(15) pushl %ebp
(16)movl %esp, %ebp
(17) movl 12(%ebp), %eax
(18)movl 8(%ebp), %edx
(19)addl %edx, %eax
(20)popl %ebp
(21)ret
(22) leave
(23) ret
(24)addl $3, %eax
(25)leave
(26)ret
最終返回 eax = 9圖片
4.學習總結
計算機經過執行存儲的程序指令來進行工做,在程序執行過程當中,堆棧存儲了臨時的數據,以便進行函數的調用和返回,由ebp和esp肯定的臨時棧對當前程序的執行環境進行了明確。在本次做業的完成過程當中,加深了對堆棧變化的理解,對於計算機內部寄存器、存儲器之間完美有序的配合,實現程序執行的機制有了更深入的理解,是一次頗有意義的實踐。ip
bintasong 原創做品轉載請註明出處《Linux內核分析》MOOC課程http://mooc.study.163.com/course/USTC-1000029000內存