Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import 'GDB' in Python

Tags:

python

gdb

I am using Python 2.7 and Python 3.1.3. But in my Python I am unable to "import gdb".

It is giving me an error as:

>>> import gdb Traceback (most recent call last):   File "<interactive input>", line 1, in <module> ImportError: No module named gdb >>> 

What's a reason for this? How should I solve this problem?

like image 982
Sagar Gupta M. Avatar asked Jan 25 '11 10:01

Sagar Gupta M.


People also ask

Can you use GDB for Python?

A set of GDB macros are distributed with Python that aid in debugging the Python process. You can install them by adding the contents of Misc/gdbinit in the Python sources to ~/. gdbinit -- or copy it from Subversion.


1 Answers

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 gdb from /usr/bin/python like it's an ordinary Python library because GDB isn't structured as a library.
  • What you can do is source MY-SCRIPT.py from within gdb (equivalent to running gdb -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 <[email protected]>    0x0000000000401ae6 <+6>:  pushq  $0x3d    0x0000000000401aeb <+11>: jmpq   0x401700 End of assembler dump. 

I've collected some resources on learning the GDB Python API here.

like image 91
scottt Avatar answered Sep 28 '22 10:09

scottt