Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does leave do "mov esp,ebp" in x86 assembly?

Tags:

x86

assembly

It's said that the leave instruction is the same as :

mov esp,ebp pop ebp 

But what is mov esp,ebp here for? It doesn't seem valid to me...

like image 890
compile-fan Avatar asked Mar 29 '11 14:03

compile-fan


People also ask

What does MOV EBP ESP do?

A stack frame is used to store local variables and each function will have its own stack frame in memory. mov ebp, esp moves the current stack position into EBP which is the base of the stack. We now have a reference point that allows us to reference our local variables stored on the stack.

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 is ESP in x86?

The ESP register is the stack pointer for the system stack. It is rarely changed directly by a program but is changed when data is pushed onto the stack or popped from the stack. One use for the stack is in procedure calls. the address of the instructions following the procedure call instruction is stored on the stack.

What is EBP Assembly?

base pointer (EBP): register containing the. address of the bottom of the stack frame. instruction pointer (EIP): register containing. the address of the instruction to be executed. Other examples: EAX (return value), etc.


2 Answers

mov esp,ebp sets the stack pointer to the base frame address, effectively releasing the whole frame. (Don't forget that this is Intel syntax, the destination comes first.) If you didn't do it, once you call ret, you would still be using the called function's stack frame with your calling function, with crashtastic consequences.

like image 185
zneak Avatar answered Oct 17 '22 09:10

zneak


I think your issue is the fact that there are two different ways of writing x86 assembly. One is the AT&T notation and the other is the Intel notation. The order of the arguments to an instruction are reversed in Intel notation as opposed to AT&T. Your version of the assembly appears to be in Intel notation, which means that mov esp, ebp actaully moves the value in ebp to esp. In the more logical (in my opinion) AT&T notation it would be mov %ebp, %esp.

like image 37
Abhay Buch Avatar answered Oct 17 '22 09:10

Abhay Buch