使用 GDB 查找枚举的可能数值

Find Possible Numerical Values of Enum Using GDB

像这样声明和实例化的枚举:

enum test_enumeration
    {
        test1 = 4,
        test2 = 10,
        test3,
    };

test_enumeration test_enum;

我可以打电话

(gdb) ptype test_enum

出去

type = enum test_enumeration {test1 = 4, test2 = 10, test3}

这给了我 test1 和 test2 但不是 test3 的数值。 如果我打电话

(gdb) print (int)test3

GDB 打印出值 11。 但是我希望能够得到这样的东西:

type = enum test_enumeration {test1 = 4, test2 = 10, test3 = 11}

通过使用 test_enum 打印出整个类型定义。
遗憾

(gdb) ptype (int)test_enum

returns 类型为 int 而不是值。

有没有办法像这样打印出枚举常量,或者需要设置一个选项来始终显示它们的数字版本?

GDB V10.1

这在 GDB 中目前是不可能的。决定是否打印 = VAL 部分的代码在这里:

https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=gdb/c-typeprint.c;h=0502d31eff9605e7e2e430c8ad72908792c1b475;hb=HEAD#l1607

仅当该值不比前一个枚举条目的值大 1 时才打印该值。

这将打印出枚举类型的所有元素。可执行文件需要使用 debuginfo 进行编译。

$ cat print-enum.py
import gdb

class PrintEnumCmd(gdb.Command):
  """print all elements of the given enum type"""

  def __init__(self):
    super(PrintEnumCmd, self).__init__("print-enum", gdb.COMMAND_DATA, gdb.COMPLETE_EXPRESSION)

  def invoke(self, argstr, from_tty):
    typename = argstr
    if not typename or typename.isspace():
      raise gdb.GdbError("Usage: print-enum type")

    try:
      t = gdb.lookup_type(typename)
    except gdb.error:
      typename = "enum " + typename
      try:
        t = gdb.lookup_type(typename)
      except gdb.error:
        raise gdb.GdbError("type " + typename + " not found")

    if t.code != gdb.TYPE_CODE_ENUM:
      raise gdb.GdbError("type " + typename + " is not an enum")

    for f in t.fields():
      print(f.name, "=", f.enumval)

PrintEnumCmd()
$ gdb enu
Reading symbols from enu...done.
(gdb) source print-enum.py
(gdb) print-enum
Usage: print-enum type
(gdb) print-enum test<tab>
test1             test2             test3             test_enumeration
(gdb) print-enum test_enumeration
test1 = 4
test2 = 10
test3 = 11