How to access the keys or values of Python GDB Value

匿名 (未验证) 提交于 2019-12-03 08:50:26

问题:

I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via

(gdb) python mystruct = gdb.parse_and_eval("mystruct") 

Now I got this variable called mystruct which is a GDB.Value object. And I can access all the members of the struct by simply using this object as a dictionary (likemystruct['member']).

The problem is, that my script doesn't know which members a certain struct has. So I wanted to get the keys (or even the values) from this GDB.Value object. But neither mystruct.values() nor mystruct.keys() is working here.

Is there no possibility to access this information? I think it's highly unlikely that you can't access this information, but I didn't found it anywhere. A dir(mystruct) showed me that there also is no keys or values function. I can see all the members by printing the mystruct, but isn't there a way to get the members in python?

回答1:

From GDB documentation:

You can get the type of mystruct like so:

tp = mystruct.type 

and iterate over the fields via tp.fields()

No evil workarounds required ;-)

Update: GDB 7.4 has just been released. From the announcement:

Type objects for struct and union types now allow access to the fields using standard Python dictionary (mapping) methods.



回答2:

Evil workaround:

python print eval("dict(" + str(mystruct)[1:-2] + ")") 

I don't know if this is generalisable. As a demo, I wrote a minimal example test.cpp

#include <iostream>  struct mystruct {   int i;   double x; } mystruct_1;  int main () {   mystruct_1.i = 2;   mystruct_1.x = 1.242;   std::cout << "Blarz";   std::cout << std::endl; } 

Now I run g++ -g test.cpp -o test as usual and fire up gdb test. Here is a example session transcript:

(gdb) break main Breakpoint 1 at 0x400898: file test.cpp, line 11. (gdb) run Starting program: ...  Breakpoint 1, main () at test.cpp:11 11        mystruct_1.i = 2; (gdb) step 12        mystruct_1.x = 1.242; (gdb) step 13        std::cout << "Blarz"; (gdb) python mystruct = gdb.parse_and_eval("mystruct_1") (gdb) python print mystruct {i = 2, x = 1.242} (gdb) python print eval("dict(" + str(mystruct)[1:-2] + ")") {'i': 2, 'x': 1.24} (gdb) python print eval("dict(" + str(mystruct)[1:-2] + ")").keys() ['i', 'x'] 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!