debugging 如何对gdb打印进行grep

huus2vyu  于 2023-02-23  发布在  其他
关注(0)|答案(4)|浏览(170)

有没有办法在gdb中对print命令的输出进行grep?在我的例子中,我正在使用gdb调试一个核心转储,而我正在调试的对象包含了大量的元素。我发现很难找到匹配的属性,即:

(gdb) print *this | grep <attribute>

谢谢。

ibps3vxo

ibps3vxo1#

您可以使用pipe命令

>>> pipe maintenance info sections | grep .text
 [15]     0x5555555551c0->0x5555555554d5 at 0x000011c0: .text ...

>>> pipe maintenance info sections | grep .text | wc 
      1      10     100
ne5o7dgx

ne5o7dgx2#

(gdb)打印 * 此|格雷普
实现这一点的"标准"方法是在emacs中使用Meta-X gdb
另一种选择:

(gdb) set logging on
(gdb) print *this
(gdb) set logging off
(gdb) shell grep attribute gdb.txt

与上面的补丁相比,cnicutar提到的补丁看起来确实很吸引人,我猜它(或它的等价物)从未提交的原因是大多数GDB维护者使用emacs,所以一开始就没有这个问题。

fhity93d

fhity93d3#

最简单的方法是利用gdb python。

gdb λ py ["attribute" in line and print(line) for line in gdb.execute("p *this", to_string=True).splitlines()]

假设你已经启用了命令历史记录,你可以只输入一次,然后按Ctrl+ Rb.exec把它从历史记录中拉出来。接下来只需根据你的要求修改attribute*this
您也可以将其简化为:

gdb λ grep_cmd "p *this" attribute

为此,只需将以下内容添加到您的.gdbinit文件:

py
class GrepCmd (gdb.Command):
    """Execute command, but only show lines matching the pattern
    Usage: grep_cmd <cmd> <pattern> """

    def __init__ (_):
        super ().__init__ ("grep_cmd", gdb.COMMAND_STATUS)

    def invoke (_, args_raw, __):
        args = gdb.string_to_argv(args_raw)
        if len(args) != 2:
            print("Wrong parameters number. Usage: grep_cmd <cmd> <pattern>")
        else:
            for line in gdb.execute(args[0], to_string=True).splitlines():
                if args[1] in line:
                    print(line)

GrepCmd() # required to get it registered
end
uplii1fm

uplii1fm4#

我知道这是一个老职位,但因为我发现它看起来做同样的事情,我想我会添加到Hi-Angel的答案说,你可以突出显示搜索词,在python输出,在红色的一个取代打印行与下面:

print(line.replace(args[1], "\033[91m"+args[1]+"\033[0m"))

这只是使用ascii escape命令的颜色,所以应该工作在Linux和Windows终端,你可以很容易地改变颜色。

  • 抱歉,没有足够的代表将此添加为评论。*

相关问题