I’ve recently been looking into ways to improve my debugging experience with mixed Python and C/C++ programs. I spend a fair amount of time working on systems built using both languages in tandem, and the tools available for debugging across the languages have historically been very limited. Often, logging and/or intimate knowledge of the Python C-API (and, in my case, boost.python) were the primary tools available.
I was naturally very excited, then, when GDB 7 introduced support for extension via Python. This seemed like an obvious step towards a “unified” debugging environment, one where I could step naturally between the languages, set breakpoints, etc. This new GDB feature doesn’t solve the problem directly, but it opens the door for more sophisticated extensions to GDB than were previously practical.
Building on this new GDB feature, recent Python source releases include GDB extensions as a build product. That is, starting at around python-3.2, when you build Python from source one of the build products is a set of GDB extensions that make it possible to do very natural debugging of Python from inside GDB. These extensions allow you, for example, to step up and down the Python call stack, display frame information (locals), and so forth. And this can be done while also navigating the base C call stack. This provides a very intuitive and productive debugging environment for anyone working across the two runtime environment.
edit: It was pointed out on reddit that gdb’s embedded Python interpreter has been around since 2009 and is thus not particularly new.
GDB 7′s Python extension system
What exactly is GDB’s new Python extension system? Broadly speaking, it’s a way to script GDB using Python rather than GDB’s own internal language. From around version 7 onward, GDB embeds a Python interpreter that you can invoke from the prompt and from scripts. For example:
(gdb) python
&>import sys
To support writing extensions, you can import the module “gdb” from this embedded interpreter. This module provides access and hooks into GDB so that you can control it via Python scripts. You can read all about this Python extension support in GDB’s documentation.
This new facility has been used to implement, for example, pretty printers for STL containers. But in this article we’re interested in improving the CPython debugging experience, so we’ll cover that in the next section.
Read more: Misspent
QR: