use python in gdb

Believe or not, you can run python code in GDB.

(gdb)
python print("hello world")
&"python print(\"hello world\")\n"
~"hello world\n"
^done
(gdb)

In the above example, we call the python function print(“hello world”) in gdb environment. The python statement is executed and the output is displayed. You just need to write your python statements after the  python command. You can execute any legal python statement with the python command. For example, you can import a python module:

(gdb)
python import gdb
&"python import gdb\n"
^done
(gdb)

You can import system defined modules or modules of your own. To let python find and load your modules, you may need to execute the following python statements before importing:

python sys.path.insert(1, 'c:/moduedirectory1/')
python sys.path.append('c:/moduedirectory2/')

But simply calling the ordinary python functions does not make much sense. Why call python functions inside GDB rather than in the python environment outside GDB? That is because GDB has python api support and provides several python modules you can use.  The GDB python modules are a set of functions/classes you can use to interact with GDB when debugging a program. For example, you can use gdb.execute to execute a GDB command, you can use gdb.selected_frame to get a GDB defined Frame object(gdb.Frame), you can get the variables in the frame by calling frame.read_var(name).

Although you can use GDB python API to control GDB and get information about the inferior, it seems not much useful considering you can do the same thing using the GDB CLI commands. You used the GDB commands: br, p, n, s, etc. in the past and you did your job well. Why bother using the API? That is because not only you can call GDB’s API functions, but also GDB may call the python functions you defined at some time. For example, you can define a dumper function to display a complex variable of inferior in a friendly way. You can register your dumper function with a type. When you want to print a variable of this type in GDB using the command “print *myvar”, GDB will call your function to display its value. So your python code extends the functionalities of GDB.

Reference:https://stackoverflow.com/questions/4792483/how-to-import-gdb-in-python/10240053

Leave a Reply