Little known GDB feature
Thomas Ptacek | April 21st, 2005 | Filed Under: Uncategorized
I’m continually surprised by the fact that people I talk to don’t know about this:
The GDB debugger offers a command called “commands”. “commands” sets up a list of other GDB commands to run when the last set breakpoint is hit. Apparently this is an obscure feature, but it’s also very powerful.
Three examples of cool tricks you can do with “commands”:
Break on “foo()” only after “bar()” is called:
(gdb) echo set second breakpoint, disable it (gdb) b foo (gdb) dis 1 (gdb) echo set also disable it each time it's hit (gdb) commands > dis 1 > end (gdb) echo set first breakpoint, tell it to set second break (gdb) echo and then continue (gdb) b bar (gdb) commands > en 1 > c > endBreak on “foo()” only after the 1345th iteration of a loop in “bar()”:
(gdb) b bar.c:100 (gdb) commands > if i != 1345 > c > end > b foo > endEach time “foo()” is called, print the value of its “x” variable (run gdb in script(1) for maximal value):
(gdb) b foo (gdb) commands > print x > c > end
Some of this you can accomplish with conditional breakpoints. I’ve never figured out how to use them. I have a possibly irrational belief that GDB watchpoints are too slow to use. So this might be a gross misuse of GDB. But in actual debugging sessions, it’s like magic; for example:
Trip an assertion (or a segfault)
Jump up the stack until you find a loop
Find the value of the iteration variable (or the link “next” pointer, or whatever).
Set a breakpoint in that loop, use “commands” to break when the value of the iterator is the one that preceded the assertion.
Single step until the assertion trips.

