Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly x86 - "leave" Instruction

Tags:

c

assembly

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?

like image 276
alexswo Avatar asked Apr 22 '15 07:04

alexswo


People also ask

What does the leave instruction Do x86?

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.

What does RETQ do in assembly?

The retq instruction pops the return address from the stack into the destination %rip , thus resuming at the saved return address.

What does Callq mean in assembly?

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.

What is MOV instruction x86?

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).


1 Answers

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.

like image 126
Michael Avatar answered Oct 08 '22 22:10

Michael