Function Prologue & Epilogue
A function saves registers, sets up its stack frame, uses local variables, then tears down the frame and restores registers before returning - the pattern you see in every compiled function.
Every compiled function follows a standard pattern: the prologue saves registers the function will use and sets up the stack frame; the body does the actual work; the epilogue restores the saved registers and returns. Recognising this pattern is the first skill in reverse engineering — it tells you where functions start and end, which registers are local variables, and how arguments are passed. In x86 you will see 'push rbp; mov rbp, rsp' as the classic prologue; here we show the same concept with our simplified instruction set.
Simulator
Walkthrough Guide
- 1
Set up the argument and call
Do this: Step through MOV R0, #7 and CALL my_func
Watch for: R0 = 7. CALL pushes the return address and jumps to my_func
R0 carries the argument (7) into the function. CALL saves the return address on the stack.
- 2
Function prologue: save registers
Do this: Step through PUSH R5 and PUSH R6
Watch for: R5 and R6's values are pushed onto the stack. SP decrements twice
The prologue saves callee-saved registers that the function body will overwrite. This is a contract: the function promises to restore these registers before returning, so the caller's data is preserved.
- 3
Function body: use saved registers as locals
Do this: Step through MOV R5, R0 / MOV R6, R0 / ADD R0, R5
Watch for: R5 = 7, R6 = 7, R0 = 14 (doubled)
The function uses R5 and R6 as local working registers. Since they were saved in the prologue, overwriting them is safe. The actual computation doubles R0 by adding it to the saved copy in R5.
- 4
Function epilogue: restore and return
Do this: Step through POP R6 / POP R5 / RET
Watch for: R6 and R5 restore their original values (in LIFO order). RET jumps back to HALT. R0 = 14
The epilogue is the prologue in reverse. POP restores each register, then RET returns to the caller. The caller sees R0 = 14 (the result) and R5/R6 unchanged — exactly as if the function never touched them.
Objectives
- •Watch PUSH R5 and PUSH R6 save register values onto the stack
- •See the function body use R5 and R6 as local working registers
- •Watch POP R6 and POP R5 restore the original values (LIFO order)
- •See RET return to the instruction after CALL - R0 holds 14
Hints
- The prologue saves registers the function will modify; the epilogue restores them. This is why callee-saved registers survive function calls.