prettyprinters.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. from __future__ import print_function
  2. import gdb.printing
  3. class Iterator:
  4. def __iter__(self):
  5. return self
  6. # Python 2 compatibility
  7. def next(self):
  8. return self.__next__()
  9. def children(self):
  10. return self
  11. def escape_bytes(val, l):
  12. return '"' + val.string(encoding='Latin-1', length=l).encode('unicode_escape').decode() + '"'
  13. class SmallStringPrinter:
  14. """Print an llvm::SmallString object."""
  15. def __init__(self, val):
  16. self.val = val
  17. def to_string(self):
  18. begin = self.val['BeginX']
  19. return escape_bytes(begin.cast(gdb.lookup_type('char').pointer()), self.val['Size'])
  20. class StringRefPrinter:
  21. """Print an llvm::StringRef object."""
  22. def __init__(self, val):
  23. self.val = val
  24. def to_string(self):
  25. return escape_bytes(self.val['Data'], self.val['Length'])
  26. class SmallVectorPrinter(Iterator):
  27. """Print an llvm::SmallVector object."""
  28. def __init__(self, val):
  29. self.val = val
  30. t = val.type.template_argument(0).pointer()
  31. self.begin = val['BeginX'].cast(t)
  32. self.size = val['Size']
  33. self.i = 0
  34. def __next__(self):
  35. if self.i == self.size:
  36. raise StopIteration
  37. ret = '[{}]'.format(self.i), (self.begin+self.i).dereference()
  38. self.i += 1
  39. return ret
  40. def to_string(self):
  41. return 'llvm::SmallVector of Size {}, Capacity {}'.format(self.size, self.val['Capacity'])
  42. def display_hint (self):
  43. return 'array'
  44. class ArrayRefPrinter:
  45. """Print an llvm::ArrayRef object."""
  46. class _iterator:
  47. def __init__(self, begin, end):
  48. self.cur = begin
  49. self.end = end
  50. self.count = 0
  51. def __iter__(self):
  52. return self
  53. def next(self):
  54. if self.cur == self.end:
  55. raise StopIteration
  56. count = self.count
  57. self.count = self.count + 1
  58. cur = self.cur
  59. self.cur = self.cur + 1
  60. return '[%d]' % count, cur.dereference()
  61. __next__ = next
  62. def __init__(self, val):
  63. self.val = val
  64. __next__ = next
  65. def children(self):
  66. data = self.val['Data']
  67. return self._iterator(data, data + self.val['Length'])
  68. def to_string(self):
  69. return 'llvm::ArrayRef of length %d' % (self.val['Length'])
  70. def display_hint (self):
  71. return 'array'
  72. class ExpectedPrinter(Iterator):
  73. """Print an llvm::Expected object."""
  74. def __init__(self, val):
  75. self.val = val
  76. def __next__(self):
  77. val = self.val
  78. if val is None:
  79. raise StopIteration
  80. self.val = None
  81. if val['HasError']:
  82. return ('error', val['ErrorStorage'].address.cast(
  83. gdb.lookup_type('llvm::ErrorInfoBase').pointer()).dereference())
  84. return ('value', val['TStorage'].address.cast(
  85. val.type.template_argument(0).pointer()).dereference())
  86. def to_string(self):
  87. return 'llvm::Expected{}'.format(' is error' if self.val['HasError'] else '')
  88. class OptionalPrinter(Iterator):
  89. """Print an llvm::Optional object."""
  90. def __init__(self, val):
  91. self.val = val
  92. def __next__(self):
  93. val = self.val
  94. if val is None:
  95. raise StopIteration
  96. self.val = None
  97. if not val['Storage']['hasVal']:
  98. raise StopIteration
  99. return ('value', val['Storage']['storage']['buffer'].address.cast(
  100. val.type.template_argument(0).pointer()).dereference())
  101. def to_string(self):
  102. return 'llvm::Optional{}'.format('' if self.val['Storage']['hasVal'] else ' is not initialized')
  103. class DenseMapPrinter:
  104. "Print a DenseMap"
  105. class _iterator:
  106. def __init__(self, key_info_t, begin, end):
  107. self.key_info_t = key_info_t
  108. self.cur = begin
  109. self.end = end
  110. self.advancePastEmptyBuckets()
  111. self.first = True
  112. def __iter__(self):
  113. return self
  114. def advancePastEmptyBuckets(self):
  115. # disabled until the comments below can be addressed
  116. # keeping as notes/posterity/hints for future contributors
  117. return
  118. n = self.key_info_t.name
  119. is_equal = gdb.parse_and_eval(n + '::isEqual')
  120. empty = gdb.parse_and_eval(n + '::getEmptyKey()')
  121. tombstone = gdb.parse_and_eval(n + '::getTombstoneKey()')
  122. # the following is invalid, GDB fails with:
  123. # Python Exception <class 'gdb.error'> Attempt to take address of value
  124. # not located in memory.
  125. # because isEqual took parameter (for the unsigned long key I was testing)
  126. # by const ref, and GDB
  127. # It's also not entirely general - we should be accessing the "getFirst()"
  128. # member function, not the 'first' member variable, but I've yet to figure
  129. # out how to find/call member functions (especially (const) overloaded
  130. # ones) on a gdb.Value.
  131. while self.cur != self.end and (is_equal(self.cur.dereference()['first'], empty) or is_equal(self.cur.dereference()['first'], tombstone)):
  132. self.cur = self.cur + 1
  133. def next(self):
  134. if self.cur == self.end:
  135. raise StopIteration
  136. cur = self.cur
  137. v = cur.dereference()['first' if self.first else 'second']
  138. if not self.first:
  139. self.cur = self.cur + 1
  140. self.advancePastEmptyBuckets()
  141. self.first = True
  142. else:
  143. self.first = False
  144. return 'x', v
  145. __next__ = next
  146. def __init__(self, val):
  147. self.val = val
  148. def children(self):
  149. t = self.val.type.template_argument(3).pointer()
  150. begin = self.val['Buckets'].cast(t)
  151. end = (begin + self.val['NumBuckets']).cast(t)
  152. return self._iterator(self.val.type.template_argument(2), begin, end)
  153. def to_string(self):
  154. return 'llvm::DenseMap with %d elements' % (self.val['NumEntries'])
  155. def display_hint(self):
  156. return 'map'
  157. class TwinePrinter:
  158. "Print a Twine"
  159. def __init__(self, val):
  160. self._val = val
  161. def display_hint(self):
  162. return 'string'
  163. def string_from_pretty_printer_lookup(self, val):
  164. '''Lookup the default pretty-printer for val and use it.
  165. If no pretty-printer is defined for the type of val, print an error and
  166. return a placeholder string.'''
  167. pp = gdb.default_visualizer(val)
  168. if pp:
  169. s = pp.to_string()
  170. # The pretty-printer may return a LazyString instead of an actual Python
  171. # string. Convert it to a Python string. However, GDB doesn't seem to
  172. # register the LazyString type, so we can't check
  173. # "type(s) == gdb.LazyString".
  174. if 'LazyString' in type(s).__name__:
  175. s = s.value().address.string()
  176. else:
  177. print(('No pretty printer for {} found. The resulting Twine ' +
  178. 'representation will be incomplete.').format(val.type.name))
  179. s = '(missing {})'.format(val.type.name)
  180. return s
  181. def is_twine_kind(self, kind, expected):
  182. if not kind.endswith(expected):
  183. return False
  184. # apparently some GDB versions add the NodeKind:: namespace
  185. # (happens for me on GDB 7.11)
  186. return kind in ('llvm::Twine::' + expected,
  187. 'llvm::Twine::NodeKind::' + expected)
  188. def string_from_child(self, child, kind):
  189. '''Return the string representation of the Twine::Child child.'''
  190. if self.is_twine_kind(kind, 'EmptyKind') or self.is_twine_kind(kind, 'NullKind'):
  191. return ''
  192. if self.is_twine_kind(kind, 'TwineKind'):
  193. return self.string_from_twine_object(child['twine'].dereference())
  194. if self.is_twine_kind(kind, 'CStringKind'):
  195. return child['cString'].string()
  196. if self.is_twine_kind(kind, 'StdStringKind'):
  197. val = child['stdString'].dereference()
  198. return self.string_from_pretty_printer_lookup(val)
  199. if self.is_twine_kind(kind, 'StringRefKind'):
  200. val = child['stringRef'].dereference()
  201. pp = StringRefPrinter(val)
  202. return pp.to_string()
  203. if self.is_twine_kind(kind, 'SmallStringKind'):
  204. val = child['smallString'].dereference()
  205. pp = SmallStringPrinter(val)
  206. return pp.to_string()
  207. if self.is_twine_kind(kind, 'CharKind'):
  208. return chr(child['character'])
  209. if self.is_twine_kind(kind, 'DecUIKind'):
  210. return str(child['decUI'])
  211. if self.is_twine_kind(kind, 'DecIKind'):
  212. return str(child['decI'])
  213. if self.is_twine_kind(kind, 'DecULKind'):
  214. return str(child['decUL'].dereference())
  215. if self.is_twine_kind(kind, 'DecLKind'):
  216. return str(child['decL'].dereference())
  217. if self.is_twine_kind(kind, 'DecULLKind'):
  218. return str(child['decULL'].dereference())
  219. if self.is_twine_kind(kind, 'DecLLKind'):
  220. return str(child['decLL'].dereference())
  221. if self.is_twine_kind(kind, 'UHexKind'):
  222. val = child['uHex'].dereference()
  223. return hex(int(val))
  224. print(('Unhandled NodeKind {} in Twine pretty-printer. The result will be '
  225. 'incomplete.').format(kind))
  226. return '(unhandled {})'.format(kind)
  227. def string_from_twine_object(self, twine):
  228. '''Return the string representation of the Twine object twine.'''
  229. lhs_str = ''
  230. rhs_str = ''
  231. lhs = twine['LHS']
  232. rhs = twine['RHS']
  233. lhs_kind = str(twine['LHSKind'])
  234. rhs_kind = str(twine['RHSKind'])
  235. lhs_str = self.string_from_child(lhs, lhs_kind)
  236. rhs_str = self.string_from_child(rhs, rhs_kind)
  237. return lhs_str + rhs_str
  238. def to_string(self):
  239. return self.string_from_twine_object(self._val)
  240. pp = gdb.printing.RegexpCollectionPrettyPrinter("LLVMSupport")
  241. pp.add_printer('llvm::SmallString', '^llvm::SmallString<.*>$', SmallStringPrinter)
  242. pp.add_printer('llvm::StringRef', '^llvm::StringRef$', StringRefPrinter)
  243. pp.add_printer('llvm::SmallVectorImpl', '^llvm::SmallVector(Impl)?<.*>$', SmallVectorPrinter)
  244. pp.add_printer('llvm::ArrayRef', '^llvm::(Const)?ArrayRef<.*>$', ArrayRefPrinter)
  245. pp.add_printer('llvm::Expected', '^llvm::Expected<.*>$', ExpectedPrinter)
  246. pp.add_printer('llvm::Optional', '^llvm::Optional<.*>$', OptionalPrinter)
  247. pp.add_printer('llvm::DenseMap', '^llvm::DenseMap<.*>$', DenseMapPrinter)
  248. pp.add_printer('llvm::Twine', '^llvm::Twine$', TwinePrinter)
  249. gdb.printing.register_pretty_printer(gdb.current_objfile(), pp)