Search code examples
pythonghidra

How to add an Enum with python into a Ghidra project


Saw someone using ghidra.app.util.cparser.C to parse a string of a struct into a struct object and than they added it into Ghidra using data_type_manager.addDataType(). I want to implement that method with Enumerates but I'm not sure how. If there is a better method to add an Enum I will gladly use it, and if this is the best way to do it an explanation would be a great help. here is my reference: https://reverseengineering.stackexchange.com/questions/23330/ghidra-python-create-struct-with-big-endian-field


Solution

  • You can create an enum via the CParser and then add the resulting DataType to the DataTypeManager. I have a script for this generic workflow, if you don't care about scripting it yourself, and are content with a simple GUI to paste C code into, check the resulting DataType and add it if desired.

    Otherwise you can also create an enum data type directly:

    from ghidra.program.model.data import EnumDataType
    # maximum enum value is (2^length)-1 according to some comment, but if you pass 8 it should be every possible Java long value, so I am not sure
    enum = EnumDataType("EnumName", length)
    enum.add("One", 1)
    enum.add("Two", 2)
    enum.add("Three", 3)
    dataTypeManager.addDataType(enum, None)