It's said that the "leave" instruction is similar to:
movl %ebp, %esp popl %ebp
I understand the movl %ebp, %esp
part, and that it acts to release stored up memory (as discussed in this question).
But what is the purpose of the popl %ebp
code?
Description. The leave instruction reverses the actions of an enter instruction. leave copies the frame pointer to the stack point and releases the stack space formerly used by a procedure for its local variables. leave pops the old frame pointer into (E)BP, thus restoring the caller's frame.
The retq instruction pops the return address from the stack into the destination %rip , thus resuming at the saved return address.
Call/return are used to transfer control between functions. The callq instruction takes one operand, the address of the function being called. It pushes the return address (current value of %rip , which is the next instruction after the call) onto the stack and then jumps to the address of the function being called.
The mov instruction copies the data item referred to by its second operand (i.e. register contents, memory contents, or a constant value) into the location referred to by its first operand (i.e. a register or memory).
LEAVE
is the counterpart to ENTER
. The ENTER
instruction sets up a stack frame by first pushing EBP
onto the stack and then copies ESP
into EBP
, so LEAVE
has to do the opposite, i.e. copy EBP
to ESP
and then restore the old EBP
from the stack.
See the section named PROCEDURE CALLS FOR BLOCK-STRUCTURED LANGUAGES in Intel's Software Developer's Manual Vol 1 if you want to read more about how ENTER
and LEAVE
work.
enter n,0
is exactly equivalent to (and should be replaced with)
push %ebp mov %esp, %ebp # ebp = esp, mov ebp,esp in Intel syntax sub $n, %esp # allocate space on the stack. Omit if n=0
leave
is exactly equivalent to
mov %ebp, %esp # esp = ebp, mov esp,ebp in Intel syntax pop %ebp
enter
is very slow and compilers don't use it, but leave
is fine. (http://agner.org/optimize). Compilers do use leave
if they make a stack frame at all (at least gcc does). But if esp
is already equal to ebp
, it's most efficient to just pop ebp
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With