无法使用 Python 调用 GDB 用户定义函数

Cannot call GDB user defined function with Python

我使用 Python API,

为 GDB 定义了一个方便的函数
import gdb

verbose = True

class HCall(gdb.Function):
    def __init__(self, funcname):
        super(HCall,self).__init__(funcname)

    def log_call(cmd):
        if verbose:
            print(cmd)
        try:
            gdb.execute(cmd)
        except Exception, e:
            print (e)
            import traceback
            # traceback.print_stack()
            traceback.format_exc()


class NewCVar(HCall):
   """ allocates a c variable in heap """
   def __init__(self):
       super(NewCVar,self).__init__("newcvar")

   def invoke(self, name, oftype):
       cmd = "call gdb.execute(set $" + name + " = malloc(sizeof(" + oftype + "))"
       log_call(cmd)
       return "$" + name

NewCVar()

我可以使用 "source usefunction.py" 加载此文件,并使用 "function newcvar" 打印帮助文本。尽管如此,GDB 并不知道 $newcvar,正如我所料 (https://sourceware.org/gdb/onlinedocs/gdb/Functions-In-Python.html).

有人知道我做错了什么吗?

提前致谢!

您应该 post 究竟发生了什么,以及您期望发生什么。

我在 gdb 中试过你的程序,gdb 确实看到了这个功能;但由于函数中存在错误,因此它实际上不起作用。例如我试过:

(gdb) p $newcvar("x", "int")
Traceback (most recent call last):
  File "/tmp/q.py", line 23, in invoke
    cmd = "call gdb.execute(set $" + name + " = malloc(sizeof(" + oftype + "))"
gdb.error: Argument to arithmetic operation not a number or boolean.
Error occurred in Python convenience function: Argument to arithmetic operation not a number or boolean.

错误是您试图 gdb.execute 看起来像 call gdb.execute(...) 的字符串。这很奇怪。 call 计算下层表达式,因此将它与包含 gdb.execute 的参数一起使用是不正确的。相反 NewCVar.invoke 应该使字符串像 set variable $mumble = ....

这里返回一个字符串也很奇怪

我想知道为什么你希望它是一个函数而不是一个新的 gdb 命令。