explanation about push ebp and pop ebp instruction in assembly

ebp is known as the base pointer or the frame pointer. On entry to your function, you push it (to save the value for the calling function). Then, you copy esp, the stack pointer, into ebp, so that ebp now points to your function's stack frame. At the end of your function, you then pop ebp so that the calling function's value is restored.

For some clarification on exactly what is going on - the push instruction puts the value from the specified register (ebp in this case), onto the stack, and decrements the stack pointer by the appropriate amount. The pop operation is the opposite - it increments the stack pointer and takes a value from the stack and puts it in the specified register.


Maybe you're wondering about this:

push    ebp
mov ebp, esp
sub esp, 12

These lines are known as the assembly function prologue. The first 2 instructions save the previous base pointer (ebp) and set EBP to point at that position on the stack (right below the return address). This sets up EBP as a frame pointer.

The sub esp,12 line is saving space for local variables in the function. That space can be addressed with addressing modes like [ebp - 4]. Any push/pop of function args, or the call instruction itself pushing a return address, or stack frames for functions we call, will happen below this reserved space, at the current ESP.

At the end you have:

mov esp, ebp         ; restore ESP
pop ebp              ; restore caller's EBP
ret                  ; pop the return address into EIP

This is the inverse the prologue does (i.e. the epilogue), so the previous context can be restored. This is sometimes called "tearing down" the stack frame.

(EBP is non-volatile aka call-preserved in all standard x86 calling conventions: if you modify it, you have to restore your caller's value.)

The leave instruction does exactly what these two instructions do, and is used by some compilers to save code size. (enter 0,0 is very slow and never used (https://agner.org/optimize/); leave is about as efficient as mov + pop.)


Note that using EBP as a frame pointer is optional, and compilers don't do it for most functions in optimized code. Instead they save separate metadata to allow stack unwinding / backtrace.