python - GDB python API - 获取 gdb 的 python API 来打印有问题的行号

标签 python gdb

我正在尝试使用 gdb python API 将一些调试宏写入 C 代码。但是在测试脚本时,我发现报告的脚本中的解释错误没有行号。

例如 (gdb) module show obj-template 0x7264b0 "test-entry" Python Exception <class 'IndexError'> list index out of range: Error occurred in Python command: list index out of range

这里我可以看到有一个IndexError,但是脚本没有说哪个是行号,我该如何获取它?

最佳答案

在脚本中的某个适当位置捕获异常,并根据需要漂亮地打印异常和回溯。

建议你引用一些用gdbpython编写的gdb插件,包括peda , gef , pwndbg等等。此类插件实际上使用了 gdbpython 的所有功能,并且包含编写 python gdb 插件的非常好的实践。强大的 gdbpython 插件通常具有用于 python 异常的 pretty-print 。

举个例子,这里是gef的backtrace pretty-print :(当然你不能直接使用它,因为它包含了太多的gef内部函数)

def show_last_exception():
    """Display the last Python exception."""
    print("")
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print(" Exception raised ".center(80, horizontal_line))
    print("{}: {}".format(Color.colorify(exc_type.__name__, attrs="bold underline red"), exc_value))
    print(" Detailed stacktrace ".center(80, horizontal_line))
    for fs in traceback.extract_tb(exc_traceback)[::-1]:
        if PYTHON_MAJOR==2:
            filename, lineno, method, code = fs
        else:
            filename, lineno, method, code = fs.filename, fs.lineno, fs.name, fs.line

        print("""{} File "{}", line {:d}, in {}()""".format(down_arrow, Color.yellowify(filename),
                                                            lineno, Color.greenify(method)))
        print("   {}    {}".format(right_arrow, code))

    print(" Last 10 GDB commands ".center(80, horizontal_line))
    gdb.execute("show commands")
    print(" Runtime environment ".center(80, horizontal_line))
    print("* GDB: {}".format(gdb.VERSION))
    print("* Python: {:d}.{:d}.{:d} - {:s}".format(sys.version_info.major, sys.version_info.minor,
                                                   sys.version_info.micro, sys.version_info.releaselevel))
    print("* OS: {:s} - {:s} ({:s}) on {:s}".format(platform.system(), platform.release(),
                                                    platform.architecture()[0],
                                                    " ".join(platform.dist())))
    print(horizontal_line*80)
    print("")
    return

关于python - GDB python API - 获取 gdb 的 python API 来打印有问题的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44733195/

相关文章:

python - 使用 pandas apply with dates and dates shifted

python - 为什么 `eval` 在 Python 类函数中不起作用?

python - 迭代 python 对象是 2.7。显示未找到错误

python - 谷歌应用程序引擎 SDK : System time different from the computer time

c - 如何使用GDB调试带SMP(对称多处理器)的QEMU?

c - 分段故障。为什么这个指针指向无效地址?

assembly - 在gdb中找不到.bss节中定义的变量名

python - 访问 murano 仪表板时 openstack newton keystone 出现 "No module named memcache"错误

c - x86 程序集中出现奇怪的段错误

c - 无法将 GDB 附加到 Eclipse CDT 中的进程