3

I'm using python2.6's gdb module while debugging a C program, and would like to convert a gdb.Value instance into a python numeral object (variable) based off the instance's '.Type'.

E.g. turn my C program's SomeStruct->some_float_val = 1./6; to a Python gdb.Value via sfv=gdb.parse_and_eval('SomeStruct->some_double_val'), but THEN turn this into a double precision floating point python variable -- knowing that str(sfv.type.strip_typedefs())=='double' and its size is 8B -- WITHOUT just converting through a string using dbl=float(str(sfv)) or Value.string() but rather something like unpacking the bytes using struct to get the correct double value.

Every link returned from my searches points https://sourceware.org/gdb/onlinedocs/gdb/Values-From-Inferior.html#Values-From-Inferior, but I can't see how to convert a Value instance into a python variable cleanly, say the Value wasn't even in C memory but represented a gdb.Value.address (so can't use Inferior.read_memory()), how would one turn this into a Python int without casting string values?

2 Answers2

5

You can convert it directly from the Value using int or float:

(gdb) python print int(gdb.Value(0))
0
(gdb) python print float(gdb.Value(0.0))
0.0

There seems to be at least one glitch in the system, though, as float(gdb.Value(0)) does not work.

Tom Tromey
  • 21,507
  • 2
  • 45
  • 63
  • Thanks! This does appear to work on my C values but doesn't work all the time e.g. `int(xxxValue.address)` fails -- I have to use int(str()). Guess I'll have to catch exceptions. Unrelated, can you set a gdb.Value of a pointed to address to another gdb.Value or gdb.Parameter without using `gdb.parse_and_eval(xxx=newval)`? –  Apr 29 '15 at 16:58
  • I think you can convert a pointer using `long()`. I don't think there is any way to assign right now without using `parse_and_eval`. – Tom Tromey Apr 30 '15 at 03:37
  • actually with python 2.7 you are better off using `long()` instead of int, as on the 32bit builds int will truncate the value to 32bits. As such I always use `long()`. – John Kearney Nov 04 '19 at 17:38
0

I stumbled upon this while trying to figure out how to do bitwise operations on a pointer. In my particular use case, I needed to calculate a page alignment offset. Python did not want to cast a pointer Value to int, however, the following worked:

int(ptr.cast(gdb.lookup_type("unsigned long long")))

We first make gdb cast our pointer to unsigned long long, and then the resulting gdb.Value can be cast to Python int.

Sasha Pachev
  • 5,162
  • 3
  • 20
  • 20