Search code examples
c++lldbpretty-print

LLDB Data Formatter and C array


I would like to write a LLDB Data Formatter for my own objects which is the following:

template <typename T, int n>
class StaticArray {
  T data_[n];
}

Here is how my synthetic data formatter looks so far:

class StaticArrayProvider:
    def __init__(self, valobj, internal_dict):
        self.valobj = valobj
        self.data = self.valobj.GetChildMemberWithName('data_').GetChildAtIndex(0)
        self.data_type = self.data.GetType()
        self.type_size = self.data_type.GetByteSize()
        self.size = # ???

    def num_children(self):
        return self.size

    def get_child_index(self, name):
        try:
            return int(name.lstrip('[').rstrip(']'))
        except:
            return -1

    def get_child_at_index(self, index):
        if index < 0:
            return None
        if index >= self.num_children():
            return None
        try:
            offset = index * self.type_size
            return # ???
        except:
            return None

I don't know what to do to fill the blanks # ???. Do you have any solution?


Solution

  • In the lldb value system, GetNumChildren returns the number of elements of a statically sized array, and GetChildAtIndex fetches that array element. Since for each template instantiation data_ is a statically sized array, your data formatter can just forward data_ when providing children. I.e. you can do:

    self.data = self.valobj.GetChildMemberWithName('data_')
    

    then num_children just returns self.data.GetNumChildren() and get_child_at_index returns self.data.GetChildAtIndex().

    You only need to calculate offsets and sizes when lldb can't figure that out for you (for instance if you have a dynamically sized array or a pointer to type that you are treating as an array.)