Old EBP. Let us tackle these three aliens one by one.
Stack Pointer and ESP: ESP is a special purpose register on the CPU which always contains the address of the last data item pushed on to the stack. In figure 2 it is pointing to local3. Every time a new data item is pushed on to the value in stack pointer register is decreased by the size of the data item to show the current top of the stack. Similarly every time a data item is popped out of the stack the value in ESP is increased by the size of the data item to show the current top of the stack.
Frame Pointer and EBP: EBP is another special purpose register on CPU.Every time a function is called the value of EBP is pushed on to the stack just after the arguments and the return address. Once the value EBP is pushed to the stack, definitely stack pointer will move to reflect the new current top of the stack. This new current top is copied into the EBP register. So the EBP also known as frame pointer register points to the previous value of EBP (or say the value of EBP before entering the called function or Caller ‘s EBP) stored on the stack.
This gives us a mechanism to traverse within a frame on the stack. If you want to know
The return address of a function from stack you have to use Frame pointer of that function and not the stack pointer because it is dynamic and keeps changing.In this case if you want to know the return address.You have to read the data item just below the location where old EBP or caller’s EBP is saved.
So return address will be EBP + 4
So the flow of making a stack frame for a function starts with caller pushing the arguments passed to the called function followed by return address of the called function.
These two things are done internally as part of the X 86 Call instructions.
After this the control goes to the called function.
The called function will always start by first pushing the EBP and then updating it with new ESP.
PUSH EBP
MOV EBP, ESP
Return Address and EIP: We have been talking bout pushing the return address of the called function on to stack. You also learnt that pushing the arguments passed and the return address is done as a part of the X 86 Call instructions. But where does the call instruction get the return address from?? The answer is from EIP .EIP is again a
Special purpose register on the CPU which always points to the next instruction to be executed. So when function1 calls function2 the control goes to
Call Function2 (arg1,arg2).
At this point EIP contains the address of next instruction to be executed after the Call completes. So Call instruction pushes the value of EIP on stack just after pushing the arguments.

No comments:
Post a Comment