What is the use of “push

前端 未结 6 1624
我寻月下人不归
我寻月下人不归 2020-12-23 09:38

What effect these two instructions cause in the assembly code generated by gcc for x86 machines:

push %ebp
movl %esp, %ebp
6条回答
  •  Happy的楠姐
    2020-12-23 10:05

    unwind's explanation is the literal truth (one minor directional error notwithstanding), but doesn't explain why.

    %ebp is the "base pointer" for your stack frame. It's the pointer used by the C runtime to access local variables and parameters on the stack. Here's some typical function prologue code generated by GCC (g++ to be precise) First the C++ source.

    // junk.c++
    int addtwo(int a)
    {
        int x = 2;
    
        return a + x;
    }
    

    This generates the following assembler.

    .file   "junk.c++"
        .text
    .globl _Z6addtwoi
        .type   _Z6addtwoi, @function
    _Z6addtwoi:
    .LFB2:
        pushl   %ebp
    .LCFI0:
        movl    %esp, %ebp
    .LCFI1:
        subl    $16, %esp
    .LCFI2:
        movl    $2, -4(%ebp)
        movl    -4(%ebp), %edx
        movl    8(%ebp), %eax
        addl    %edx, %eax
        leave
        ret
    .LFE2:
        .size   _Z6addtwoi, .-_Z6addtwoi
        .ident  "GCC: (Ubuntu 4.3.3-5ubuntu4) 4.3.3"
        .section    .note.GNU-stack,"",@progbits
    

    Now to explain that prologue code (all the stuff before .LCFI2:), first:

    1. pushl %ebp stores the stack frame of the calling function on the stack.
    2. movl %esp, %ebp takes the current stack pointer and uses it as the frame for the called function.
    3. subl $16, %esp leaves room for local variables.

    Now your function is ready for business. Any references with a negative offset from the %ebp% register are your local variables (x in this example). Any references with a positive offset from the %ebp% register are your parameters passed in.

    The final point of interest is the leave instruction which is an x86 assembler instruction which does the work of restoring the calling function's stack frame. This is usually optimized away in to the faster move %ebp %esp and pop %ebp% sequence in C code. For illustrative purposes, however, I didn't compile with any optimizations on at all.

提交回复
热议问题