import gdb only works when your Python code is running within the GDB process. It’s not supposed to work from the regular system Python interpreter.
Explanation
- GDB embeds the Python interpreter so it can use Python as an extension language.
- You can’t just
import gdbfrom/usr/bin/pythonlike it’s an ordinary Python library because GDB isn’t structured as a library. - What you can do is
source MY-SCRIPT.pyfrom within gdb (equivalent to runninggdb -x MY-SCRIPT.py).
Example Program
Here’s a self contained example. Save the file below to t.py:
import gdb
gdb.execute('file /bin/cat')
o = gdb.execute('disassemble exit', to_string=True)
print(o)
gdb.execute('quit')
run:
$ gdb -q -x t.py
and you’ll see the PLT stub for exit() disassembled. On x86-64 Linux:
Dump of assembler code for function exit@plt:
0x0000000000401ae0 <+0>: jmpq *0x20971a(%rip) # 0x60b200 <exit@got.plt>
0x0000000000401ae6 <+6>: pushq $0x3d
0x0000000000401aeb <+11>: jmpq 0x401700
End of assembler dump.
I’ve collected some resources on learning the GDB Python API here.