Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 40 ยท The Stack and Functions

Stack Frames, Prologues and Epilogues

See how a function builds its stack frame with push rbp, mov rbp, rsp and sub rsp, where locals live, what leaf functions skip, and how a debugger walks frames.

Calls and returns showed how call leaves a return address on the stack. But a real function needs more than that. It has local variables, it may save registers it wants to reuse, and it may call other functions of its own. All of that has to live somewhere, and the place is the function's stack frame: a slice of the stack that belongs to one call and disappears when that call returns.

This lesson shows the classic frame layout used by compilers at -O0, the instructions that build and tear it down (the prologue and epilogue), and how optimized code often skips most of it. You will also see how a debugger turns a chain of saved rbp values into a backtrace. The examples use x86-64 System V conventions from Calling Conventions and the stack rules from The Stack.

What lives in a frame

Each active call owns a block of the stack, between the caller's data above it and whatever the function calls next below it. Because the stack grows toward lower addresses, the layout looks like this, from high to low:

flowchart TB
  A["caller's frame (higher addresses)"] --> B["return address, rbp + 8"]
  B --> C["saved rbp of the caller, rbp + 0"]
  C --> D["local variables, rbp - 8, rbp - 16, ..."]
  D --> E["rsp points to the lowest byte in use"]

One frame: the return address pushed by call, the saved frame pointer, then the function's locals.

Three things share the frame:

  • the return address, pushed by call (the callee did not choose to put it there);
  • the saved caller's rbp, pushed by the callee's first instruction in frame-pointer code;
  • locals and spilled values, found at negative offsets from rbp (or positive offsets from rsp).

Arguments normally arrive in registers (rdi, rsi, rdx, rcx, r8, r9 under System V), so they are not part of the frame unless there are more than six integer arguments or the compiler spills them to memory.

The classic prologue and epilogue

The register rbp is the frame pointer. A function that uses it begins with the same two instructions every time:

NASM
push rbp          ; save the caller's frame pointer
mov  rbp, rsp     ; rbp now marks the base of THIS frame

After these two lines rbp points at the saved value, [rbp + 8] is the return address, and [rbp - 8] is the first free qword below. As long as the function does not touch rbp again, every local has a fixed address relative to it, no matter how much push, pop or sub rsp happens later. That is the whole point: rsp moves, rbp stays put.

If the function needs room for locals it then reserves it by moving the stack pointer down:

NASM
sub  rsp, 16      ; reserve 16 bytes for locals

The matching epilogue undoes things in reverse order and returns:

NASM
mov  rsp, rbp     ; throw away the locals
pop  rbp          ; restore the caller's frame pointer
ret               ; pop the return address into rip

The first two instructions have a one-instruction shortcut, leave, which does exactly mov rsp, rbp followed by pop rbp. You will see both spellings. When there was no sub rsp, a plain pop rbp is enough because rsp already points at the saved value.

On entry to a function rsp is always 8 modulo 16 (the return address just pushed 8 bytes onto a 16-byte aligned stack). push rbp makes it a multiple of 16 again, so a sub rsp, N with N a multiple of 16 keeps the stack aligned for the next call. That is why you see sizes like 16, 32 and 48 in compiler output.

A real function at -O0

Here is a small C function, with the kind of assembly GCC writes at -O0 (no optimization, Intel syntax). Exact offsets vary between compiler versions, so read it as a typical shape and not as a guarantee.

C
long square_sum(long a, long b) {
    long x = a * a;
    long y = b * b;
    return x + y;
}
NASM
square_sum:
    push rbp
    mov  rbp, rsp
    mov  QWORD PTR [rbp-24], rdi    ; spill argument a
    mov  QWORD PTR [rbp-32], rsi    ; spill argument b
    mov  rax, QWORD PTR [rbp-24]
    imul rax, rax                   ; a * a
    mov  QWORD PTR [rbp-8], rax     ; x
    mov  rax, QWORD PTR [rbp-32]
    imul rax, rax                   ; b * b
    mov  QWORD PTR [rbp-16], rax    ; y
    mov  rdx, QWORD PTR [rbp-8]
    mov  rax, QWORD PTR [rbp-16]
    add  rax, rdx                   ; x + y, result in rax
    pop  rbp
    ret

