Stacks usually grown down, i.e., the stack starts at a higher address in memory and progressively gets lower.
- To keep track of current growth of the stack, the hardware defines a register as the stack pointer.
- The compiler (or the programmer, when writing in assembler) users this register to keep track of current top of the stack.
- It is stored in the register ESP.
- A call stack is used for several related purposes, but the main reason for have one is to keep track of the point to which each active subrountine should return control when it finishes executing.
- Active subrountine
- An active subrountine is one that has been called by yet to complete execution after which control should be handed back to the point of the call.
How it works?
- Return address
- Store the returning address somewhere, so that we can continue executing the current function after completion of called function.
- Other info
- Saving other information about current function.
- Providing the callee with the parameters
- Provided called function some space to store its automic variables
- Return value
- Providing some mechanism to get return value from the called function.
- It is implemented using EAX register. Called function stores return value in EAX.
Execution in Steps
- Push the parameters in the reverse order (right to left)
- Call function now
- It implicitly pushes the return address into STACK
- Push the current EBP
- i.e., push Frame Pointer (FP) of calling function into stack. We need to do this to continue with the execution of calling function after return from the called function,
- Copy the ESP to EBP
- Yes, this location will be the new FRAME Pointer
- Allocate space on stack for local variable
- It is done by decrementing ESP
- Put the value to be returned in EAX
- Copy current EBP to ESP
- It will reduce stack size. Now we have the old FP at the top of the stack??
- The stack frame generally includes the following components
- The return address
- Argument variables passed on the stack
- Local variables
- Saved copies of any registers modified by the subprogram that need to be restored.
- If you are a programmer accept arbitrary input into a stack variable (say, reading from the keyboard or over the network), you need to say how big that data is going to be.
- The OS can make the stack not executable.