tags:

views:

19

answers:

2

Standard Entry Sequence:

_function:
    push ebp       ;store the old base pointer
    mov ebp, esp   ;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

+3  A: 

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.

KennyTM
What's the difference between *automatic variables* and *parameter*?
Mask
@Mask: automatic variables are the local variables in the function. e.g. `int f(int y){ int z=y+7; return z*z; }` Here `y` is a parameter, and `z` is an automatic (local) variable.
KennyTM
@KennyTM,thanks!I've updated a little about the exit sequence,why is `ret` necessary there?
Mask
@Mask: `ret` pops the return_address and jumps to that point.
KennyTM
A: 

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.

Paul R
What's *ABI* ???BTW can you also elaborate how to reference parameters and local variables all via one common pointer and offset?
Mask
@Mask: Application Binary Interface. It's the 3rd link in Google.
KennyTM
@Mask: as KennyTM rightly says, the ABI is the Application Binary Interface - it defines the `calling conventions` for a given architecture. As for parameters + local variables - they are all on the stack, so you typically use an address register as a pointer into this stack frame and then you can load/store locals and params using indexed/offset addressing.
Paul R