Notice what is missing: there is no sub rsp at all. This function calls nobody, so it is a leaf function, and the System V ABI gives leaf functions a red zone: the 128 bytes below rsp are guaranteed not to be touched by signal handlers or the OS, so a leaf may use them without moving rsp. That is why locals sit at rbp-8 and below while rsp stays equal to rbp. A function that makes calls must reserve its space with sub rsp, because the callee's call would otherwise overwrite it. Windows x64 has no red zone, so there every function reserves its locals explicitly.

Also notice how wasteful -O0 is: both arguments are stored to memory and read straight back. The compiler does this so a debugger can always find every variable at a fixed place.

Watching a frame being built

Real memory is hard to look at, so the first demo uses a small interpreter for a toy x86-style CPU. It supports just enough instructions for this lesson (mov, add, sub, imul, push, pop, call, ret, leave) and a brk pseudo-instruction that prints the stack. Memory holds one 8-byte value per address, and the stack top starts at 0x100. A "return address" here is an instruction number in the program, not a real machine address, but everything else works like the real thing, including the way the callee builds its frame.

JS Build and tear down a frame

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Run it and compare the two snapshots. The first shows the frame right after the prologue: the return address on top, then the saved rbp (zero, because the toy main never set one), and 16 bytes reserved but not yet written. rbp and rsp are 16 bytes apart. The second snapshot, taken just before leave, shows both locals filled in at rbp-8 and rbp-16 (0x9 is 3 squared, 0x10 is 4 squared, and the final out: 25 is their sum). After leave and ret the frame is gone: rsp is back at 0x100 and rbp has its old value again. The cells above rsp still hold stale numbers in memory, but nothing treats them as live, which is also why returning a pointer to a local variable is a bug.

Leaf functions and frame-pointer omission

The push rbp / mov rbp, rsp pair costs two instructions and ties up one register. Optimizing compilers therefore often omit the frame pointer: they address locals relative to rsp instead, and rbp becomes a free general-purpose register. GCC and Clang do this by default from -O1 and above on x86-64 Linux (the flag is -fomit-frame-pointer, and -fno-omit-frame-pointer brings it back). The same function at -O2:

NASM
square_sum:
    imul rdi, rdi          ; a * a
    imul rsi, rsi          ; b * b
    lea  rax, [rdi+rsi]    ; sum, result in rax
    ret

There is no frame at all: no locals in memory, no saved registers, no prologue. Everything stayed in registers. The compiler tracks rsp changes itself and records them in unwind tables (the .eh_frame section), so debuggers and C++ exceptions can still walk the stack without a frame pointer. Some projects build with -fno-omit-frame-pointer anyway, because walking a chain of rbp values is fast and simple, which makes sampling profilers cheap.

A function that does call others, but keeps no frame pointer, still reserves its space with sub rsp and releases it with add rsp before ret:

NASM
    sub  rsp, 24           ; locals (keeps rsp 16-byte aligned for the call below)
    ...
    call other
    ...
    add  rsp, 24
    ret

Here locals are addressed as [rsp + 8], [rsp + 16] and so on. The offsets are relative to a register that moves, so the compiler must adjust them by hand if it ever pushes something. You will also see callee-saved registers pushed in the prologue (push rbx, push r12) and popped in reverse order in the epilogue, as Calling Conventions required.

Walking the frame chain

Because every frame stores the previous rbp right next to the return address, the frames form a linked list:

flowchart LR
  G["g: rbp"] -->|"[rbp] = saved rbp"| F["f: rbp"]
  F -->|"[rbp] = saved rbp"| M["main: rbp"]
  M -->|"[rbp] = 0"| END["end of chain"]

Each frame's first cell holds the base pointer of its caller's frame; the cell just above it holds the address to return to.

