assemblyx86stack-framestack-pointerframe-pointer

What are the ESP and the EBP registers?


I found that the ESP register is the current stack pointer and EBP is the base pointer for the current stack frame. However, I don't understand these definitions (I am just starting to learn how to code in assembler).

What I understand is that ESP points towards the stack itself and EBP points towards whatever is on top of the stack1. But these are just my guesses and they are most likely incorrect. Otherwise, what would a statement like the following mean?

MOV EBP, ESP    

Footnote 1: Editor's note: Yes, that's incorrect. In standard terminology, the "top of the stack" is where ESP points, even though it's the lowest address in the stack frame. By analogy to a stack data structure that grows upward, even though the callstack on x86 (like most ISAs) grows downward.


Solution

  • esp is the stack pointer. ebp is for a stack frame so that when you enter a function, ebp can get a copy of esp at that point. Everything already on the stack, the return address, passed-in parameters, etc. and things that are global for that function (local variables) will now be a static distance away from the stack frame pointer for the duration of the function. esp is now free to wander about as the compiler desires and can be used when nesting to other functions (each needs to preserve the ebp naturally).

    It is a lazy way to manage the stack. It makes compiler debugging and understanding compiler-generated code easier, but it uses a register that could have been otherwise general-purpose.