We typically use GDB in interactive mode, manually entering various GDB commands. However, GDB also supports executing pre-written debugging scripts for automated debugging. A debugging script consists of a series of GDB commands, which GDB executes sequentially.
When writing debugging scripts, handling breakpoints correctly is essential. In interactive mode, when a program reaches a breakpoint, GDB waits for the user to input the next command. To define operations that occur automatically when a breakpoint is triggered, a mechanism similar to a callback function is required.
GDB uses the Breakpoint Command Lists mechanism to achieve this. Users can define a series of commands, known as a command-list, to be executed whenever the program stops at a specific breakpoint (or watchpoint, catchpoint). The syntax is as follows:
commands [list…]
… command-list …
endFor example, if I want to print the value of the argument x every time the function foo is entered and x > 0:
break foo if x>0
commands
silent
printf "x is %d\n",x
continue
endThere are a few points to note here:
- The first command in a breakpoint command list is usually
silent. This ensures that the messages printed when the breakpoint is triggered are as concise as possible. If thecommand … endblock does not contain printing statements likeprintf, the breakpoint trigger may not produce any output at all. - The last command in a breakpoint command list is usually
continue. This prevents the program from stopping at the breakpoint, allowing the automated debugging script to keep running.
To run an automated debugging script in GDB, use the following command:
gdb [program] -batch -x [commands_file] > logThe -batch flag runs GDB in script mode (without entering the interactive environment), and the -x flag (which can also be written as -command) specifies the debugging script file.