Presentation is loading. Please wait.

Presentation is loading. Please wait.

C function call conventions and the stack

Similar presentations


Presentation on theme: "C function call conventions and the stack"— Presentation transcript:

1 C function call conventions and the stack
based on ©Gabriel Kliot, Technion

2 ©Gabriel Kliot, Technion
The stack High Addresses 0x5000 Bottom of the Stack . Stack grows down 0x1004 esp 0x1000 . Pushes Move the Top Of Stack to Lower Addresses Pops Move the Top Of Stack to Higher Addresses Low Addresses ESP always points on the last item on the stack PUSH decrements ESP and writes the value on top of the stack POP reads the value from top of the stack and increments ESP ©Gabriel Kliot, Technion

3 ©Gabriel Kliot, Technion
#1 - The caller’s actions before the function call int main() { foo(3,5); } int foo(int x, int y); Caller saved EAX, ECX, EDX – if needed Argument 2 = 5 Argument 1 = 3 Return address esp main() pushes EAX, ECX, EDX on the stack (if needed) main() pushes the arguments of foo(), last argument first on the stack main() issues: call foo EIP register is pushed on the stack EIP is loaded with foo() address ©Gabriel Kliot, Technion

4 ©Gabriel Kliot, Technion
#2 - The callee’s actions after the function call int main() { foo(3,5); } int foo(int x, int y); Caller saved EAX, ECX, EDX – if needed Argument 2 = 5 [EBP+12] Argument 1 = 3 [EBP+8] Return address Old (main()’s) EBP ebp foo() sets up its stack frame: pushl %ebp movl %esp, %ebp store EBX, ESI, EDI on the stack (if needed) allocate space for local vars on the stack Old ESI, EDI, EBX Function frame Local variable 1 Local variable 2 esp ©Gabriel Kliot, Technion

5 ©Gabriel Kliot, Technion
#3 - The callee’s actions before returning int main() { foo(3,5); } int foo(int x, int y); Caller saved EAX, ECX, EDX – if needed Argument 2 = 5 Argument 1 = 3 esp store return value in EAX advance ESP back to point above all local variables Restore EBX, ESI, EDI – pop them of the stack restore EBP: movl %ebp,%esp – (not really necessary if ESP already points to where old EBP stored) popl %ebp ret: pops the return address of the stack and stores it into EIP ©Gabriel Kliot, Technion

6 ©Gabriel Kliot, Technion
#4 - The caller’s actions after returning int main() { foo(3,5); } int foo(int x, int y); esp main can pop all arguments of the stack add $8, %esp Use the return value stored in EAX POP EAX, ECX, EDX (if needed) ©Gabriel Kliot, Technion


Download ppt "C function call conventions and the stack"

Similar presentations


Ads by Google