zoukankan      html  css  js  c++  java
  • 堆栈平衡


    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

  • 相关阅读:
    2021/3/12
    2021/3/11
    2021/3/10
    2021/3/9
    2021/3/8
    2021/3/5
    2021/3/4
    2021/3/3
    2021/3/2
    2021/3/1
  • 原文地址:https://www.cnblogs.com/mysqlinternal/p/12737841.html
Copyright © 2011-2022 走看看