1

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.

2 Answers 2

1

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"))
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.