Contents
Start GDB
Compile and Enable Debugging
To allow GDB to examine functions and variables with using their names appeared in the source code/files, it is necessary to add the flag -g
when compiling your program (with gcc
/g++
).
Quoting a good explanation:
Select Program
# specify the executable to trace file <executable_name> # set arguments to append when running the executable set args <arguments>
[Bonus] Debug a Linux Kernel
It’s not uncommon to debug a Linux kernel with using QEMU and GDB, so I’m giving a little summary here. A full article for building and running the kernel for QEMU can be found here.
The following configurations should be set in defconfig to enable the GDB debugging:
CONFIG_DEBUG_INFO=y CONFIG_DEBUG_KERNEL=y CONFIG_GDB_SCRIPTS=y
CONFIG_GDB_SCRIPTS
for?
“Gdb comes with a powerful scripting interface for python. The kernel provides a collection of helper scripts that can simplify typical kernel debugging steps.” — source
When starting your QEMU, you will want to add the arguments -s -S
to make your VM stop and wait for GDB to connect. Then, in another terminal, you can start gdb
and connect to your QEMU’ed kernel by:
GDB
# enable Python scripts for kernel debugging with lx- commands python gdb.COMPLETE_EXPRESSION = gdb.COMPLETE_SYMBOL add-auto-load-safe-path scripts/gdb/vmlinux-gdb.py # read symbols file vmlinux # connect to the GDB server at the default address target remote :1234 # check the Linux version lx-version # run continue
Configurations
Print and Display
To beautify printing variables (ref):
# enable printing with indents and new lines set print pretty on
Debugging Operations
Run
There are several ways to advance execution in GDB (ref):
# run the program run # continue after a pause continue # execute one line at a time step # run out of the current function finish # step over the current line if it is a function nexti
Show Variables
# show all (global) variable symbols info variables # show variables in current stack (of a function) info locals # show arguments of current function info args # show the value of the specified variable <variable_name> print <variable_name>
Set/Delete Breakpoints
To add breakpoints:
# by function name <function_name> break <function_name> # by file name and line number break <filename>:<line_number> # show existing breakpoints info breakpoints
To delete breakpoints (ref):
# delete all breakpoints clear # delete a breakpoint by ID (displayed in info breakpoints) delete 1
To temporarily disable or enable one or all break points
# disable all breakpoints disable b # enable all breakpoints enable b # disable a breakpoint (e.g., the first breakpoint shown in `info b`) disable 1 # enable a breakpoint enable 1