使用 'gdb' 在函数内的特定行中设置断点

setting a breakpoint in a specific line inside a function with 'gdb'

本文关键字:断点 设置 gdb 函数 使用      更新时间:2023-10-16

我正试图用"gdb"将断点设置到类(我创建的类)的成员函数内的第五行。

从这里开始,我了解了如何在函数的开始处设置断点,但我想将其设置在函数内特定的行上,或从函数开始设置特定的offset

一般来说,"gdb"中有没有一种方法可以通过设置与我已经拥有的另一个断点的偏移量来设置一行的断点?

谢谢!

您可以使用gdb breakpoint +<offset>在当前停止位置的偏移处创建断点。

也可以使用gdb break <linenumber>(用于当前源文件)或gdb break <filename>:<linenumber>(用于当前文件以外的文件)在特定行号上创建断点。

更多详细信息请参阅文档。

没有一种方法可以设置相对于函数开头的断点,以便在修改源文件时保留其相对位置。这有时是有用的;但这只是gdb中没有人添加的一个特性。

它可能可以从Python中进行模拟,尽管它不能完全像普通断点那样工作,因为Python无法访问gdb中的断点重置机制。

一次性解决方案可以按照另一个答案中所示的方式完成,也可以从Python中完成。

当我需要这种功能时——一个断点中间函数,它对源代码的更改相当健壮——我使用了"SDT"静态探测点。这些可以让你在你的来源中命名这样的点。

  1. info fun <function name>或完全合格的info functions <function name>获取函数及其源文件
  2. list <function name>

打印以函数开头为中心的行。

将列出所有函数的源代码,并在下面列出一些代码。

  1. 选择您想要的行
  2. break <filename:linenum>

以下是如何使用GDB:的python脚本实现自动化

class RelativeFunctionBreakpoint (gdb.Breakpoint):
    def __init__(self, functionName, lineOffset):
        super().__init__(RelativeFunctionBreakpoint.calculate(functionName, lineOffset))
    def calculate(functionName, lineOffset):
        """
        Calculates an absolute breakpoint location (file:linenumber)
        based on functionName and lineOffset
        """
        # get info about the file and line number where the function is defined
        info = gdb.execute("info line "+functionName, to_string=True)
        # extract file name and line number 
        m = re.match(r'Line[^d]+(d+)[^"]+"([^"]+)', info)
        if not m:
            raise Exception('Failed to find function %s.' % functionName)
        line = int(m.group(1))+lineOffset #add the lineOffset
        fileName = m.group(2)
        return "%s:%d" % (fileName, line)

基本用法:

RelativeFunctionBreakpoint("yourFunctionName", lineOffset=5)

您还可以编写自定义断点。点击此处查看更多信息:https://stackoverflow.com/a/46737659/5787022

使用python编写GDB 脚本

  • 官方文件:https://sourceware.org/gdb/onlinedocs/gdb/Python.html
  • 一些考试:http://tromey.com/blog/?p=548