Having problem understanding Standard Entry Sequence
Standard Entry Sequence:
_function:
push ebp ;store the old base pointer
mov ebp, esp 开发者_Go百科 ;make the base pointer point to the current
;stack location – at the top of the stack is the
;old ebp, followed by the return address and then
;the parameters.
sub esp, x ;x is the size, in bytes, of all
;"automatic variables" in the function
at the top of the stack is the old ebp, followed by the return address and then the parameters.
The old ebp is there because push ebp
,
but why are the return address and the parameters there too?
UPDATE
Standard Exit Sequence
mov esp, ebp ;reset the stack to "clean" away the local variables
pop ebp ;restore the original base pointer
ret ;return from the function
What does ret
actually do?I think the esp should have already reached the return address at the line pop ebp
In x86 standard call convention, before a function is called, the parameter are pushed to the stack first.
And the call
op means "push the next address to the stack, then jump to the function", so the return address is on the stack too.
That means, before the push ebp
, the stack looks like:
...
param2
param1
param0
return_address <- esp
After calling push ebp
it becomes
...
param2
param1
param0
return_address
ebp <- esp
Finally, mov ebp, esp
stores this esp
into ebp
, so you can refer to the return address and all input parameters relative to ebp
, and free the stack for local use.
It's all part of the ABI. By convention the caller creates a stack frame
which contains parameters, etc, then calls the function (during which process the return address is also pushed onto the stack). The called function will allocate additional space on the stack for local variables and can reference parameters and local variables all via one common pointer and offset.
精彩评论