Wakan Tanka
Wakan Tanka

Reputation: 8042

how to pass variables from GDB to invoked python interpeter

From some version of GDB (I guess 7 or so) it is possible to invoke python from GDB in interactive or non interactive way.

Here is some example:

(gdb) python print("gdb".capitalize())
Gdb
(gdb)

Is it possible to pass variables from used in GDB into Python? I've tried something like this but with no luck:

Try to pass C variable named c_variable

(gdb) python print(c_variable.capitalize())
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'c_variable' is not defined
Error while executing Python code.

Try to pass GDB's variable named $1

(gdb) python print($1.capitalize())
  File "<string>", line 1
    print($1.capitalize())
          ^
SyntaxError: invalid syntax
Error while executing Python code.

EDIT

Almost imediatelly after my question I've found this question passing c++ variables to python via gdb

So I've end up with following:

(gdb) whatis p_char
type = char *

(gdb) ptype p_char
type = char *

(gdb) p p_char
$1 = 0x8002004 "hello world"

(gdb) python x=str(gdb.parse_and_eval('p_char')); print(x.split(" "))
['0x8002004', '"hello', 'world"']

This is something that I can work with but I need to do some extra cleanup (remove quotes, address etc), is there any better way? And I still do not know if is possible to pass $1.

Upvotes: 1

Views: 575

Answers (2)

Andrew
Andrew

Reputation: 4751

If you want to work with Python and GDB I would highly recommend reading this. Of special interest to you would be this page that includes parse_and_eval as well as this page on values.

The gdb.parse_and_eval function returns a gdb.Value object. For values that are strings you can use the string method, so:

(gdb) python print(gdb.parse_and_eval("string_var").string())
Hello World
(gdb) python print(gdb.parse_and_eval("string_var").string()[::-1])
dlroW olleH

Upvotes: 0

Employed Russian
Employed Russian

Reputation: 213586

Try to pass C variable named c_variable
Try to pass GDB's variable named $1

py print(gdb.parse_and_eval("c_variable"))
py print(gdb.parse_and_eval("$1"))

Upvotes: 1

Related Questions