Monday, September 21, 2009

Stack Frame

Before calling a function, the caller will first reserved space for the parameters in the stack. For example, assuming the parameters occupies 20 bytes:

sub esp,14h

Following this is a series of mov statment to move the parameters to the stack using offset with ebp. For example,

mov dword ptr [edp-14h],3
:
:

Then the call operation is used to jump to the function. Call will push the eip onto the stack (esp will advance as a result).

At the beginning of the function, the compiler generates a stack frame using the frame base pointer register ebp. The function prologue saves the current ebp onto the stack before setting up a new stack frame:

mov edi, edi
push ebp
mov edp, esp

As a result, the ebp of the new frame points to the old ebp value (the last frame base). The ebp is then used to access the parameter (positive offset) and local variables (negative offset).

At this stage, the call stack contains the following (growing downwards):

parm1
parm2
:
return address
saved ebp of caller
local variable1
local variable2
:

When the function finishes, the epilogue restore the previous stack frame

add esp,14h ; clean up the parameter stack space assuming this is stdcall
mov esp, ebp
pop ebp
ret

No comments: