Module 2 · Lesson 3 of 131

gdb: stepping, state and watchpoints

Drive gdb to set breakpoints, step, inspect state, use watchpoints and diagnose crashes from core dumps, and generate correct header dependencies with -MMD -MP.

  • Beginner to advanced
  • 12 min read
  • 24 min lab
What you will need

gcc, make and gdb on Ubuntu 24.04 (WSL2, VM or container); a Raspberry Pi for the remote-debugging section

Your place in the module
By the end you can 3 objectives
  • Generate automatic header dependencies with -MMD -MP and -include, and verify an incremental rebuild skips untouched objects.
  • Drive gdb: set breakpoints, step, inspect memory, registers and backtraces, and read a stack trace.
  • Use watchpoints, conditional breakpoints and state changes, and diagnose a crash from a core dump.
Video coming soongdb: stepping, state and watchpoints
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Make rules, variables and pattern rules
  • Automatic variables $@, $<, $^ and $? plus pattern rules turn a page of repeated rules into a few generic lines.
  • =, :=, ?= and += differ in when expansion happens; CPPFLAGS, CFLAGS and LDFLAGS each carry a different kind of flag.
  • .PHONY marks a target as an action rather than a file, so make runs its recipe every time.
01

gdb essentials: starting, breaking and stepping

3 min read

Your Makefile now rebuilds correctly, but a correct build is not a correct program; when it segfaults you need to watch it run. This lesson answers: how do you drive gdb to find a bug in a running program?

gdb needs one thing from your build: debugging information. The -g flag tells the compiler to embed, in the object file, a description of the source that maps machine code back to files, lines, variables and types. Without it, gdb sees only raw machine code and addresses. Compile with -g and, for clean debugging, -O0 to disable optimization, since an optimizing compiler may reorder code and eliminate variables that you want to inspect.

bash
gcc -g -O0 -Wall -Wextra -o monitor main.c sensor.c
gdb ./monitor

Inside gdb, run (or r) starts the program with no arguments, and run arg1 arg2 passes arguments. start is run with a temporary breakpoint at main, so the program stops at the first line of main immediately, a useful shortcut. A is set with break (or b).

text
(gdb) break sensor_read          # stop at the function entry
(gdb) break sensor.c:42          # stop at a specific line
(gdb) break *main+4              # stop at an address, main plus 4 bytes
(gdb) info breakpoints           # list them, numbered
(gdb) delete 2                   # remove breakpoint 2

A breakpoint can be made conditional, so it stops only when an expression is true, and condition attaches or changes that condition after the fact.

text
(gdb) break sensor.c:42 if reading < 0
(gdb) condition 3 reading < 0   # add a condition to breakpoint 3
(gdb) condition 3               # clear the condition

Once stopped, you move forward with a small set of commands. continue (or c) runs until the next breakpoint, signal or exit. step (or s) runs one source line, stepping into any function call on that line. next (or n) also runs one line but steps over function calls, treating them as a single step. finish runs until the current function returns, and prints the return value, which is the fastest way out of a function you stepped into by accident. until (or u) runs until a source line greater than the current one is reached, useful for exiting a loop without setting a breakpoint; until 99 runs until line 99.

The distinction between step and next is the one beginners mix up most. If the current line calls read_adc(), step stops at the first line inside read_adc, while next runs the whole call and stops at the following line. Use step when you suspect the callee, next when you trust it, and finish to escape when you stepped in by mistake.

The gdb inspect looprunbreakpointstep / nextprint / x/continue↻ Repeat from step 1runbreakpointstep / nextprint / x/continue↻ Repeat from step 1
The core gdb loop: break, run, step or next, inspect, continue
Step by stepWhat a software breakpoint actually does
  1. Insert: gdb writes a trap instruction, on x86-64 the single-byte int3, over the first byte of the target instruction, saving the original byte.

  2. Run: the CPU executes normally until it reaches the overwritten byte.

  3. Trap: the trap instruction raises a SIGTRAP, and the kernel stops the process and notifies gdb.

  4. Report: gdb reports the stop and shows you the source line it mapped from the program counter.

  5. Restore: when you continue, gdb puts the original byte back, single-steps one instruction, and re-inserts the trap.

A breakpoint on a line with no code, or inside code the optimizer moved, will not land where you expect. gdb may report the nearest addressable line instead. This is the first hint that debugging optimized code is harder, a theme the inspection section returns to.

Break, run, step, next and finish on a real crash
Recording coming soon. Follow the commands in this lesson.
02

Automatic dependencies and incremental correctness

3 min read

The Makefile from the last two sections has one weakness: it tracks headers by hand. If sensor.c includes sensor.h and config.h, and the rule lists only sensor.c, then editing config.h changes nothing. make reports 'monitor' is up to date, the binary stays stale, and the bug is invisible. The rule of thumb is that a build that is only correct after make clean has a dependency bug, and make clean before every build is a workaround that masks it.

The compiler knows the real dependency list, and it can write it down. The flags -MMD and -MP make gcc emit, alongside each object, a .d file containing a make rule that lists the object's true prerequisites: its source and every header it included, transitively.

bash
gcc -MMD -MP -c sensor.c   # produces sensor.o and sensor.d

sensor.d contains a line shaped like a make rule, such as sensor.o: sensor.c sensor.h config.h. The -MP flag adds an empty phony target for each header, so deleting a header later does not make make fail on a missing prerequisite. To use the files, the Makefile pulls them in with -include, where the leading dash means ignore the file if it does not exist yet, which is exactly the state on a clean build before any object has been compiled.

makefile
CC      = gcc
CPPFLAGS = -Iinclude
CFLAGS  = -Wall -Wextra -O2 -g -MMD -MP
OBJS    = main.o sensor.o stats.o

monitor: $(OBJS)
    $(CC) -o $@ $^ $(LDFLAGS) $(LDLIBS)

%.o: %.c
    $(CC) $(CPPFLAGS) $(CFLAGS) -c $<

-include $(OBJS:.o=.d)

.PHONY: clean
clean:
    rm -f monitor $(OBJS) $(OBJS:.o=.d)

The expression $(OBJS:.o=.d) rewrites main.o sensor.o stats.o into main.d sensor.d stats.d, and -include reads them all. Now an edit to any header that sensor.c includes, however indirect, appears in sensor.d, and make rebuilds sensor.o and relinks. The hand-maintained header lists are gone, and the dependency graph is generated by the one tool that actually knows it.

-MMD deliberately omits system headers, the ones in /usr/include and your -I paths do not count as system headers, so your own headers are tracked, while the compiler's own headers are not. This is what you want: you do not want to rebuild every object because a system header was touched. The related -MD includes system headers too, which is almost never desirable for application builds and produces enormous dependency files.

Incremental correctness is what makes -j safe. A parallel build can only schedule recipes whose prerequisites are complete, and with the .d files in place, make knows the true prerequisites of every object, so make -j8 neither races nor links prematurely. The performance win is real: on a project with dozens of files, -j8 can turn a minute-long build into a few seconds, but only after the graph is correct. Turn the parallelism up only after the dependency tracking is in place, not before.

Header dependency graphmonitorsensor.osensor.csensor.hconfig.hmain.omain.cconfig.hmonitorsensor.osensor.csensor.hconfig.hmain.omain.cconfig.h
With -MMD, each .d file records the source and every header, so make rebuilds on any header edit
Going deeperHow the .d files are generated on the same pass

-MMD does not run the compiler twice. It tells the preprocessor, which already reads every header to expand includes, to note each one it opens and write the resulting rule to the .d file at the same time it produces the object. The cost is negligible because the preprocessor walks those files anyway. The -MM variant prints the same rule to standard output instead of a file, useful for inspecting what would be tracked, and -M does the same including system headers. For a named output file there is also -MF to choose the .d path and -MT to override the target the rule names, both needed only in unusual layouts.

Prove an incremental rebuild skips the untouched object
Recording coming soon. Follow the commands in this lesson.
03

Inspecting state and reading backtraces

4 min read

