Skip to content

GdbWithPythonOnUbuntu

Erik Rose edited this page Mar 1, 2016 · 1 revision

gdb debugging of Python stack frames on Ubuntu Trusty

I couldn't find anywhere else that put it all together, so here it is. This may not be completely minimal; I was just happy to finally get it working. Also, this seems to go out of date easily with new gdb and OS versions, so I don't expect it to work beyond Trusty. However, it can save you weeks of guess-and-check debugging.

Install things

  1. Install python2.7-dbg, a version of Python with debug symbols included.
  2. Make and activate a new venv that uses python2.7-dbg as its Python.
  3. cd /the/venv
  4. mkdir bin/.debug
  5. Link everything into the magic directories gdb looks for:
ln -sf /usr/lib/debug/usr/bin/python2.7-gdb.py bin/.debug/python-gdb.py
ln -sf /usr/lib/debug/usr/bin/python2.7 bin/.debug/
ln -sf /usr/lib/python2.7/config_d/ lib/python2.7/config_d
ln -sf /usr/include/python2.7_d/ local/include/python2.7_d
ln -sf /usr/lib/debug/usr/bin/python2.7-gdb.py bin/python-gdb.py
sudo ln -sf /usr/lib/debug/usr/lib/libpython2.7.so.1.0-gdb.py /usr/lib/debug/usr/lib/libpython.py

Either attach to a running (typically hung) Python process...

The initialization of libpython (which provides the macros like py-bt and py-list) can theoretically be moved into a gdb rc file, but that didn't work for me, so I had to type it out interactively each time.

$ gdb --args python
(gdb) attach 585
(gdb) python
>import sys
>sys.path.append('/usr/lib/debug/usr/lib/')
>import libpython
>end
(gdb) py-bt

...or start your Python script from within gdb

$ gdb --args python
(gdb) python
>import sys
>sys.path.append('/usr/lib/debug/usr/lib/')
>import libpython
>end
(gdb) run dbg-venv/bin/dxr index

Some other Python gdb macros