Site Tools


wiki:gdb-advanced-features

GDB Advanced Features

GDB supports Python scripting, remote debugging, and signal handling. These features enable automation, distributed debugging, and fine-grained control over program behavior.

Python Scripting

GDB allows Python scripts to inspect and control programs. Define custom commands or automate debugging tasks:

(gdb) python
> import gdb
> frame = gdb.selected_frame()
> print(frame.name())
> end
 
(gdb) define pprint
  python
    frame = gdb.selected_frame()
    print(f"Function: {frame.name()}")
  end
end

Access program state from Python: gdb.selected_frame() returns the current frame; gdb.breakpoints() lists breakpoints; gdb.execute(cmd) runs a GDB command. Combine these to script complex debugging workflows.

Remote Debugging

Debug a program running on another machine using gdbserver. Start the remote server, then connect from your local GDB:

# On remote machine
gdbserver localhost:1234 ./program
 
# On local machine
gdb ./program
(gdb) target remote hostname:1234
(gdb) break main
(gdb) continue

gdbserver is lightweight and does not require GDB on the remote machine—only on your local machine. Useful for embedded systems or production servers.

Signal Handling

Control how GDB handles signals (SIGTERM, SIGSEGV, etc.):

(gdb) handle SIGTERM stop       # pause on SIGTERM
(gdb) handle SIGPIPE nostop     # ignore SIGPIPE, don't pause
(gdb) handle SIGUSR1 print      # print message but don't pause
(gdb) catch signal SIGUSR1      # breakpoint on signal (alternative syntax)
(gdb) info signals              # list all signals

By default, some signals pause (SIGSEGV) and others don't (SIGPIPE). handle lets you change this. Useful for debugging signal handlers or ignoring noisy signals in production code.

Pretty Printing

Configure how complex types print:

(gdb) define pp
  set print pretty on
  print $arg0
  set print pretty off
end

Write Python pretty-printers to customize output of user-defined types (classes, structs). Saves time inspecting complex data structures.

Debugging Optimization

Compile with -O0 -g for reliable debugging. If you must debug optimized code (-O2), GDB loses variable information and instruction order becomes unpredictable. Some variables may be optimized away entirely.

Remote debugging and signal handling are essential for production debugging; Python scripting is useful for automating repetitive debugging patterns.

wiki/gdb-advanced-features.md · Last modified: by 127.0.0.1