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

AssemblyX86

Assembly Problem Overview


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

Assembly Solutions


Solution 1 - Assembly

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.

Solution 2 - Assembly

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.

Solution 3 - Assembly

The compiler use this instruction to free the used space by the function in the stack, the leave instruction has the same behavior as mov esp, ebp with pop ebp.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncompile-fanView Question on Stackoverflow
Solution 1 - AssemblyzneakView Answer on Stackoverflow
Solution 2 - AssemblyAbhay BuchView Answer on Stackoverflow
Solution 3 - AssemblykababView Answer on Stackoverflow