Stack Frames and the Return Address
When main calls greet, the CPU must remember where to continue after greet finishes. On x86-64 the call instruction pushes that return address onto the stack, and ret pops it back into the instruction pointer. Between the two, greet keeps its local variables on the same stack, a few bytes below the return address. That closeness is the root of the most famous bug class in security: a local array that overflows towards higher addresses runs into the saved data that controls where the program goes next. Reading machine code and calling conventions in depth is part of Reverse Engineering & Binary Analysis; this lesson takes only what memory safety needs.
Definitions
- Stack frame: the part of the stack that belongs to one active function call: its locals, saved registers, and the return address pushed by its caller.
rsp(stack pointer): the lowest address in use. The stack grows down: pushing decreasesrsp.rbp(frame pointer): at-O0, a fixed reference inside the frame; locals are atrbp - n, the saved caller'srbpatrbp, the return address atrbp + 8.- Prologue / epilogue: the instructions at the start (
push rbp; mov rbp, rsp; sub rsp, N) and end (leave; ret) of a function that build and tear down its frame. - Stack canary: a secret 8-byte value the compiler stores between the locals and the saved registers, checked before
ret(-fstack-protector-strong, on by default on Ubuntu).
The frame of a real function
The sandbox session compiles a small function with a 16-byte buffer, stops it with gdb after the copy, and measures the frame: how far the buffer is below rbp, the low byte of the canary, and what the saved return address points to. Measuring differences keeps the output the same on every run despite ASLR. It runs in your sandbox:
cat > frame.c <<'SRC'
#include <stdio.h>
#include <string.h>
void greet(const char *name) {
char buf[16];
strcpy(buf, name);
printf("hi %s\n", buf);
}
int main(void) {
greet("lab");
return 0;
}
SRC
gcc -g -O0 frame.c -o frame
gdb -q -batch -ex 'break 7' -ex run -ex bt \
-ex 'p (char *)$rbp - (char *)&buf' \
-ex 'p (char *)$rbp - (char *)&name' \
-ex 'p/x *(unsigned long *)($rbp - 8) & 0xff' \
-ex 'info symbol *(void **)($rbp + 8)' \
-ex 'x/s buf' ./frame 2>&1 | grep -v '^\[Thread\|^Using host'
echo "== greet's prologue and epilogue"
objdump -d --no-show-raw-insn -M intel frame | awk '/<greet>:/,/ret/' | sed 's/^ *[0-9a-f]*:\t//' | sed -n '1,8p;21,$p'Breakpoint 1 at 0x11bb: file frame.c, line 7.
Breakpoint 1, greet (name=0x61c6cec8000b "lab") at frame.c:7
7 printf("hi %s\n", buf);
#0 greet (name=0x61c6cec8000b "lab") at frame.c:7
#1 0x000061c6cec7f204 in main () at frame.c:11
$1 = 32
$2 = 40
$3 = 0x0
main + 23 in section .text of /home/learner/frame
0x7ffef99fca30: "lab"
== greet's prologue and epilogue
0000000000001189 <greet>:
endbr64
push rbp
mov rbp,rsp
sub rsp,0x30
mov QWORD PTR [rbp-0x28],rdi
mov rax,QWORD PTR fs:0x28
mov QWORD PTR [rbp-0x8],rax
nop
mov rax,QWORD PTR [rbp-0x8]
sub rax,QWORD PTR fs:0x28
je 11eb <greet+0x62>
call 1080 <__stack_chk_fail@plt>
leave
ret
What the numbers say:
bufstarts 32 bytes belowrbp(lea rax,[rbp-0x20]in the code passes that address tostrcpy), and the pointer argumentnamewas saved atrbp - 40([rbp-0x28]).- The canary is at
rbp - 8: the prologue copies it fromfs:0x28(a slot in the thread control block holding a random value chosen at program start, the same for every thread of the process) and the epilogue compares it again and calls__stack_chk_failif it changed. Its lowest byte is0x0on purpose: a NUL byte stops string copies from reproducing it. - The saved return address at
rbp + 8points tomain + 23, the instruction right after thecall greet.btshows the same place as frame#1.
So, from the first byte of buf upwards: 16 bytes of buffer, 8 bytes of padding (alignment), 8 bytes of canary, 8 bytes of saved rbp, 8 bytes of return address. 48 bytes in all.
A model of the frame in Python
To study what an overflow does without running anything dangerous, the course uses a model: the 48 bytes of this frame as a Python bytearray, with the same offsets gdb measured. The saved rbp and return address are the labelled placeholders FRAMEPTR and RET>main, not real addresses, and the canary is a fixed value (a real one is random per process). An unchecked_copy behaves like strcpy: it writes the string and its NUL from offset 0 with no bound. It runs in your browser:
FIELDS = [("buf[16]", 0, 16), ("padding", 16, 8), ("canary", 24, 8),
("saved rbp", 32, 8), ("return address", 40, 8)]
CANARY = bytes.fromhex("005a3c91e27f4b18") # fixed for the lesson; real canaries are secret, set per process
def new_frame():
return bytearray(bytes(24) + CANARY + b"FRAMEPTR" + b"RET>main")
def unchecked_copy(frame, s):
data = s + b"\0" # like strcpy: no length check
frame[0:len(data)] = data[:len(frame)] # (the model stops at the end of the frame)
def show(frame):
ref = new_frame()
for name, off, size in FIELDS:
now = bytes(frame[off:off + size])
state = "" if name == "buf[16]" else ("intact" if now == ref[off:off + size] else "OVERWRITTEN")
print(f"{off:2}-{off + size - 1:<2} {name:15} {now.hex(' ')} {state}")
f = new_frame()
unchecked_copy(f, b"lab")
show(f)
print()
for n in (15, 16, 17, 24, 25, 32, 40):
f = new_frame()
unchecked_copy(f, b"A" * n)
hit = [name for name, off, size in FIELDS[1:] if f[off:off + size] != new_frame()[off:off + size]]
print(f"{n:2} chars + NUL -> {', '.join(hit) or 'nothing outside buf'}") 0-15 buf[16] 6c 61 62 00 00 00 00 00 00 00 00 00 00 00 00 00
16-23 padding 00 00 00 00 00 00 00 00 intact
24-31 canary 00 5a 3c 91 e2 7f 4b 18 intact
32-39 saved rbp 46 52 41 4d 45 50 54 52 intact
40-47 return address 52 45 54 3e 6d 61 69 6e intact
15 chars + NUL -> nothing outside buf
16 chars + NUL -> nothing outside buf
17 chars + NUL -> padding
24 chars + NUL -> padding
25 chars + NUL -> padding, canary
32 chars + NUL -> padding, canary, saved rbp
40 chars + NUL -> padding, canary, saved rbp, return address
With "lab" only the first four bytes of buf change (6c 61 62 00). The sweep shows the boundaries, and two surprises. Fifteen characters plus the NUL fill buf exactly. Sixteen characters are already an overflow (the NUL lands at offset 16), yet nothing visibly changes, because the padding byte was already zero: a silent bug that only a sanitizer sees. Seventeen change the padding. Twenty-four put the NUL onto the canary's first byte, which is zero by design, so the canary still looks intact; twenty-five change it. Thirty-two reach the saved frame pointer and forty the return address. A real strcpy does exactly what the model does, which is why the next lessons treat every unbounded copy into a stack array as a potential overwrite of the return address.
The same frame as an animation: the lab writes len bytes of 'A' upwards from buf[0] (like read(fd, buf, len) with a wrong length, so there is no NUL) and then runs the epilogue. Its frame has no padding, so N = 24 stands for the 16-byte buf plus its 8 bytes of padding and gives the offsets gdb measured: canary 24–31, saved rbp 32–39, return address 40–47. With 48 bytes written all three are overwritten, and the canary check aborts before leave. Switch the canary off and the same write reaches the return address with nothing to stop it.
How frame corruption is detected
- Before shipping: ASan reports a
stack-buffer-overflowat the first byte pastbuf(offset 16 here), long before the canary is reached. - At run time: the canary check in the epilogue prints
*** stack smashing detected ***and aborts if the canary changed. Shadow stacks (Intel CET) compare the return address with a protected copy. - After a crash: a core dump whose backtrace is garbage (
#1 0x4141414141414141 in ?? ()) is a sign the saved data was overwritten.
How it is prevented
Bound every write into a local array (Safe C Patterns), keep the default -fstack-protector-strong, and prefer containers that know their size. The mitigations that protect the return address are compared in Stack Canaries, NX and Why ROP Exists.
Pitfalls
- Offsets are compiler choices. Another compiler, flag or optimisation level reorders locals and padding; at
-O2there may be no frame pointer at all. Always measure, never assume. - The canary protects only the return path. Locals between the buffer and the canary (another array, a function pointer) are overwritten before the canary is; GCC places arrays above scalar locals partly for this reason.
- Arguments in registers. On x86-64 the first six integer arguments arrive in registers (
rdi,rsi, …); at-O0they are copied into the frame (herenameatrbp - 40).
Practice
1. What is the longest string that leaves the canary unchanged, and why is it longer than you might expect?
24 characters. Its NUL lands on offset 24, the canary's first byte, which is already 0. A 25-character string changes the canary and the epilogue check fails. The string is still 9 bytes too long for buf: the overflow happened, the canary just can't see it.
2. Why does the canary's first byte being 0 help?
String functions stop at NUL. An overflow done with strcpy can't write a correct copy of the canary followed by more bytes, because writing the 0 ends the copy.
3. In the model, what does show print for the canary after copying 30 characters?
OVERWRITTEN: bytes 24 to 29 become 41 and byte 30 the NUL.
Test yourself
Which instruction pushes the return address?
- push rbp
- call
- ret
- leave
In the measured frame, at which offset from the start of buf does the return address begin?
- 16
- 24
- 32
- 40
Where does the canary's value come from in the code gdb showed?
- A constant in .rodata
- fs:0x28, the thread control block's copy of a random value chosen at start-up
- The return address
- The user's input
Why does the stack-frame model use placeholders like RET>main instead of real addresses?
- Python can't store numbers
- The point is which bytes an overflow overwrites, not working addresses; real ones change with ASLR anyway
- gdb hides them
- For speed
In the stack-frame lab (N = 24, 48 bytes written), you switch the canary off. What happens?
- The function returns normally
- Only the saved rbp changes
- The saved rbp and the return address are overwritten and nothing detects it: the return is hijacked
- ASan aborts at the first byte past buf