|
| 1 | +import abc |
| 2 | +import logging |
| 3 | +import math |
| 4 | +from typing import ( |
| 5 | + Any, |
| 6 | + Callable, |
| 7 | + Iterable, |
| 8 | +) |
| 9 | +import re |
| 10 | + |
| 11 | +import gdb |
| 12 | + |
| 13 | + |
| 14 | +class Buffer(metaclass=abc.ABCMeta): |
| 15 | + """Base class for accessing buffer contents""" |
| 16 | + |
| 17 | + def __init__(self, val: gdb.Value, data_key: str): |
| 18 | + self._val: gdb.Value = val |
| 19 | + self._data_key: str = data_key |
| 20 | + |
| 21 | + @abc.abstractmethod |
| 22 | + def __len__(self) -> int: |
| 23 | + ... |
| 24 | + |
| 25 | + def __getitem__(self, key) -> Any: |
| 26 | + return self.data()[key] |
| 27 | + |
| 28 | + def data(self) -> gdb.Value: |
| 29 | + return self._val[self._data_key] |
| 30 | + |
| 31 | + |
| 32 | +class StackBuffer(Buffer): |
| 33 | + |
| 34 | + def __init__(self, val: gdb.Value): |
| 35 | + super().__init__(val, "m_data") |
| 36 | + |
| 37 | + def __len__(self) -> int: |
| 38 | + return int(self._val.type.template_argument(1)) |
| 39 | + |
| 40 | + |
| 41 | +class ChaiBuffer(Buffer): |
| 42 | + |
| 43 | + def __init__(self, val: gdb.Value): |
| 44 | + super().__init__(val, "m_pointer") |
| 45 | + |
| 46 | + def __len__(self) -> int: |
| 47 | + return int(self._val['m_capacity']) |
| 48 | + |
| 49 | + |
| 50 | +class MallocBuffer(Buffer): |
| 51 | + |
| 52 | + def __init__(self, val: gdb.Value): |
| 53 | + super().__init__(val, "m_data") |
| 54 | + |
| 55 | + def __len__(self) -> int: |
| 56 | + return int(self._val['m_capacity']) |
| 57 | + |
| 58 | + |
| 59 | +def extract_buffer(val: gdb.Value) -> Buffer: |
| 60 | + # Use self.val.type.fields() to know the fields. |
| 61 | + # You can also have a look at the fields of the fields. |
| 62 | + t: str = str(val.type) |
| 63 | + if re.match('LvArray::ChaiBuffer<.*>', t): |
| 64 | + return ChaiBuffer(val) |
| 65 | + elif re.match('LvArray::StackBuffer<.*>', t): |
| 66 | + return StackBuffer(val) |
| 67 | + elif re.match('LvArray::MallocBuffer<.*>', t): |
| 68 | + return MallocBuffer(val) |
| 69 | + else: |
| 70 | + raise ValueError(f"Could not build buffer from `{val.type}`.") |
| 71 | + |
| 72 | + |
| 73 | +class LvArrayPrinter: |
| 74 | + """Base printer for LvArray classes""" |
| 75 | + |
| 76 | + def __init__(self, val: gdb.Value): |
| 77 | + self.val: gdb.Value = val |
| 78 | + |
| 79 | + def real_type(self) -> gdb.Type: |
| 80 | + return self.val.type.strip_typedefs() |
| 81 | + |
| 82 | + def display_hint(self) -> str: |
| 83 | + return 'array' |
| 84 | + |
| 85 | + |
| 86 | +class __ArrayPrinter(LvArrayPrinter): |
| 87 | + """Utility class for code factorization""" |
| 88 | + |
| 89 | + def __init__(self, |
| 90 | + val: gdb.Value, |
| 91 | + data_extractor: Callable[[gdb.Value], gdb.Value], |
| 92 | + dimension_extractor: Callable[[gdb.Value], gdb.Value]): |
| 93 | + """ |
| 94 | + val: The initial `gdb.Value`. Typically a `LvArray::Array`. |
| 95 | + data_extractor: How to access the raw data from the initial `val`. |
| 96 | + dimension_extractor: How to access the dimensions (since this is a multi-dimensional array) from the initial `val`. |
| 97 | + """ |
| 98 | + super().__init__(val) |
| 99 | + |
| 100 | + self.data = data_extractor(self.val) |
| 101 | + dimensions: gdb.Value = dimension_extractor(self.val) |
| 102 | + |
| 103 | + num_dimensions: int = int(self.val.type.template_argument(1)) |
| 104 | + dimensions: Iterable[gdb.Value] = map(dimensions.__getitem__, range(num_dimensions)) |
| 105 | + self.dimensions: tuple[int] = tuple(map(int, dimensions)) |
| 106 | + |
| 107 | + def to_string(self) -> str: |
| 108 | + # Extracting the permutations from the type name (looks like the integer template parameters are optimized out) |
| 109 | + permutation = self.val.type.strip_typedefs().template_argument(2) |
| 110 | + if m := re.search(r"\d+(?:[ \t]*,[ \t]*\d+)*", str(permutation)): # Extract a list of integers separated with commas |
| 111 | + s = m.group() |
| 112 | + permutation: tuple[int, ...] = tuple(map(int, s.split(","))) |
| 113 | + if permutation != tuple(range(len(self.dimensions))): |
| 114 | + msg = f"Only sorted permutation is supported by pretty printers. " \ |
| 115 | + f"{permutation} is not sorted so the output of the pretty printers will be jumbled." |
| 116 | + logging.warning(msg) |
| 117 | + else: |
| 118 | + raise ValueError(f"Could not parse permutation for {permutation}.") |
| 119 | + |
| 120 | + dimensions = map(str, self.dimensions) |
| 121 | + return f'{self.real_type()} of shape [{", ".join(dimensions)}]' |
| 122 | + |
| 123 | + def children(self) -> Iterable[tuple[str, gdb.Value]]: |
| 124 | + d0, ds = self.dimensions[0], self.dimensions[1:] |
| 125 | + |
| 126 | + # The main idea of this loop is to build the multi-dimensional array type to the data (e.g. `int[2][3]`). |
| 127 | + # Then we'll cast the raw pointer into this n-d array and gdb will be able to manage it. |
| 128 | + array_type: gdb.Type = self.data.type.target() |
| 129 | + for d in reversed(ds): # Note that we ditch the first dimension from our loop in order to have it as first level children. |
| 130 | + array_type = array_type.array(d - 1) |
| 131 | + |
| 132 | + # We manage the first level children ourselves, so we need to manage the position of the data ourselves too. |
| 133 | + stride: int = math.prod(ds) |
| 134 | + |
| 135 | + for i in range(d0): |
| 136 | + array = (self.data + i * stride).dereference().cast(array_type) |
| 137 | + yield '[%d]' % i, array |
| 138 | + |
| 139 | + |
| 140 | +class ArrayPrinter(__ArrayPrinter): |
| 141 | + """Pretty-print for Array(View)""" |
| 142 | + |
| 143 | + def __init__(self, val: gdb.Value): |
| 144 | + super().__init__(val, lambda v: extract_buffer(v["m_dataBuffer"]).data(), lambda v: v["m_dims"]["data"]) |
| 145 | + |
| 146 | + |
| 147 | +class ArraySlicePrinter(__ArrayPrinter): |
| 148 | + """Pretty-print for ArraySlice""" |
| 149 | + |
| 150 | + def __init__(self, val: gdb.Value): |
| 151 | + super().__init__(val, lambda v: v["m_data"], lambda v: v["m_dims"]) |
| 152 | + |
| 153 | + |
| 154 | +class ArrayOfArraysPrinter(LvArrayPrinter): |
| 155 | + """Pretty-print for ArrayOfArrays(View)""" |
| 156 | + |
| 157 | + def __len__(self) -> int: |
| 158 | + return int(self.val['m_numArrays']) |
| 159 | + |
| 160 | + def to_string(self) -> str: |
| 161 | + return '%s of size %d' % (self.real_type(), len(self)) |
| 162 | + |
| 163 | + def children(self) -> Iterable[tuple[str, gdb.Value]]: |
| 164 | + # In this function, we are walking along the "sub" arrays ourselves. |
| 165 | + # To do this, we manipulate the raw pointer/offsets information ourselves. |
| 166 | + data = extract_buffer(self.val["m_values"]).data() |
| 167 | + offsets = extract_buffer(self.val["m_offsets"]) |
| 168 | + sizes = extract_buffer(self.val["m_sizes"]) |
| 169 | + for i in range(len(self)): # Iterating over all the "sub" arrays. |
| 170 | + # Converting a raw pointer `T*` to an equivalent type including the size `T[N]` that gdb will manage. |
| 171 | + array_type = data.type.target().array(sizes[i] - 1) |
| 172 | + array = (data + offsets[i]).dereference().cast(array_type) |
| 173 | + yield '[%d]' % i, array |
| 174 | + |
| 175 | + |
| 176 | +def build_array_printer(): |
| 177 | + pp = gdb.printing.RegexpCollectionPrettyPrinter("LvArray-arrays-shallow") |
| 178 | + pp.add_printer('LvArray::Array', '^LvArray::Array(View)?<.*>$', ArrayPrinter) |
| 179 | + pp.add_printer('LvArray::ArraySlice', '^LvArray::ArraySlice<.*>$', ArraySlicePrinter) |
| 180 | + pp.add_printer('LvArray::ArrayOfArrays', '^LvArray::ArrayOfArrays(View)?<.*>$', ArrayOfArraysPrinter) |
| 181 | + return pp |
| 182 | + |
| 183 | + |
| 184 | +try: |
| 185 | + import gdb.printing |
| 186 | + gdb.printing.register_pretty_printer(gdb.current_objfile(), build_array_printer()) |
| 187 | +except ImportError: |
| 188 | + logging.warning("Could not register LvArray pretty printers.") |
0 commit comments