To print a backtrace, a debugger starts at the current rbp, reads [rbp + 8] to learn which function the current one will return into, then follows [rbp] to the next frame, and repeats. The next demo does exactly that, using the same toy CPU with three functions, main, f and g, and a brk instruction placed inside g.

JS Walk the rbp chain like a debugger

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The backtrace prints three frames, innermost first, at 0xc8, 0xe8 and 0xf8. Each gap is the caller's locals plus 16 bytes for the return address and saved rbp: f reserved 16 bytes of locals, so g's frame is 0x20 below it, while main reserved none, so f's frame is only 0x10 below main's. The program also prints out: 41: g squares 6 and returns 36, f adds the 5 it had stored in its local, and 36 + 5 is 41. Without that saved local in f's frame, the original argument would have been lost: rdi was overwritten by the call, which is exactly why locals live in the frame and not in caller-saved registers.

Reading a real frame in a debugger

You cannot run native code on this site, but on your own machine a debugger shows the same structure. With GDB, after stopping at a breakpoint inside a function, these commands are useful (lines starting with # are comments, not input):

TEXT
(gdb) info frame               # rbp, rsp, saved rip and where the frame starts
(gdb) bt                       # backtrace: the chain of frames
(gdb) x/6gx $rsp               # examine six 8-byte values (g = giant, x = hex) from rsp
(gdb) p $rbp                   # print the frame pointer
(gdb) frame 1                  # switch to the caller's frame
(gdb) info locals              # variables of the selected frame (needs -g)

If you compile with gcc -O0 -g -fno-omit-frame-pointer, x/2gx $rbp shows the saved rbp followed by the return address, just as in the toy. At -O2 the layout depends on the compiler: locals may live in registers, rbp may hold ordinary data, and GDB then relies on the unwind tables instead. Do not be surprised if values in optimized code do not match the source line you expect; Debugging at the Instruction Level covers that.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do the first two instructions push rbp and mov rbp, rsp accomplish?

    push rbp preserves the caller's frame pointer, and mov rbp, rsp makes rbp point at that saved value, so locals and the return address have fixed offsets from rbp. The return address was already pushed by call, and sub rsp reserves local space.
  2. 2. At which address is the return address, relative to rbp, in a frame built by the classic prologue?

    [rbp] holds the saved caller rbp (pushed by the prologue), and the return address pushed by call sits just above it at rbp + 8.
  3. 3. Why can a leaf function at -O0 store locals below rsp without a sub rsp instruction?

    System V x86-64 defines a red zone of 128 bytes below rsp that signal handlers must not clobber. A function that makes no calls can use it freely. Windows x64 has no red zone.
  4. 4. What does frame-pointer omission (-fomit-frame-pointer) change?

    The compiler skips push rbp / mov rbp, rsp and tracks rsp offsets itself. Backtraces still work through unwind tables (.eh_frame), and the return address is still pushed by call.
  5. 5. What does leave do?

    leave is the shortcut for the first two instructions of the epilogue: it discards the locals by restoring rsp from rbp, then restores the caller's rbp. A separate ret then returns.

Summary

  • A stack frame is the slice of stack owned by one call: return address, saved rbp, locals and saved registers.
  • The classic prologue is push rbp / mov rbp, rsp / sub rsp, N; the epilogue is leave (or mov rsp, rbp / pop rbp) followed by ret.
  • With the frame pointer in place, [rbp + 8] is the return address and locals sit at [rbp - 8], [rbp - 16] and so on.
  • Keep rsp 16-byte aligned at every call; frame sizes are multiples of 16 for that reason.
  • Leaf functions may use the 128-byte red zone (System V only) and often need no sub rsp.
  • Optimized code usually omits the frame pointer, addressing locals through rsp and relying on unwind tables for backtraces.
  • A debugger walks the saved-rbp chain, reading each frame's return address, to print a backtrace.

Next: Arrays and Addressing Modes, where [base + index*scale + displacement] makes memory walking cheap.