GDB: how to change a convenience variable from a built-in python

gdb, python

Solution

accept a string, return it's lenght

If you indeed need strlen you can use `$_strlen` - a built in gdb convenience function that compute string length:

(gdb) set $Retrn=$_strlen("test")
(gdb) p $Retrn
$4 = 4

how to assign something to a GDB convenience variable from a built-in python?

You can use gdb.execute:

>more my_own_len.py
class my_own_len (gdb.Function):
   def __init__ (self):
     super (my_own_len, self).__init__ ("my_own_len")

   def invoke (self, arg):
      res=len(arg.string())
      gdb.execute( "set $Retrn=" + str(res))
      return res

my_own_len()

This is a test:

>gdb -q -x my_own_len.py
(gdb) p $_strlen("test")
$1 = 4
(gdb) p $my_own_len("test")
$2 = 4
(gdb) p $Retrn
$3 = 4
(gdb)

Problem

How do I assign something to a gdb convenience variable from its built-in python? I thought it should be simple, because it naturally arises while trying to implement a user-defined function. However I couldn't find anything. UPD: Added a simplified example. My real function is more complex though. Anyway, a way to transfer a variable from python up to gdb would help greatly. An example of usage (achtung! — it raises an error): ``` #accept a string, return it's lenght define RetLenOfArg py arg0 = gdb.parse_and_eval("$arg0") set $Retrn = py len(arg0) end ```

Original source