Search code examples
c++cassemblystack-frameepilogue

Function Prologue and Epilogue in C


I know data in nested function calls go to the Stack.The stack itself implements a step-by-step method for storing and retrieving data from the stack as the functions get called or returns.The name of these methods is most known as Prologue and Epilogue.

I tried with no success to search material on this topic. Do you guys know any resource ( site,video, article ) about how function prologue and epilogue works generally in C ? Or if you can explain would be even better.

P.S : I just want some general view, not too detailed.


Solution

  • There are lots of resources out there that explain this:

    to name a few.

    Basically, as you somewhat described, "the stack" serves several purposes in the execution of a program:

    1. Keeping track of where to return to, when calling a function
    2. Storage of local variables in the context of a function call
    3. Passing arguments from calling function to callee.

    The prolouge is what happens at the beginning of a function. Its responsibility is to set up the stack frame of the called function. The epilog is the exact opposite: it is what happens last in a function, and its purpose is to restore the stack frame of the calling (parent) function.

    In IA-32 (x86) cdecl, the ebp register is used by the language to keep track of the function's stack frame. The esp register is used by the processor to point to the most recent addition (the top value) on the stack. (In optimized code, using ebp as a frame pointer is optional; other ways of unwinding the stack for exceptions are possible, so there's no actual requirement to spend instructions setting it up.)

    The call instruction does two things: First it pushes the return address onto the stack, then it jumps to the function being called. Immediately after the call, esp points to the return address on the stack. (So on function entry, things are set up so a ret could execute to pop that return address back into EIP. The prologue points ESP somewhere else, which is part of why we need an epilogue.)

    Then the prologue is executed:

    push  ebp         ; Save the stack-frame base pointer (of the calling function).
    mov   ebp, esp    ; Set the stack-frame base pointer to be the current
                      ; location on the stack.
    sub   esp, N      ; Grow the stack by N bytes to reserve space for local variables
    

    At this point, we have:

    ...
    ebp + 4:    Return address
    ebp + 0:    Calling function's old ebp value
    ebp - 4:    (local variables)
    ...
    

    The epilog:

    mov   esp, ebp    ; Put the stack pointer back where it was when this function
                      ; was called.
    pop   ebp         ; Restore the calling function's stack frame.
    ret               ; Return to the calling function.