callandretaren’t “entering a function”—they’re a control transfer that pushes and pops a return address on the stack.
In lesson 09, we moved the stack pointer by hand. Functions do the same thing by protocol: call pushes the address of the next instruction onto the stack, the prologue builds a frame, and ret pops that address back off. In this lesson, I dissect a recursive call, the rbp frame, the registers a function is required to preserve, and tail recursion that never grows the stack.
Mental Model: A Frame Instead of Names
| What it looks like in C99 | What happens in hardware |
|---|---|
| The stack holds local variable names | The frame holds numbers and addresses; names exist only in debug info |
| A recursive call always grows the stack | A tail call can be replaced by a jump, leaving $rsp unchanged |
call f is the same as jmp f |
call also pushes the return address, and ret pops it back |
| Returning from a function is compiler magic | ret pops an address off the stack and jumps to it |
rbp is just cosmetic |
The rbp chain defines frame boundaries for debuggers and unwinders |
call, ret, and the Return Address
The sum_range.asm testbed computes 1 + 2 + ... + n recursively:
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; sum_range.asm — recursive sum 1..n with a full rbp frame.
; The frame_probe label lets GDB inspect the saved frame pointer,
; return address, and argument — with no variable names in sight.
default rel
%define SYS_EXIT 60
%define SUM_ARG 5
section .text
global _start
; ------------------------------------------------------------------------------
; int64_t asm_sum_range(int64_t n)
; Input: rdi = n
; Output: rax = 1 + 2 + ... + n, or 0 if n <= 0
; Clobbers: rdi, rax, flags (caller-saved)
; Preserves: rbp (callee-saved; push rbp in prologue, leave in epilogue)
; ------------------------------------------------------------------------------
asm_sum_range:
push rbp
mov rbp, rsp
sub rsp, 16
mov qword [rbp - 8], rdi
frame_probe:
test rdi, rdi
jle .zero
dec rdi
call asm_sum_range
add rax, qword [rbp - 8]
jmp .done
.zero:
xor eax, eax
.done:
leave
ret
_start:
mov rdi, SUM_ARG
call asm_sum_range
mov edi, eax
; syscall: exit(asm_sum_range(SUM_ARG))
mov eax, SYS_EXIT
syscall
section .note.GNU-stack noalloc noexec nowrite progbitsThe call from _start takes five bytes: opcode e8 and a 32-bit relative displacement to the target.
401023: bf 05 00 00 00 mov edi,0x5
401028: e8 d3 ff ff ff call 401000 <asm_sum_range>
40102d: 89 c7 mov edi,eaxbf 05 00 00 00—mov edi, 5: theSUM_ARGargument.e8 d3 ff ff ff—callwithrel32; displacementd3 ff ff ffdecodes as-45(-0x2d).89 c7— the next instruction,mov edi, eax; its address is the return address.
The displacement is measured from the end of call, not its start:
The five-byte call instruction pushes the return address onto the stack. Recursion uses the exact same mechanism: every call pushes its own return address.
The Stack Frame
A function’s Prologue subtracts space for locals from $rsp, while rbp anchors the base of the frame. That stack frame is built with four instructions:
push rbpsaves the caller’s frame pointer;mov rbp, rspsets the new frame pointer;sub rsp, 16reserves local slots;leavein the epilogue restoresrspandrbpto the caller’s values.
In GDB at frame_probe, two adjacent invocations are visible side by side:
Breakpoint 1, frame_probe () at sum_range.asm:29
29 test rdi, rdi
rbp=0x7fffffffd800 rsp=0x7fffffffd7f0
0x7fffffffd7f8: 0x0000000000000005 0x0000000000000000
0x7fffffffd808: 0x000000000040102d
Breakpoint 1, frame_probe () at sum_range.asm:29
29 test rdi, rdi
rbp=0x7fffffffd7e0 rsp=0x7fffffffd7d0
0x7fffffffd7d8: 0x0000000000000004 0x00007fffffffd800
0x7fffffffd7e8: 0x0000000000401019- At
rbp - 8sits the argument:5at depth 1 and4at depth 2. - At
rbpsits the caller’s savedrbp:0at depth 1, because_startnever built a frame. - At
rbp + 8sits the return address:0x40102dback in_start, and0x401019insideasm_sum_range.
Adjacent frames are spaced exactly 32 bytes apart:
Those 32 bytes break down into three parts:
- saved
rbp— 8 bytes; - return address — 8 bytes;
- local slot — 16 bytes.
Why reserve 16 bytes instead of 8 for a single 8-byte slot [rbp - 8]? To preserve 16-byte alignment on rsp before the recursive call (we’ll examine this ABI rule in detail in lesson 18).
Recursion via call (asm_sum_range) Tail jmp (asm_sum_down)
┌─────────────────────────┐ 0x...d808 ┌─────────────────────────┐
│ ret addr -> _start │ │ ret addr -> _start │ ◄─ $rsp
├─────────────────────────┤ 0x...d800 └─────────────────────────┘ never grows
│ saved rbp (= 0) │ ◄──┐ all 5 iterations reuse
├─────────────────────────┤ │ the exact same return slot
│ slot n=5 + alignment │ │
├─────────────────────────┤ │
│ ret addr -> asm_sum_rng │ │
├─────────────────────────┤ 0x...d7e0
│ saved rbp ──────────────┼────┘
├─────────────────────────┤
│ slot n=4 + alignment │ ◄── $rsp
└─────────────────────────┘There are no variable names on the stack: at the exact same checkpoint, info locals replies No locals. and info args replies No symbol table info available.
Registers: Who Preserves What
The calling convention splits general-purpose registers into two groups: caller-saved registers and callee-saved registers.
| Group | Registers | Who is responsible for saving |
|---|---|---|
| caller-saved | rax, rcx, rdx, rsi, rdi, r8–r11 |
the caller, if needed after call |
| callee-saved | rbx, rbp, r12–r15 |
the callee, on every exit path |
| stack pointer | rsp |
both sides: by ret, it must point to the return address |
That’s why asm_sum_range opens with push rbp and closes with leave: without them, the caller would lose its frame pointer. Vector registers xmm0–xmm15 are all caller-saved under the System V AMD64 ABI; the full ABI is covered in lesson 18.
leave is shorthand for two instructions:
mov rsp, rbpdiscards local slots and pointsrspback at the savedrbp;pop rbppops the saved value and restores the caller’s frame.
leave leaves other callee-saved registers untouched: if a function saved rbx or r12, it must restore them with explicit pop instructions before ret. In sum_range.asm, leave is followed directly by ret, returning both the stack and control together.
Tail Calls
When a call is the final action of a function, there’s no need to push a new return address: jumping straight back to the start of the function is tail-call optimization.
This is only valid when no work remains after the call: no adding to the return value, no restoring registers, and no frame teardown.
The sum_down.asm testbed implements this with jmp. A single call pushes the return address back to _start, and every subsequent iteration executes jmp to the same label, keeping $rsp constant across iterations.
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; sum_down.asm — tail recursion via jmp: rsp stays constant across iterations.
; The tail_iteration label is inspected by GDB on each pass.
default rel
%define SYS_EXIT 60
%define SUM_ARG 5
section .text
global _start
; ------------------------------------------------------------------------------
; int64_t asm_sum_down(int64_t n, int64_t acc)
; Input: rdi = n, rsi = running accumulator
; Output: rax = acc + 1 + 2 + ... + n, or acc if n <= 0
; Clobbers: rdi, rsi, rax, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_sum_down:
tail_iteration:
test rdi, rdi
jle .done
add rsi, rdi
dec rdi
jmp asm_sum_down
.done:
mov rax, rsi
ret
_start:
mov rdi, SUM_ARG
xor esi, esi
call asm_sum_down
mov edi, eax
; syscall: exit(asm_sum_down(SUM_ARG, 0))
mov eax, SYS_EXIT
syscall
section .note.GNU-stack noalloc noexec nowrite progbitsGDB hits tail_iteration repeatedly, yet $rsp never moves. Here are the first and third stops:
(gdb) break tail_iteration
Breakpoint 1 at 0x401000: file sum_down.asm, line 22.
(gdb) run
Starting program: .../build/sum_down
Breakpoint 1, tail_iteration () at sum_down.asm:22
22 test rdi, rdi
(gdb) set $first = $rsp
(gdb) print/x $rsp
$1 = 0x7fffffffd818
(gdb) continue
Continuing.
Breakpoint 1, tail_iteration () at sum_down.asm:22
22 test rdi, rdi
(gdb) continue
Continuing.
Breakpoint 1, tail_iteration () at sum_down.asm:22
22 test rdi, rdi
(gdb) print/x $rsp
$2 = 0x7fffffffd818
(gdb) print/d $rsp == $first
$3 = 1
(gdb) x/2gx $rsp
0x7fffffffd818: 0x000000000040101d 0x0000000000000001print/d $rsp == $first returns 1: five recursive passes share a single frame. At $rsp still sits the lone return address 0x40101d back to _start, followed by argc.
Compilers fold recursion into a loop automatically—even when an associative accumulation remains after the recursive call (strictly speaking, n + sum_down(n - 1) in tco_demo.c is linear recursion rather than a syntactic tail call, yet the optimizer still turns it into an accumulator loop):
/* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 */
/* tco_demo.c — recursion: -O0 keeps call, -O2 folds it into a loop. */
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
static uint64_t sum_down(uint64_t n)
{
if (n == 0) {
return 0;
}
return n + sum_down(n - 1);
}
int main(void)
{
volatile uint64_t n = 1000000;
uint64_t total = sum_down(n);
printf("sum_down(%" PRIu64 ") = %" PRIu64 "\n", n, total);
return 0;
}In main, n is marked volatile uint64_t so -O2 cannot constant-fold 1000000 into a compile-time literal: the value stays in memory, forcing the loop to actually run.
Without optimization, GCC emits a real call and a 32-byte frame:
"sum_down":
push rbp
mov rbp, rsp
sub rsp, 16
mov QWORD PTR -8[rbp], rdi
cmp QWORD PTR -8[rbp], 0
jne .L2
...
call "sum_down"At -O2, the function disappears: its body is inlined into main and lowered into a loop, with neither call nor jmp to sum_down left in the listing:
sub rsp, 24
...
test rax, rax
je .L3
.L2:
add rdx, rax
sub rax, 1
jne .L2
.L3:The quotes around "sum_down" are how GAS quotes symbol names in Intel syntax. At -O2, the running sum lives in rdx, the counter in rax, and the stack never grows.
Verification in the Terminal
Both testbeds return the sum as their exit status:
$ ./build/sum_range; echo $?
15
$ ./build/sum_down; echo $?
15Running tco_demo with one million steps highlights the difference between stack recursion and a loop:
$ (ulimit -c 0; ./build/tco_demo_O0); echo $?
139
$ ./build/tco_demo_O2
sum_down(1000000) = 500000500000Exit status 139 is 128 + 11, termination by SIGSEGV on stack exhaustion: a million 32-byte frames won’t fit inside 8 MiB. The -O2 build covers the exact same range in a single frame.
Common Pitfalls
-
“Assuming
$rsprestores itself after a recursive call.”
Fact: withoutleaveor a matchingpop, the function returns, but$rspstays shifted and the nextretjumps to garbage.
Cause:callandpushdecrement$rsp; onlyret,pop,leave, or an explicitadd rsp, Nrestores it.
Fix: keep prologue and epilogue symmetric across every exit path and verify$rspin GDB right before eachret. -
“Expecting to find local variable names on the stack.”
Fact: atframe_probe,info localssaysNo locals.andinfo argssaysNo symbol table info available.
Cause: variable names live in DWARF debug metadata, not on the hardware stack; raw assembly files carry no variable symbols at all.
Fix: inspect frame slots by offsets fromrbpand match them against comments in your listing. -
“Tail recursion will blow the stack anyway.”
Fact:tco_demo_O0crashes with139, whiletco_demo_O2prints500000500000.
Cause:tco_demo.cuses ordinary linear recursion (return n + sum_down(n - 1)), yet-O2still turns it into a loop using accumulatorrdx; at-O0, each step emits acalland allocates a new frame until the stack runs out.
Fix: rewrite tail calls asjmpmanually in assembly, or enable optimization and verify in the disassembly that nocallremains.
Lab
Goal. Build frame_walk.asm to compute 1 + 2 + ... + n in two ways—recursive call and tail-call jmp—and demonstrate the difference in stack depth.
Contract and requirements.
- Both functions take
nand return the sum; forn <= 0, return0. - The recursive version must build a full
rbpframe and usecall. - The tail-recursive version must leave
$rspunchanged across iterations. - Define
nas a constant in the source file; exit with the low byte of the sum. - Place debug labels in both functions so GDB can break on entry to each pass.
Verification criteria.
./build/frame_walk; echo $?exits with the expected sum for your chosenn.- In GDB at the recursive label,
$rspdecreases by one frame size at each deeper call. - In GDB at the tail-call label,
$rspis identical on the first and last iteration. objdump -d -M intel build/frame_walkshowscallin the recursive function and none in the tail-call function.gcc -O0 -Sandgcc -O2 -Son an equivalent C99 function produce acallat-O0and a loop at-O2.
Hints, expected output, and walkthrough
For n = 6, the sum is 21, so the exit code is 21. If the recursive version returns something else, check the order of add and dec: accumulate the current value before decrementing the counter.
On this testbed, a recursive frame takes 32 bytes: 8 for saved rbp, 8 for the return address, and 16 for the local slot. Between n = 6 and n = 1, that’s 5 * 32 = 160 bytes; measuring down to the base case n = 0 where recursion stops gives 6 * 32 = 192 bytes.
In the tail-call version, $rsp must match down to the exact byte: any drift means a call or an unmatched push slipped in.
At -O2, GCC may inline the function into main and eliminate its symbol completely. Look for a loop across the whole disassembly rather than under the function name: a jne loop without call confirms the transformation.
Testbed sources, Makefile, and automated tests for this lesson: lessons/10-functions.
Summary
callpushes the next instruction’s address onto the stack;retpops it and transfers control there.- A
push rbp/mov rbp, rsp/sub rsp, Nprologue builds a stack frame, andleavetears it down. rbpholds the saved frame pointer,rbp + 8holds the return address, and negative offsets belowrbphold local slots.- Callee-saved registers
rbx,rbp,r12–r15must be restored along every return path. - A tail call via
jmpleaves$rspuntouched and turns recursion into a loop. gcc -O2performs this transformation automatically, whereas-O0keeps growing the stack untilSIGSEGV.
call and ret hand control back, and the frame disappears. In lesson 11, I move from single stack slots to contiguous data: arrays, arrays of structs, and the addressing formula shared by both mov and lea.