Stack Frames
Local Variables
Consider a subroutines that contains variable declarations:
int sub1 (int n) {
int x; float y; char z;
...
}
The variables x
, y
, and z
are local variables
:
- They only exist while the subroutine is active.
- Then the subroutines exist, the local variables disappear.
Stack Frames
The a HLL subroutines is called, a new stack frame is created on the stack (by the compiler).
The stack frame holds data pertinent to this particular call, including:
- Return address
- Parameters
- Local Variables
ESP and EBP
Because of nested calls, several stack frames may be present simultaneously.
The ESP always points to the top of the stack; however, this may alter as space is created for local data.
Another register, the EBP (base pointer), remains stable and can be used to a access parameters and variables:
- Add or subtract offset to EBP.
Stack Frames
The stack frame is made of the following components:
- Parameters
- Return addresses
- The previous base pointer location
- Local variables
How Does it Work?
- ESP is always pointing to the top of the stack.
- EBP initially contains address of base of the stack.
When calling a subroutine to following happens:
- The parameters are pushed onto the stack.
- The return address is pushed onto the stack.
- The old EBP is pushed onto the stack.
- The current address of the top of the stack is put onto EBP.
- The local variables are installed on the stack, causing the ESP to alter.
When call returns:
- Clean up local variables.
- Restore previous stack base by popping into EBP.
- Pop return address into IP.
Calling routine is responsible for cleaning it’s parameters from the stack.