Prolog and Epilogue function in C

I know that data in nested function calls go onto the stack. The stack itself implements a step-by-step method of storing and retrieving data from the stack when functions are called or returned. The name of these methods is best known as Prologue and Epilogue.

I did not succeed in finding materials on this topic. Do you guys know any resource (website, video, article) about how the prolog and epilog function works in general in C? Or, if you can explain, it would be even better.

PS: I just need a general view, not too detailed.

+6
source share
3 answers

There are many resources that explain this:

to name a few.

In principle, as you have already described, a stop performs several tasks when executing a program:

  • Tracking where to return when calling a function
  • Storing local variables in the context of a function call
  • Passing arguments from the calling function to the call.

A prolog is what happens at the beginning of a function. Its responsibility is to create a stack frame of the called function. The epilogue is the exact opposite: this is what happens last in the function, and its goal 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 track the frame of the function stack. The esp register is used by the processor to indicate the most recent addition (top value) on the stack.

The call does two things: first, it pushes the return address onto the stack, and then goes to the called function. Immediately after call , esp points to the return address on the stack.

Then the prolog 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 moment we have:

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

Epilogue:

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

Each function has an identical prologue (beginning of function code) and epilogue (end of function).

Prolog: The Prolog structure looks like this: push ebp mov esp, ebp

Epilogue: the Prolog structure looks like this: leave RET

Read more: what is Prolog and Epilogue

-1
source

All Articles