Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Possible Numerical Values of Enum Using GDB

Tags:

enums

gdb

With an enum declared and instantiated like this:

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

test_enumeration test_enum;

I can call

(gdb) ptype test_enum

to get out

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

This gives me the numerical value of test1 and test2 but NOT test3. If I call

(gdb) print (int)test3

GDB prints out the value 11. However I want to be able to get something like this:

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

By printing out the entire type definition using test_enum.
Unfortunately

(gdb) ptype (int)test_enum

returns the the type as int and not the values.

Is there a way to print out the enum constants like this or an option that needs to be set to always display their numerical versions?

GDB V10.1

like image 949
user486185 Avatar asked Oct 20 '25 03:10

user486185


1 Answers

This will print out all the elements of an enum type. The executable needs to have been compiled with 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
like image 193
Mark Plotnick Avatar answered Oct 22 '25 04:10

Mark Plotnick