summaryrefslogtreecommitdiff
path: root/gnu/llvm/utils/gdb-scripts/prettyprinters.py
blob: 1a549f875d4492936edf943f4e02cca0ba48a625 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import gdb.printing
class SmallStringPrinter:
  """Print an llvm::SmallString object."""

  def __init__(self, val):
    self.val = val

  def to_string(self):
    begin = self.val['BeginX']
    end = self.val['EndX']
    return begin.cast(gdb.lookup_type("char").pointer()).string(length = end - begin)

  def display_hint (self):
    return 'string'

class StringRefPrinter:
  """Print an llvm::StringRef object."""

  def __init__(self, val):
    self.val = val

  def to_string(self):
    return self.val['Data'].string(length =  self.val['Length'])

  def display_hint (self):
    return 'string'

class SmallVectorPrinter:
  """Print an llvm::SmallVector object."""

  class _iterator:
    def __init__(self, begin, end):
      self.cur = begin
      self.end = end
      self.count = 0

    def __iter__(self):
      return self

    def next(self):
      if self.cur == self.end:
        raise StopIteration
      count = self.count
      self.count = self.count + 1
      cur = self.cur
      self.cur = self.cur + 1
      return '[%d]' % count, cur.dereference()

    __next__ = next

  def __init__(self, val):
    self.val = val

  def children(self):
    t = self.val.type.template_argument(0).pointer()
    begin = self.val['BeginX'].cast(t)
    end = self.val['EndX'].cast(t)
    return self._iterator(begin, end)

  def to_string(self):
    t = self.val.type.template_argument(0).pointer()
    begin = self.val['BeginX'].cast(t)
    end = self.val['EndX'].cast(t)
    capacity = self.val['CapacityX'].cast(t)
    return 'llvm::SmallVector of length %d, capacity %d' % (end - begin, capacity - begin)

  def display_hint (self):
    return 'array'

class ArrayRefPrinter:
  """Print an llvm::ArrayRef object."""

  class _iterator:
    def __init__(self, begin, end):
      self.cur = begin
      self.end = end
      self.count = 0

    def __iter__(self):
      return self

    def next(self):
      if self.cur == self.end:
        raise StopIteration
      count = self.count
      self.count = self.count + 1
      cur = self.cur
      self.cur = self.cur + 1
      return '[%d]' % count, cur.dereference()

    __next__ = next

  def __init__(self, val):
    self.val = val

  def children(self):
    data = self.val['Data']
    return self._iterator(data, data + self.val['Length'])

  def to_string(self):
    return 'llvm::ArrayRef of length %d' % (self.val['Length'])

  def display_hint (self):
    return 'array'

class OptionalPrinter:
  """Print an llvm::Optional object."""

  def __init__(self, value):
    self.value = value

  class _iterator:
    def __init__(self, member, empty):
      self.member = member
      self.done = empty

    def __iter__(self):
      return self

    def next(self):
      if self.done:
        raise StopIteration
      self.done = True
      return ('value', self.member.dereference())

  def children(self):
    if not self.value['hasVal']:
      return self._iterator('', True)
    return self._iterator(self.value['storage']['buffer'].address.cast(self.value.type.template_argument(0).pointer()), False)

  def to_string(self):
    return 'llvm::Optional is %sinitialized' % ('' if self.value['hasVal'] else 'not ')

class DenseMapPrinter:
  "Print a DenseMap"

  class _iterator:
    def __init__(self, key_info_t, begin, end):
      self.key_info_t = key_info_t
      self.cur = begin
      self.end = end
      self.advancePastEmptyBuckets()
      self.first = True

    def __iter__(self):
      return self

    def advancePastEmptyBuckets(self):
      # disabled until the comments below can be addressed
      # keeping as notes/posterity/hints for future contributors
      return
      n = self.key_info_t.name
      is_equal = gdb.parse_and_eval(n + '::isEqual')
      empty = gdb.parse_and_eval(n + '::getEmptyKey()')
      tombstone = gdb.parse_and_eval(n + '::getTombstoneKey()')
      # the following is invalid, GDB fails with:
      #   Python Exception <class 'gdb.error'> Attempt to take address of value
      #   not located in memory.
      # because isEqual took parameter (for the unsigned long key I was testing)
      # by const ref, and GDB
      # It's also not entirely general - we should be accessing the "getFirst()"
      # member function, not the 'first' member variable, but I've yet to figure
      # out how to find/call member functions (especially (const) overloaded
      # ones) on a gdb.Value.
      while self.cur != self.end and (is_equal(self.cur.dereference()['first'], empty) or is_equal(self.cur.dereference()['first'], tombstone)):
        self.cur = self.cur + 1

    def next(self):
      if self.cur == self.end:
        raise StopIteration
      cur = self.cur
      v = cur.dereference()['first' if self.first else 'second']
      if not self.first:
        self.cur = self.cur + 1
        self.advancePastEmptyBuckets()
        self.first = True
      else:
        self.first = False
      return 'x', v

  def __init__(self, val):
    self.val = val

  def children(self):
    t = self.val.type.template_argument(3).pointer()
    begin = self.val['Buckets'].cast(t)
    end = (begin + self.val['NumBuckets']).cast(t)
    return self._iterator(self.val.type.template_argument(2), begin, end)

  def to_string(self):
    return 'llvm::DenseMap with %d elements' % (self.val['NumEntries'])

  def display_hint(self):
    return 'map'

