The C Function Call Mechanism ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Current Function ~~~~~~~~~~~~~~~~ int current (int a, int b, int c) { int x, y = 223; ... } Memory Layout ~~~~~~~~~~~~~ 0 +-------------+ | text | machine code and constants +-------------+ | data | global and static local variables +-------------+ | heap | dynamically allocated storage (malloc()); | | grows upward in memory +~~~~~~~~~~~~~+ | hole | +~~~~~~~~~~~~~+ <-- stack pointer \ / | stuff | | | +-------------+ <-- frame pointer | current | | automatic | x storage for automatic locals | frame | | variables | y (if not in registers) | | +-------------+ | | | return | return address | | | information | old stack/frame/argument pointers | | | | saved registers | | +-------------+ <-- argument pointer | | | arguments | c storage for arguments | | | | b (if not in registers) | \ | | a | stack; grows +-------------+ <-- old stack pointer | downward / | stuff | | in memory | +-------------+ <-- old frame pointer | frame in | | automatic | | calling | +-------------+ | function | | return info | | | +-------------+ <-- old argument pointer | \ | arguments | | +-------------+ | | additional | | | frames | | size-1 +-------------+ / Function Call ~~~~~~~~~~~~~ 1. Evaluate the arguments and push their values onto the stack (in SOME order) 2. Push the return information (saved registers, copies of the current stack/ frame/argument pointers, and return address) onto the stack 3. Set the new argument pointer 4. Transfer control to the function 5. Set the new frame pointer (thereby allocating stack space for the automatic local variables but NOT initializing them) 6. Set the new stack pointer to the frame pointer 7. Begin executing the code in current(), starting with non-static initializers Function Return ~~~~~~~~~~~~~~~ 1. Restore the return information 2. Put the value returned in a register or push it onto the stack 3. Transfer control to the return address CS-223-02/05/20