堆栈平衡
Posted mysqlinternal
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了堆栈平衡相关的知识,希望对你有一定的参考价值。
1 #include <stdio.h> 2 #include <unistd.h> 3 4 int abc() { 5 int d; 6 return 2; 7 } 8 int sum(int a) { 9 int c; 10 abc(); 11 return a; 12 } 13 int main() { 14 int b = 0; 15 b = sum(1); 16 printf("hello:%d ", b); 17 return 0; 18 } 1 .file "test.c" 2 .text 3 .globl abc 4 .type abc, @function 5 abc: 6 pushq %rbp 7 movq %rsp, %rbp 8 movl $2, %eax 9 popq %rbp 10 ret 11 .size abc, .-abc 12 .globl sum 13 .type sum, @function 14 sum: 15 pushq %rbp 16 movq %rsp, %rbp 17 subq $8, %rsp 18 movl %edi, -4(%rbp) 19 movl $0, %eax 20 call abc 21 movl -4(%rbp), %eax 22 leave 23 ret 24 .size sum, .-sum 25 .section .rodata 26 .LC0: 27 .string "hello:%d " 28 .text 29 .globl main 30 .type main, @function 31 main: 32 pushq %rbp 33 movq %rsp, %rbp 34 subq $16, %rsp 35 movl $0, -4(%rbp) 36 movl $1, %edi 37 call sum 38 movl %eax, -4(%rbp) 39 movl -4(%rbp), %eax 40 movl %eax, %esi 41 movl $.LC0, %edi 42 movl $0, %eax 43 call printf 44 movl $0, %eax 45 leave 46 ret 47 .size main, .-main 48 .ident "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.1) 5.4.0 20160609" 49 .section .note.GNU-stack,"",@progbits
分析一下堆帧:
1.call main 初始化:
2. main
pushq %rbp //会使rsp=rsp+4 存入调用main 之前的栈帧
movq %rsp, %rbp
3.分配临时变量
subq $16, %rsp
movl $0, -4(%rbp)
movl $1, %edi
call sum
4. sum
pushq %rbp //存入调用main 的栈帧
movq %rsp, %rbp
5.
subq $8, %rsp
call abc
pushq %rbp
movq %rsp, %rbp
6. abc 回退栈帧
popq %rbp
ret
7 回退sum
leave
ret
8 回退main
以上是关于堆栈平衡的主要内容,如果未能解决你的问题,请参考以下文章