Stopping is only useful if you can read what is frozen. gdb offers a hierarchy of inspection, from a named variable to raw bytes to the call stack itself.

print (or p) evaluates an expression in the stopped program's context and prints its value. It understands C expressions, structure members, pointer dereferences and arrays, and takes a format prefix to control the representation.

text
(gdb) print reading            # the value of reading
(gdb) print/x reading          # hexadecimal
(gdb) print sensor->state      # a structure member
(gdb) print arr[0]@5           # the first five elements of arr
(gdb) print ptr                # prints the address in ptr

42 decimal is 0x2a in hex, 0o52 in octal and 0b101010 in binary; this is exactly what print/x shows for a value of 42.

  • value: 42
  • width: 32

display is print that repeats: the expression is evaluated and shown every time the program stops, until you remove it with undisplay. It is the right tool for watching a value change as you step through a loop.

Raw memory inspection is x/, the examine command, with a format, size and count: x/nfu address. n is the number of units, f the format (x hex, d decimal, s string, i instruction), and u the unit size (b byte, h halfword, w word, g giant word). It is how you look at memory that has no variable name, or verify what a pointer really points at.

text
(gdb) x/4bx &reading        # four bytes, hex, at the address of reading
(gdb) x/2gx $rsp            # two 8-byte words at the top of the stack
(gdb) x/s ptr               # the string at ptr, up to the null byte
(gdb) x/8i $pc              # eight instructions starting at the program counter

Register state comes from info registers (or i r), which prints the general-purpose registers, and info registers rax for one. info locals lists the local variables of the current function, and info args its arguments. A lets you save a value for later. Every print result is automatically stored as $1, $2 and so on, and you can assign your own with set $count = reading.

text
(gdb) print reading
$1 = 42
(gdb) set $start = $1       # save it under a readable name
(gdb) print $start * 2
$2 = 84

A , printed with bt, is how you answer the question "how did we get here". Each line is a frame, numbered from zero at the innermost.

text
(gdb) bt
#0  read_adc () at sensor.c:19
#1  0x00005555555551e9 in sensor_read () at sensor.c:31
#2  0x0000555555555254 in main () at main.c:14

This is typical output, and the addresses will differ on your machine. bt full adds the local variables of every frame. frame 2 selects frame two, up and down move between frames, and info frame describes the current frame in detail, including the saved instruction pointer and the frame pointer. When you select an outer frame, print and info locals evaluate in that frame's context, so you can read main's variables while stopped inside read_adc.

Reading the stack itself is how you understand frames from first principles. On x86-64, each call pushes a return address and, if frame pointers are enabled, the old base pointer, and the frame pointer register (rbp) chains the frames together. info registers rbp rsp shows the current base and stack pointers, and x/4gx $rbp dumps the frame. On ARM the same role belongs to the frame pointer register r11, or x29 in the 64-bit ABI.

The call stackhighmain framesaved rbp, return addrsensor_read framelocals, return addrlowread_adc framersp points herehighmain framesaved rbp, return addrsensor_read framelocals, return addrlowread_adc framersp points here
The stack growing downward, with each frame holding a saved base pointer, locals and a return address
Going deeperOptimized code and frame pointers

At -O2 on x86-64, gcc omits the frame pointer and uses rbp as an ordinary register, because a frame pointer costs a register and instructions. gdb still produces a correct backtrace, because the compiler emits unwind information in a DWARF section (.eh_frame and .debug_frame) that tells gdb how to recover the stack layout at every instruction. On ARM and in kernels that need reliable backtraces, -fno-omit-frame-pointer keeps the frame pointer. The practical lesson: you do not need to read raw frames to use bt, but you do need -g, and under optimization some variables are held in registers or eliminated, so print can report <optimized out>. Recompile that one file at -O0 -g when a variable you need disappears.

04

Watchpoints, altering state, core files and threads

5 min read

Sometimes you know what is wrong but not who changes it. A answers "who wrote to this variable". Set one with watch, and add rwatch for a read-only watch and awatch for either access. Conditions attach the same way as breakpoints.