class TwinePrinter:
  "Print a Twine"

  def __init__(self, val):
    self._val = val

  def display_hint(self):
    return 'string'

  def string_from_pretty_printer_lookup(self, val):
    '''Lookup the default pretty-printer for val and use it.

    If no pretty-printer is defined for the type of val, print an error and
    return a placeholder string.'''

    pp = gdb.default_visualizer(val)
    if pp:
      s = pp.to_string()

      # The pretty-printer may return a LazyString instead of an actual Python
      # string.  Convert it to a Python string.  However, GDB doesn't seem to
      # register the LazyString type, so we can't check
      # "type(s) == gdb.LazyString".
      if 'LazyString' in type(s).__name__:
        s = s.value().address.string()

    else:
      print(('No pretty printer for {} found. The resulting Twine ' +
             'representation will be incomplete.').format(val.type.name))
      s = '(missing {})'.format(val.type.name)

    return s

  def is_twine_kind(self, kind, expected):
    if not kind.endswith(expected):
      return False
    # apparently some GDB versions add the NodeKind:: namespace
    # (happens for me on GDB 7.11)
    return kind in ('llvm::Twine::' + expected,
                    'llvm::Twine::NodeKind::' + expected)

  def string_from_child(self, child, kind):
    '''Return the string representation of the Twine::Child child.'''

    if self.is_twine_kind(kind, 'EmptyKind') or self.is_twine_kind(kind, 'NullKind'):
      return ''

    if self.is_twine_kind(kind, 'TwineKind'):
      return self.string_from_twine_object(child['twine'].dereference())

    if self.is_twine_kind(kind, 'CStringKind'):
      return child['cString'].string()

    if self.is_twine_kind(kind, 'StdStringKind'):
      val = child['stdString'].dereference()
      return self.string_from_pretty_printer_lookup(val)

    if self.is_twine_kind(kind, 'StringRefKind'):
      val = child['stringRef'].dereference()
      pp = StringRefPrinter(val)
      return pp.to_string()

    if self.is_twine_kind(kind, 'SmallStringKind'):
      val = child['smallString'].dereference()
      pp = SmallStringPrinter(val)
      return pp.to_string()

    if self.is_twine_kind(kind, 'CharKind'):
      return chr(child['character'])

    if self.is_twine_kind(kind, 'DecUIKind'):
      return str(child['decUI'])

    if self.is_twine_kind(kind, 'DecIKind'):
      return str(child['decI'])

    if self.is_twine_kind(kind, 'DecULKind'):
      return str(child['decUL'].dereference())

    if self.is_twine_kind(kind, 'DecLKind'):
      return str(child['decL'].dereference())

    if self.is_twine_kind(kind, 'DecULLKind'):
      return str(child['decULL'].dereference())

    if self.is_twine_kind(kind, 'DecLLKind'):
      return str(child['decLL'].dereference())

    if self.is_twine_kind(kind, 'UHexKind'):
      val = child['uHex'].dereference()
      return hex(int(val))

    print(('Unhandled NodeKind {} in Twine pretty-printer. The result will be '
           'incomplete.').format(kind))

    return '(unhandled {})'.format(kind)

  def string_from_twine_object(self, twine):
    '''Return the string representation of the Twine object twine.'''

    lhs_str = ''
    rhs_str = ''

    lhs = twine['LHS']
    rhs = twine['RHS']
    lhs_kind = str(twine['LHSKind'])
    rhs_kind = str(twine['RHSKind'])

    lhs_str = self.string_from_child(lhs, lhs_kind)
    rhs_str = self.string_from_child(rhs, rhs_kind)

    return lhs_str + rhs_str

  def to_string(self):
    return self.string_from_twine_object(self._val)

pp = gdb.printing.RegexpCollectionPrettyPrinter("LLVMSupport")
pp.add_printer('llvm::SmallString', '^llvm::SmallString<.*>$', SmallStringPrinter)
pp.add_printer('llvm::StringRef', '^llvm::StringRef$', StringRefPrinter)
pp.add_printer('llvm::SmallVectorImpl', '^llvm::SmallVector(Impl)?<.*>$', SmallVectorPrinter)
pp.add_printer('llvm::ArrayRef', '^llvm::(Const)?ArrayRef<.*>$', ArrayRefPrinter)
pp.add_printer('llvm::Optional', '^llvm::Optional<.*>$', OptionalPrinter)
pp.add_printer('llvm::DenseMap', '^llvm::DenseMap<.*>$', DenseMapPrinter)
pp.add_printer('llvm::Twine', '^llvm::Twine$', TwinePrinter)
gdb.printing.register_pretty_printer(gdb.current_objfile(), pp)