Why do we "PUSH EBP" and "MOV EBP, ESP" in the CALLEE in Assembly?

Viewed 18372

Why do we push ebp as the first action in the Callee of an Assembly function?

I understand that then we use mov edi, [ebp+8] to get the passed in variables, but our esp is already pointing to return address of the Caller function. We can easily access the passed in variables with mov edi, [esp+4] or if we pushed the Callee registers, then mov edi, [esp+16].

So, why have that extra register in the cpu (the ebp) which you later have to manage in functions? i.e.

push ebp
mov ebp, esp

...

mov esp, ebp
pop ebp
2 Answers

The given answer from Remy is perfect, however here is one small addition, a thing you might also see right after

mov ebp, esp

it's very possible to see instruction such:

sub esp, 20h   ; creating space for local variables with size 20h
sub esp, CCh   ; creating space for local variables with size CCh

along side with an AND call sometimes (like and esp, 0FFFFFFF0h). This is also part of the dealing with the stack and it's done so the stack can be align and be divisible by 16. Of course all this depends on the used calling convention (cdecl, fastcall, stdcall etc.)

Related