text
(gdb) watch reading            # stop when reading changes
(gdb) watch reading if reading > 100
(gdb) rwatch samples_taken     # stop when it is read

Watchpoints come in two very different kinds, and gdb reports which it installed. A hardware watchpoint uses the CPU's debug registers, four address registers on x86-64, so up to four are available at once, and it stops on the exact instruction that changes the value. gdb prints Hardware watchpoint 1: reading. If those registers are exhausted, or the target has none, gdb falls back to a software watchpoint, which single-steps the program and compares the value after every instruction, hundreds of times slower, and it reports the change at the next source line rather than the exact instruction. set can-use-hw-watchpoints 0 forces the software kind, which is how you tell which you have. In a multi-threaded program, hardware watchpoints watch the expression in every thread, while software watchpoints are effectively limited to the current thread, so on threaded code the hardware kind is essential.

Conditional breakpoints deserve one caution: gdb evaluates the condition by stopping at the breakpoint, testing the expression, and continuing invisibly if it is false. In a hot loop this makes the program crawl, and the hardware-assisted equivalent, if you only need a value to change, is often a watchpoint instead.

gdb can change the program while it runs. set var x = 5 assigns a new value, spelled set var to distinguish it from gdb's own set settings, and print x = 5 does the same because an assignment is also an expression. call func(args) invokes a function in the inferior and prints its result, letting you test a helper or force a code path without restarting. return expr makes the current function return immediately with a given value, and jump line resumes execution at a chosen line, both of which are for experiments, since they can corrupt state if misused.

A captures a crash for later. It is produced only if the shell's core limit allows it, raised with ulimit -c unlimited, and its name and location come from /proc/sys/kernel/core_pattern.

bash
ulimit -c unlimited
./monitor                 # segfaults, writes a core file
gdb ./monitor core        # inspect the crash

The first thing to do inside gdb is bt, which shows the exact call stack at the moment of the fault, then frame 0, info locals and print to read the values. On many systems the core is not a plain file: core_pattern may be a pipe into a handler such as systemd-coredump, and on Ubuntu 24.04 the cores are collected with coredumpctl rather than left in the working directory. cat /proc/sys/kernel/core_pattern shows which arrangement your system uses, and a value beginning with | means a handler program is receiving the dump. On an embedded board with no room for a core file, you instead rely on gdbserver and remote debugging, the subject of the next section, to catch the crash live.

Threads turn a single backtrace into many. info threads lists every thread with an id, and thread N switches the context of all the inspection commands to thread N. thread apply all bt prints a backtrace for every thread at once, the single most useful command when a multithreaded program is stuck or crashed, because it shows what every thread was doing. thread apply 2-3 bt restricts it to a range. A related setting, set scheduler-locking step, keeps the other threads stopped while you single-step, so a step does not get lost when the scheduler runs another thread in between.

Analysing a core dumpProgramKernelCore handlergdbfault(SIGSEGV)dump memory(core_pattern)gdb binarycorebt, frame,print1. Program → Kernelfault (SIGSEGV)2. Kernel → Core handlerdump memory (core_pattern)3. gdb → Core handlergdb binary core4. Core handler → gdbbt, frame, print
A crash writes a core file, and gdb plus the binary reconstructs the call stack and variable values
Hardware watchpoints are finite

On x86-64 only four hardware watchpoints exist, and each can watch at most eight bytes. A fifth watch silently becomes a software watchpoint, slowing the program by orders of magnitude and changing the stop precision. When gdb prints a watchpoint without the word hardware, you are in the slow path, and the fix is to free one of the four or watch a smaller region.

Key takeaways

  • A Makefile that ignores headers goes silently stale; -MMD -MP with -include records the true dependency set.
  • gdb maps machine state back to source through DWARF; break, print, x/, bt and frame are the core loop.
  • Hardware watchpoints run in CPU debug registers and stop on the exact instruction; software watchpoints single-step and are far slower.
  • A core file plus the matching binary reconstructs the crash without a live debugger.
Reflect
  1. Explain to a colleague, in two sentences: generate automatic header dependencies with -MMD -MP and -include, and verify an incremental rebuild skips untouched objects.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close