PoiNtEr->: Function's Prologue and Epilogue

                             Difference between a dream and an aim. A dream requires soundless sleep, whereas an aim requires sleepless efforts.

Search This Blog

Tuesday, January 8, 2013

Function's Prologue and Epilogue

In assembly language programming, the function prologue is a few lines of code at the beginning of a function, which prepare the stack and registers for use within the function. Similarly, the function epilogue appears at the end of the function, and restores the stack and registers to the state they were in before the function was called. The prologue and epilogue are not a part of the assembly language itself; they represent a convention used by assembly language programmers, and compilers of many higher-level languages. They are fairly rigid, having the same form in each function. Sometimes, function prologue and epilogue contain also buffer overflow protection code.

A function prologue typically does the following actions if the architecture has a base pointer (also known as frame pointer) and a stack pointer (the following actions may not be applicable to those architectures that are missing a base pointer or stack pointer) :
=>Pushes the old base pointer onto the stack, such that it can be restored later (by getting the new base pointer value which is set in the next step and is always pointed to this location).
=>Assigns the value of stack pointer (which is pointed to the saved base pointer and the top of the old stack frame) into base pointer such that a new stack frame will be created on top of the old stack frame (i.e. the top of the old stack frame will become the base of the new stack frame).
=> Moves the stack pointer further by decreasing or increasing its value, depending on whether the stack grows down or up. On x86, the stack pointer is decreased to make room for variables (i.e. the function's local variables).
As an example, here′s a typical IA-32 assembly language function prologue as produced by the GCC:
pushl %ebp 
movl %esp,%ebp 
subl $N,%esp

Function epilogue reverses the actions of the function prologue and returns control to the calling function. It typically does the following actions (this procedure may differ from one architecture to another):
=>Replaces the stack pointer with the current base (or frame) pointer, so the stack pointer is restored to its value before the prologue
=>Pops the base pointer off the stack, so it is restored to its value before the prologue
=>Returns to the calling function, by popping the previous frame's program counter off the stack and jumping to it The given epilogue will reverse the effects of either of the above prologues (either the full one, or the one which uses enter). For example, these three steps may be accomplished in 32-bit x86 assembly language by the following instructions (using AT&T syntax):
movl %ebp,%esp 
popl %ebp 

No comments:

Post a Comment