新的GDB-Python 脚本 API看起来非常强大,应该非常有用。然而,编写一个有用的脚本来遍历 C 或 C++ 结构中的字段并非易事。有谁知道一些确实可以做到这一点的固体样品?
提前致谢。
更新最终样本:替换_print_fields()
早期样本。
if l.type.code == gdb.TYPE_CODE_STRUCT:
print "Found a struct %s " % n
#self._print_fields(n, t)
self._print_deep_items(n, t, l)
else:
print "Found no struct"
def _print_deep_items (self, n_, type_, instance_):
for fld in type_.fields():
fn = fld.name
ft = fld.type
fv = instance_[fn]
if fv.type.code == gdb.TYPE_CODE_STRUCT:
print " Found a sub struct %s " % fn
self._print_deep_items(fn, ft, fv)
else:
print " Field %s " % fn, " type %s " % ft.tag, " value %s " % fv
和输出:
variable s1 type S1
Found a struct s1
Field v1 type None value 0
Field v2 type None value 0
Found a sub struct v3
Field w3 type None value 0
使用第一个示例更新:使以下示例代码正常工作。这不是最佳的,因为它在组成字符串字段名称后对每个字段进行查找。abarnert 展示了一种有前途且优雅的方法,工作代码在上述最终更新部分进行了更新。
import gdb
class PrintGList(gdb.Command):
"""print fields of a struct: wzd struct_object
Iterate through the fields of a struct, and display
a human-readable form of the objects."""
def __init__(self):
gdb.Command.__init__(self, "wzd", gdb.COMMAND_DATA, gdb.COMPLETE_SYMBOL, True)
def invoke(self, arg, from_tty):
arg_list = gdb.string_to_argv(arg)
if len(arg_list) < 1:
print "usage: wzd struct"
return
n = arg_list[0]
l = gdb.parse_and_eval(arg_list[0])
m = l.type.tag
print " variable %s " % n, " type %s " % m
try:
t = gdb.lookup_type(m)
except RuntimeError, e:
print "type %s not found" % t
return
if l.type.code == gdb.TYPE_CODE_STRUCT:
print "Found a struct %s " % n
self._print_fields(n, t)
else:
print "Found no struct"
def _print_fields(self, n, typeobject):
print typeobject
flds = typeobject.fields()
for x in flds:
sn = n + "." + x.name
print " field %s" % sn, " code %s " % x.type.code, " type %s " % x.type.tag
if x.type.code == gdb.TYPE_CODE_STRUCT:
print "Found sub level struct %s " % sn
sl = gdb.parse_and_eval(sn)
sm = sl.type.tag
st = gdb.lookup_type( sm )
self._print_fields(sn, x.type)
def _deep_items (self, type_):
for k, v in type_.iteritems():
if k:
print " k v %s " % k , " %s " % v
else:
print " v ", " %s " % v
PrintGList()
用于测试的源文件:
struct S2 { int w3; };
struct S1 { int v1, v2; struct S2 v3; } s1;
int main(int argc, char *argv[]) { return 0; }
示例输出:
variable s1 type S1
Found a struct s1
S1
field s1.v1 typecode 8 type None
field s1.v2 typecode 8 type None
field s1.v3 typecode 3 type S2
Found sub level struct s1.v3
S2
field s1.v3.w3 typecode 8 type None
获取 GDB 会话: source /home/me/testpath/wzdfile.py 文件 a.out b main r wzd s1 quit