Exploring GDB's Python API with Jupyter
GDB — the most common console debugger on Linux systems — has a Python API for adding new debugger commands and pretty-printers for complex data structures, or to automate debugging tasks.
While Python scripts can be loaded from files, it is nice to interactively explore the API or the debugged program. IPython would be perfect for the job, but starting it directly inside GDB doesn't work well. Fortunately, it's easy to launch an IPython kernel and connect with an external Jupyter console.
Launching the kernel from the gdb prompt:
(gdb) python
>import IPython; IPython.embed_kernel()
>end
Gives the following message:
To connect another client to this kernel, use:
--existing kernel-12688.json
We can start Jupyter on a separate terminal and connect to this kernel:
$ jupyter console --existing kernel-12688.json
In [1]: gdb.newest_frame().name()
Out[1]: 'main'
The GDB Python API is then available from the gdb
module within this
Python session. To get started, I'd suggest the API documentation
or this series of tutorials.
Currently, only the console client can connect to existing kernels. Support in the Notebook or in Jupyter Lab is tackled in this Github issue. Even with the limited capabilities of the console client, it's a great way to explore the API and to tackle more complicated debugging problems that require automation to solve.