explanation about push ebp and pop ebp instruction in assembly

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.

Leave a Comment