Under the source

The CPU does not run C. Each line was turned into a few instructions. disassemble shows them; => marks the next one.

Instructions, registers and the return address

Level 13 of 13 · interactive GDB exercise · runs in your browser

Start this exercise

What you will learn

Step one machine instruction at a time, read CPU registers, and find a function's return value and return address at the machine level.

stepi runs exactly one instruction. info registers shows the CPU's registers. A single one is written with a dollar sign: print $eax.

This is a 32-bit x86 machine: a function leaves its result in eax, and ret jumps to the address on top of the stack (esp).

The exercise

Step through add one instruction at a time until ret is next, then look at what it leaves behind.

You work in a real GDB session on the program below. A breakpoint on add was set and the program was started; it is paused at the first line of add.

#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int main(void) {
    int sum = add(2, 3);
    printf("sum = %d\n", sum);
    return 0;
}

main.c, compiled with gcc -g -O0 -std=c11 -Wall -fno-omit-frame-pointer -fno-stack-protector -no-pie -fno-pie for 32-bit x86 Linux.

GDB commands you will use

disassemble
Show the machine instructions of the current function. => marks the next one.
stepi
Run exactly one machine instruction (si). nexti (ni) does the same but steps over calls.
(Enter)
An empty line repeats the last command. Handy after next, step or stepi.
x/i $pc
Show the instruction about to run. x/5i $pc shows the next five.
info registers
Show CPU registers (i386 names: eax, esp, ebp, eip ...).
print $eax
Registers are written with a dollar sign: $eax, $esp, $ebp, $pc. print/x shows hex.
x/a $esp
Show the word on top of the stack as an address, with the symbol it belongs to.
info frame
Describe the selected stack frame (addresses are target specific).
break *<addr>
Breakpoint on an exact instruction address, e.g. break *0x8049176.

Common mistakes

Try it in your browser