| Stack Internals |
|
|
|
| Written by Yash |
| Wednesday, 19 November 2008 00:41 |
|
Stack is a temporary abstract data type and data structure on the principle of Last In First Out (LIFO). Stack is a container of nodes and has two basic operations PUSH and POP. PUSH adds a node to top of stack and POP removes node from top of the stack. System Stack System stack provides a mechanism to allocate memory dynamically for various data associated with a function (or procedure). System stack will store following types of data:
Local variables: All the variables which are created inside a function except static variables are temporary and these will be destroyed after completing the execution of a procedure or after going outside the scope. Return address: Before CPU transfers execution control to new procedure, it will automatically store the next instruction pointer into a stack. Parameters: Before calling any procedure, all the parameters either stored in a System stack or it will store in register and this is completely depends on the calling convention of a function and availability of a CPU register. Registers: Typically, after entering a function, it stores some of CPU registers in system stack and make use of those CPU registers in the current function till it completes the procedure execution.
All parameters are pushed to function and stack clean up happens based on the calling convention. Compiler will generate prolog and epilog code to save and restore ESI, EDI, EBX, EBP registers if they are used inside a function. Compiler can create new calling conventions based on the need. There are different types of calling convention available in Visual C/C++ compiler:
Code generation for cdecl:
Code generation for stdcall: Caller is not cleaning up the stack in above code.
Code generation for fastcall:
Code generation for thiscall:
Executing a function in High level language will result in following operations internally:
Code generation for calling a function will look like:
In a stack dump you will find following data:
After entering a function, it stores EBP register in stack for use inside this function. This register is used mainly to access the stack and its parameters. If it’s using any registers during the execution of this function it will PUSH all those registers. In our example, it is pushing register EBX, ESI, EDI. Once it retrieves parameters it will execute the function to serve it purpose, releases all the local variables memory from stack if there is any, restores the registers which was PUSH’d earlier like EDI, ESI, and EBX, restore the EBP register which was PUSH’d earlier and return from function. RET instruction will POP the return address 0x004151d0 and transfers control to the caller.
|
| Last Updated on Wednesday, 19 November 2008 22:41 |



sree makes this comment
24 December 2009