Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 382
Artur Grigio Avatar asked Mar 16 '16 20:03

Artur Grigio


1 Answers

It is establishing a new stack frame within the callee, while preserving the stack frame of the caller. A stack frame allows consistent access to passed parameters and local variables using fixed offsets relative to EBP anywhere in the function, while ESP is free to continue being modified 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 tricky, if not impossible, depending on how the function uses the stack. Creating a stack frame is generally safer, at the cost of using a few bytes of stack space to preserve the pointer to the caller's stack frame.

like image 72
Remy Lebeau Avatar answered Mar 19 '23 11:03

Remy Lebeau