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

Why are we push ebp as the first action in the Callee Assembly function?

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

So why is this extra register in processor ( ebp ) that you later need to manage functions? i.e.

 push ebp mov ebp, esp ... mov esp, ebp pop ebp 
+8
source share
2 answers

It sets a new stack frame inside the called party, while maintaining the stack frame of the calling party. The stack frame provides consistent access to the passed parameters and local variables using fixed offsets relative to EBP anywhere in the function, while the ESP can continue to change as needed while the function is running. ESP is a moving target, so accessing parameters and variables using dynamic offsets relative to ESP can be difficult, if not impossible, depending on how the function uses the stack. Creating a stack frame is generally safer by using several bytes of stack space to store a pointer to the stack frame of the caller.

+8
source

This answer from Remy is perfect, however here is one small addition that you can also see right after

 mov ebp, esp 

It is very possible to see an instruction like this:

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

along with calling AND sometimes (like and esp, 0FFFFFFF0h). This is also part of working with the stack, and this is done so that the stack can be aligned and divided by 16. Of course, it all depends on the calling convention used (cdecl, fastcall, stdcall, etc.)

+2
source

All Articles