2011年9月15日 星期四

Intel x86 Function-call Conventions

reference:
http://www.unixwiz.net/techtips/win32-callconv-asm.html
** the stack grows from high memory address to low memory addr **

When a function is called, the compiler generates assembly code by doing:
1. push parameters onto the stack

2. call the function
the processor push content of %EIP to the stack.
%EIP points to the next instruction (the instruction after CALL). So that after calling it can return to the caller.

The caller has lost control.

**The figure below grows from up to down.


3. Save and update %ebp
push %ebp
mov %esp, %ebp
The new base pointer (base frame) is from the %esp

4. save CPU register states

5. Allocate local variables

- Function Parameters are positive offsets from EBP (stack frame register)
- Local Variables occur as negative offsets from the EBP (stack frame pointer) register

At this point, the stack frame is set up correctly, and this is represented by the diagram to the right. All the parameters and locals are offsets from the %ebp register:
16(%ebp) - third function parameter
12(%ebp) - second function parameter
8(%ebp) - first function parameter
4(%ebp) - old %EIP (the function's "return address")
0(%ebp) - old %EBP (previous function's base pointer)
-4(%ebp) - first local variable
-8(%ebp) - second local variable
-12(%ebp) - third local variable

沒有留言:

張貼留言