Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1982 lines
73KB

  1. # Pretty-printers for libstdc++.
  2. # Copyright (C) 2008-2020 Free Software Foundation, Inc.
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. import gdb
  16. import itertools
  17. import re
  18. import sys
  19. ### Python 2 + Python 3 compatibility code
  20. # Resources about compatibility:
  21. #
  22. # * <http://pythonhosted.org/six/>: Documentation of the "six" module
  23. # FIXME: The handling of e.g. std::basic_string (at least on char)
  24. # probably needs updating to work with Python 3's new string rules.
  25. #
  26. # In particular, Python 3 has a separate type (called byte) for
  27. # bytestrings, and a special b"" syntax for the byte literals; the old
  28. # str() type has been redefined to always store Unicode text.
  29. #
  30. # We probably can't do much about this until this GDB PR is addressed:
  31. # <https://sourceware.org/bugzilla/show_bug.cgi?id=17138>
  32. if sys.version_info[0] > 2:
  33. ### Python 3 stuff
  34. Iterator = object
  35. # Python 3 folds these into the normal functions.
  36. imap = map
  37. izip = zip
  38. # Also, int subsumes long
  39. long = int
  40. else:
  41. ### Python 2 stuff
  42. class Iterator:
  43. """Compatibility mixin for iterators
  44. Instead of writing next() methods for iterators, write
  45. __next__() methods and use this mixin to make them work in
  46. Python 2 as well as Python 3.
  47. Idea stolen from the "six" documentation:
  48. <http://pythonhosted.org/six/#six.Iterator>
  49. """
  50. def next(self):
  51. return self.__next__()
  52. # In Python 2, we still need these from itertools
  53. from itertools import imap, izip
  54. # Try to use the new-style pretty-printing if available.
  55. _use_gdb_pp = True
  56. try:
  57. import gdb.printing
  58. except ImportError:
  59. _use_gdb_pp = False
  60. # Try to install type-printers.
  61. _use_type_printing = False
  62. try:
  63. import gdb.types
  64. if hasattr(gdb.types, 'TypePrinter'):
  65. _use_type_printing = True
  66. except ImportError:
  67. pass
  68. # Starting with the type ORIG, search for the member type NAME. This
  69. # handles searching upward through superclasses. This is needed to
  70. # work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
  71. def find_type(orig, name):
  72. typ = orig.strip_typedefs()
  73. while True:
  74. # Strip cv-qualifiers. PR 67440.
  75. search = '%s::%s' % (typ.unqualified(), name)
  76. try:
  77. return gdb.lookup_type(search)
  78. except RuntimeError:
  79. pass
  80. # The type was not found, so try the superclass. We only need
  81. # to check the first superclass, so we don't bother with
  82. # anything fancier here.
  83. fields = typ.fields()
  84. if len(fields) and fields[0].is_base_class:
  85. typ = fields[0].type
  86. else:
  87. raise ValueError("Cannot find type %s::%s" % (str(orig), name))
  88. _versioned_namespace = '__8::'
  89. def lookup_templ_spec(templ, *args):
  90. """
  91. Lookup template specialization templ<args...>
  92. """
  93. t = '{}<{}>'.format(templ, ', '.join([str(a) for a in args]))
  94. try:
  95. return gdb.lookup_type(t)
  96. except gdb.error as e:
  97. # Type not found, try again in versioned namespace.
  98. global _versioned_namespace
  99. if _versioned_namespace and _versioned_namespace not in templ:
  100. t = t.replace('::', '::' + _versioned_namespace, 1)
  101. try:
  102. return gdb.lookup_type(t)
  103. except gdb.error:
  104. # If that also fails, rethrow the original exception
  105. pass
  106. raise e
  107. # Use this to find container node types instead of find_type,
  108. # see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91997 for details.
  109. def lookup_node_type(nodename, containertype):
  110. """
  111. Lookup specialization of template NODENAME corresponding to CONTAINERTYPE.
  112. e.g. if NODENAME is '_List_node' and CONTAINERTYPE is std::list<int>
  113. then return the type std::_List_node<int>.
  114. Returns None if not found.
  115. """
  116. # If nodename is unqualified, assume it's in namespace std.
  117. if '::' not in nodename:
  118. nodename = 'std::' + nodename
  119. try:
  120. valtype = find_type(containertype, 'value_type')
  121. except:
  122. valtype = containertype.template_argument(0)
  123. valtype = valtype.strip_typedefs()
  124. try:
  125. return lookup_templ_spec(nodename, valtype)
  126. except gdb.error as e:
  127. # For debug mode containers the node is in std::__cxx1998.
  128. if is_member_of_namespace(nodename, 'std'):
  129. if is_member_of_namespace(containertype, 'std::__cxx1998',
  130. 'std::__debug', '__gnu_debug'):
  131. nodename = nodename.replace('::', '::__cxx1998::', 1)
  132. try:
  133. return lookup_templ_spec(nodename, valtype)
  134. except gdb.error:
  135. pass
  136. return None
  137. def is_member_of_namespace(typ, *namespaces):
  138. """
  139. Test whether a type is a member of one of the specified namespaces.
  140. The type can be specified as a string or a gdb.Type object.
  141. """
  142. if type(typ) is gdb.Type:
  143. typ = str(typ)
  144. typ = strip_versioned_namespace(typ)
  145. for namespace in namespaces:
  146. if typ.startswith(namespace + '::'):
  147. return True
  148. return False
  149. def is_specialization_of(x, template_name):
  150. "Test if a type is a given template instantiation."
  151. global _versioned_namespace
  152. if type(x) is gdb.Type:
  153. x = x.tag
  154. if _versioned_namespace:
  155. return re.match('^std::(%s)?%s<.*>$' % (_versioned_namespace, template_name), x) is not None
  156. return re.match('^std::%s<.*>$' % template_name, x) is not None
  157. def strip_versioned_namespace(typename):
  158. global _versioned_namespace
  159. if _versioned_namespace:
  160. return typename.replace(_versioned_namespace, '')
  161. return typename
  162. def strip_inline_namespaces(type_str):
  163. "Remove known inline namespaces from the canonical name of a type."
  164. type_str = strip_versioned_namespace(type_str)
  165. type_str = type_str.replace('std::__cxx11::', 'std::')
  166. expt_ns = 'std::experimental::'
  167. for lfts_ns in ('fundamentals_v1', 'fundamentals_v2'):
  168. type_str = type_str.replace(expt_ns+lfts_ns+'::', expt_ns)
  169. fs_ns = expt_ns + 'filesystem::'
  170. type_str = type_str.replace(fs_ns+'v1::', fs_ns)
  171. return type_str
  172. def get_template_arg_list(type_obj):
  173. "Return a type's template arguments as a list"
  174. n = 0
  175. template_args = []
  176. while True:
  177. try:
  178. template_args.append(type_obj.template_argument(n))
  179. except:
  180. return template_args
  181. n += 1
  182. class SmartPtrIterator(Iterator):
  183. "An iterator for smart pointer types with a single 'child' value"
  184. def __init__(self, val):
  185. self.val = val
  186. def __iter__(self):
  187. return self
  188. def __next__(self):
  189. if self.val is None:
  190. raise StopIteration
  191. self.val, val = None, self.val
  192. return ('get()', val)
  193. class SharedPointerPrinter:
  194. "Print a shared_ptr or weak_ptr"
  195. def __init__ (self, typename, val):
  196. self.typename = strip_versioned_namespace(typename)
  197. self.val = val
  198. self.pointer = val['_M_ptr']
  199. def children (self):
  200. return SmartPtrIterator(self.pointer)
  201. def to_string (self):
  202. state = 'empty'
  203. refcounts = self.val['_M_refcount']['_M_pi']
  204. if refcounts != 0:
  205. usecount = refcounts['_M_use_count']
  206. weakcount = refcounts['_M_weak_count']
  207. if usecount == 0:
  208. state = 'expired, weak count %d' % weakcount
  209. else:
  210. state = 'use count %d, weak count %d' % (usecount, weakcount - 1)
  211. return '%s<%s> (%s)' % (self.typename, str(self.val.type.template_argument(0)), state)
  212. class UniquePointerPrinter:
  213. "Print a unique_ptr"
  214. def __init__ (self, typename, val):
  215. self.val = val
  216. impl_type = val.type.fields()[0].type.strip_typedefs()
  217. # Check for new implementations first:
  218. if is_specialization_of(impl_type, '__uniq_ptr_data') \
  219. or is_specialization_of(impl_type, '__uniq_ptr_impl'):
  220. tuple_member = val['_M_t']['_M_t']
  221. elif is_specialization_of(impl_type, 'tuple'):
  222. tuple_member = val['_M_t']
  223. else:
  224. raise ValueError("Unsupported implementation for unique_ptr: %s" % str(impl_type))
  225. tuple_impl_type = tuple_member.type.fields()[0].type # _Tuple_impl
  226. tuple_head_type = tuple_impl_type.fields()[1].type # _Head_base
  227. head_field = tuple_head_type.fields()[0]
  228. if head_field.name == '_M_head_impl':
  229. self.pointer = tuple_member['_M_head_impl']
  230. elif head_field.is_base_class:
  231. self.pointer = tuple_member.cast(head_field.type)
  232. else:
  233. raise ValueError("Unsupported implementation for tuple in unique_ptr: %s" % str(impl_type))
  234. def children (self):
  235. return SmartPtrIterator(self.pointer)
  236. def to_string (self):
  237. return ('std::unique_ptr<%s>' % (str(self.val.type.template_argument(0))))
  238. def get_value_from_aligned_membuf(buf, valtype):
  239. """Returns the value held in a __gnu_cxx::__aligned_membuf."""
  240. return buf['_M_storage'].address.cast(valtype.pointer()).dereference()
  241. def get_value_from_list_node(node):
  242. """Returns the value held in an _List_node<_Val>"""
  243. try:
  244. member = node.type.fields()[1].name
  245. if member == '_M_data':
  246. # C++03 implementation, node contains the value as a member
  247. return node['_M_data']
  248. elif member == '_M_storage':
  249. # C++11 implementation, node stores value in __aligned_membuf
  250. valtype = node.type.template_argument(0)
  251. return get_value_from_aligned_membuf(node['_M_storage'], valtype)
  252. except:
  253. pass
  254. raise ValueError("Unsupported implementation for %s" % str(node.type))
  255. class StdListPrinter:
  256. "Print a std::list"
  257. class _iterator(Iterator):
  258. def __init__(self, nodetype, head):
  259. self.nodetype = nodetype
  260. self.base = head['_M_next']
  261. self.head = head.address
  262. self.count = 0
  263. def __iter__(self):
  264. return self
  265. def __next__(self):
  266. if self.base == self.head:
  267. raise StopIteration
  268. elt = self.base.cast(self.nodetype).dereference()
  269. self.base = elt['_M_next']
  270. count = self.count
  271. self.count = self.count + 1
  272. val = get_value_from_list_node(elt)
  273. return ('[%d]' % count, val)
  274. def __init__(self, typename, val):
  275. self.typename = strip_versioned_namespace(typename)
  276. self.val = val
  277. def children(self):
  278. nodetype = lookup_node_type('_List_node', self.val.type).pointer()
  279. return self._iterator(nodetype, self.val['_M_impl']['_M_node'])
  280. def to_string(self):
  281. headnode = self.val['_M_impl']['_M_node']
  282. if headnode['_M_next'] == headnode.address:
  283. return 'empty %s' % (self.typename)
  284. return '%s' % (self.typename)
  285. class NodeIteratorPrinter:
  286. def __init__(self, typename, val, contname, nodename):
  287. self.val = val
  288. self.typename = typename
  289. self.contname = contname
  290. self.nodetype = lookup_node_type(nodename, val.type)
  291. def to_string(self):
  292. if not self.val['_M_node']:
  293. return 'non-dereferenceable iterator for std::%s' % (self.contname)
  294. node = self.val['_M_node'].cast(self.nodetype.pointer()).dereference()
  295. return str(get_value_from_list_node(node))
  296. class StdListIteratorPrinter(NodeIteratorPrinter):
  297. "Print std::list::iterator"
  298. def __init__(self, typename, val):
  299. NodeIteratorPrinter.__init__(self, typename, val, 'list', '_List_node')
  300. class StdFwdListIteratorPrinter(NodeIteratorPrinter):
  301. "Print std::forward_list::iterator"
  302. def __init__(self, typename, val):
  303. NodeIteratorPrinter.__init__(self, typename, val, 'forward_list',
  304. '_Fwd_list_node')
  305. class StdSlistPrinter:
  306. "Print a __gnu_cxx::slist"
  307. class _iterator(Iterator):
  308. def __init__(self, nodetype, head):
  309. self.nodetype = nodetype
  310. self.base = head['_M_head']['_M_next']
  311. self.count = 0
  312. def __iter__(self):
  313. return self
  314. def __next__(self):
  315. if self.base == 0:
  316. raise StopIteration
  317. elt = self.base.cast(self.nodetype).dereference()
  318. self.base = elt['_M_next']
  319. count = self.count
  320. self.count = self.count + 1
  321. return ('[%d]' % count, elt['_M_data'])
  322. def __init__(self, typename, val):
  323. self.val = val
  324. def children(self):
  325. nodetype = lookup_node_type('__gnu_cxx::_Slist_node', self.val.type)
  326. return self._iterator(nodetype.pointer(), self.val)
  327. def to_string(self):
  328. if self.val['_M_head']['_M_next'] == 0:
  329. return 'empty __gnu_cxx::slist'
  330. return '__gnu_cxx::slist'
  331. class StdSlistIteratorPrinter:
  332. "Print __gnu_cxx::slist::iterator"
  333. def __init__(self, typename, val):
  334. self.val = val
  335. def to_string(self):
  336. if not self.val['_M_node']:
  337. return 'non-dereferenceable iterator for __gnu_cxx::slist'
  338. nodetype = lookup_node_type('__gnu_cxx::_Slist_node', self.val.type).pointer()
  339. return str(self.val['_M_node'].cast(nodetype).dereference()['_M_data'])
  340. class StdVectorPrinter:
  341. "Print a std::vector"
  342. class _iterator(Iterator):
  343. def __init__ (self, start, finish, bitvec):
  344. self.bitvec = bitvec
  345. if bitvec:
  346. self.item = start['_M_p']
  347. self.so = start['_M_offset']
  348. self.finish = finish['_M_p']
  349. self.fo = finish['_M_offset']
  350. itype = self.item.dereference().type
  351. self.isize = 8 * itype.sizeof
  352. else:
  353. self.item = start
  354. self.finish = finish
  355. self.count = 0
  356. def __iter__(self):
  357. return self
  358. def __next__(self):
  359. count = self.count
  360. self.count = self.count + 1
  361. if self.bitvec:
  362. if self.item == self.finish and self.so >= self.fo:
  363. raise StopIteration
  364. elt = bool(self.item.dereference() & (1 << self.so))
  365. self.so = self.so + 1
  366. if self.so >= self.isize:
  367. self.item = self.item + 1
  368. self.so = 0
  369. return ('[%d]' % count, elt)
  370. else:
  371. if self.item == self.finish:
  372. raise StopIteration
  373. elt = self.item.dereference()
  374. self.item = self.item + 1
  375. return ('[%d]' % count, elt)
  376. def __init__(self, typename, val):
  377. self.typename = strip_versioned_namespace(typename)
  378. self.val = val
  379. self.is_bool = val.type.template_argument(0).code == gdb.TYPE_CODE_BOOL
  380. def children(self):
  381. return self._iterator(self.val['_M_impl']['_M_start'],
  382. self.val['_M_impl']['_M_finish'],
  383. self.is_bool)
  384. def to_string(self):
  385. start = self.val['_M_impl']['_M_start']
  386. finish = self.val['_M_impl']['_M_finish']
  387. end = self.val['_M_impl']['_M_end_of_storage']
  388. if self.is_bool:
  389. start = self.val['_M_impl']['_M_start']['_M_p']
  390. so = self.val['_M_impl']['_M_start']['_M_offset']
  391. finish = self.val['_M_impl']['_M_finish']['_M_p']
  392. fo = self.val['_M_impl']['_M_finish']['_M_offset']
  393. itype = start.dereference().type
  394. bl = 8 * itype.sizeof
  395. length = (bl - so) + bl * ((finish - start) - 1) + fo
  396. capacity = bl * (end - start)
  397. return ('%s<bool> of length %d, capacity %d'
  398. % (self.typename, int (length), int (capacity)))
  399. else:
  400. return ('%s of length %d, capacity %d'
  401. % (self.typename, int (finish - start), int (end - start)))
  402. def display_hint(self):
  403. return 'array'
  404. class StdVectorIteratorPrinter:
  405. "Print std::vector::iterator"
  406. def __init__(self, typename, val):
  407. self.val = val
  408. def to_string(self):
  409. if not self.val['_M_current']:
  410. return 'non-dereferenceable iterator for std::vector'
  411. return str(self.val['_M_current'].dereference())
  412. # TODO add printer for vector<bool>'s _Bit_iterator and _Bit_const_iterator
  413. class StdTuplePrinter:
  414. "Print a std::tuple"
  415. class _iterator(Iterator):
  416. @staticmethod
  417. def _is_nonempty_tuple (nodes):
  418. if len (nodes) == 2:
  419. if is_specialization_of (nodes[1].type, '__tuple_base'):
  420. return True
  421. elif len (nodes) == 1:
  422. return True
  423. elif len (nodes) == 0:
  424. return False
  425. raise ValueError("Top of tuple tree does not consist of a single node.")
  426. def __init__ (self, head):
  427. self.head = head
  428. # Set the base class as the initial head of the
  429. # tuple.
  430. nodes = self.head.type.fields ()
  431. if self._is_nonempty_tuple (nodes):
  432. # Set the actual head to the first pair.
  433. self.head = self.head.cast (nodes[0].type)
  434. self.count = 0
  435. def __iter__ (self):
  436. return self
  437. def __next__ (self):
  438. # Check for further recursions in the inheritance tree.
  439. # For a GCC 5+ tuple self.head is None after visiting all nodes:
  440. if not self.head:
  441. raise StopIteration
  442. nodes = self.head.type.fields ()
  443. # For a GCC 4.x tuple there is a final node with no fields:
  444. if len (nodes) == 0:
  445. raise StopIteration
  446. # Check that this iteration has an expected structure.
  447. if len (nodes) > 2:
  448. raise ValueError("Cannot parse more than 2 nodes in a tuple tree.")
  449. if len (nodes) == 1:
  450. # This is the last node of a GCC 5+ std::tuple.
  451. impl = self.head.cast (nodes[0].type)
  452. self.head = None
  453. else:
  454. # Either a node before the last node, or the last node of
  455. # a GCC 4.x tuple (which has an empty parent).
  456. # - Left node is the next recursion parent.
  457. # - Right node is the actual class contained in the tuple.
  458. # Process right node.
  459. impl = self.head.cast (nodes[1].type)
  460. # Process left node and set it as head.
  461. self.head = self.head.cast (nodes[0].type)
  462. self.count = self.count + 1
  463. # Finally, check the implementation. If it is
  464. # wrapped in _M_head_impl return that, otherwise return
  465. # the value "as is".
  466. fields = impl.type.fields ()
  467. if len (fields) < 1 or fields[0].name != "_M_head_impl":
  468. return ('[%d]' % self.count, impl)
  469. else:
  470. return ('[%d]' % self.count, impl['_M_head_impl'])
  471. def __init__ (self, typename, val):
  472. self.typename = strip_versioned_namespace(typename)
  473. self.val = val;
  474. def children (self):
  475. return self._iterator (self.val)
  476. def to_string (self):
  477. if len (self.val.type.fields ()) == 0:
  478. return 'empty %s' % (self.typename)
  479. return '%s containing' % (self.typename)
  480. class StdStackOrQueuePrinter:
  481. "Print a std::stack or std::queue"
  482. def __init__ (self, typename, val):
  483. self.typename = strip_versioned_namespace(typename)
  484. self.visualizer = gdb.default_visualizer(val['c'])
  485. def children (self):
  486. return self.visualizer.children()
  487. def to_string (self):
  488. return '%s wrapping: %s' % (self.typename,
  489. self.visualizer.to_string())
  490. def display_hint (self):
  491. if hasattr (self.visualizer, 'display_hint'):
  492. return self.visualizer.display_hint ()
  493. return None
  494. class RbtreeIterator(Iterator):
  495. """
  496. Turn an RB-tree-based container (std::map, std::set etc.) into
  497. a Python iterable object.
  498. """
  499. def __init__(self, rbtree):
  500. self.size = rbtree['_M_t']['_M_impl']['_M_node_count']
  501. self.node = rbtree['_M_t']['_M_impl']['_M_header']['_M_left']
  502. self.count = 0
  503. def __iter__(self):
  504. return self
  505. def __len__(self):
  506. return int (self.size)
  507. def __next__(self):
  508. if self.count == self.size:
  509. raise StopIteration
  510. result = self.node
  511. self.count = self.count + 1
  512. if self.count < self.size:
  513. # Compute the next node.
  514. node = self.node
  515. if node.dereference()['_M_right']:
  516. node = node.dereference()['_M_right']
  517. while node.dereference()['_M_left']:
  518. node = node.dereference()['_M_left']
  519. else:
  520. parent = node.dereference()['_M_parent']
  521. while node == parent.dereference()['_M_right']:
  522. node = parent
  523. parent = parent.dereference()['_M_parent']
  524. if node.dereference()['_M_right'] != parent:
  525. node = parent
  526. self.node = node
  527. return result
  528. def get_value_from_Rb_tree_node(node):
  529. """Returns the value held in an _Rb_tree_node<_Val>"""
  530. try:
  531. member = node.type.fields()[1].name
  532. if member == '_M_value_field':
  533. # C++03 implementation, node contains the value as a member
  534. return node['_M_value_field']
  535. elif member == '_M_storage':
  536. # C++11 implementation, node stores value in __aligned_membuf
  537. valtype = node.type.template_argument(0)
  538. return get_value_from_aligned_membuf(node['_M_storage'], valtype)
  539. except:
  540. pass
  541. raise ValueError("Unsupported implementation for %s" % str(node.type))
  542. # This is a pretty printer for std::_Rb_tree_iterator (which is
  543. # std::map::iterator), and has nothing to do with the RbtreeIterator
  544. # class above.
  545. class StdRbtreeIteratorPrinter:
  546. "Print std::map::iterator, std::set::iterator, etc."
  547. def __init__ (self, typename, val):
  548. self.val = val
  549. nodetype = lookup_node_type('_Rb_tree_node', self.val.type)
  550. self.link_type = nodetype.pointer()
  551. def to_string (self):
  552. if not self.val['_M_node']:
  553. return 'non-dereferenceable iterator for associative container'
  554. node = self.val['_M_node'].cast(self.link_type).dereference()
  555. return str(get_value_from_Rb_tree_node(node))
  556. class StdDebugIteratorPrinter:
  557. "Print a debug enabled version of an iterator"
  558. def __init__ (self, typename, val):
  559. self.val = val
  560. # Just strip away the encapsulating __gnu_debug::_Safe_iterator
  561. # and return the wrapped iterator value.
  562. def to_string (self):
  563. base_type = gdb.lookup_type('__gnu_debug::_Safe_iterator_base')
  564. itype = self.val.type.template_argument(0)
  565. safe_seq = self.val.cast(base_type)['_M_sequence']
  566. if not safe_seq:
  567. return str(self.val.cast(itype))
  568. if self.val['_M_version'] != safe_seq['_M_version']:
  569. return "invalid iterator"
  570. return str(self.val.cast(itype))
  571. def num_elements(num):
  572. """Return either "1 element" or "N elements" depending on the argument."""
  573. return '1 element' if num == 1 else '%d elements' % num
  574. class StdMapPrinter:
  575. "Print a std::map or std::multimap"
  576. # Turn an RbtreeIterator into a pretty-print iterator.
  577. class _iter(Iterator):
  578. def __init__(self, rbiter, type):
  579. self.rbiter = rbiter
  580. self.count = 0
  581. self.type = type
  582. def __iter__(self):
  583. return self
  584. def __next__(self):
  585. if self.count % 2 == 0:
  586. n = next(self.rbiter)
  587. n = n.cast(self.type).dereference()
  588. n = get_value_from_Rb_tree_node(n)
  589. self.pair = n
  590. item = n['first']
  591. else:
  592. item = self.pair['second']
  593. result = ('[%d]' % self.count, item)
  594. self.count = self.count + 1
  595. return result
  596. def __init__ (self, typename, val):
  597. self.typename = strip_versioned_namespace(typename)
  598. self.val = val
  599. def to_string (self):
  600. return '%s with %s' % (self.typename,
  601. num_elements(len(RbtreeIterator (self.val))))
  602. def children (self):
  603. node = lookup_node_type('_Rb_tree_node', self.val.type).pointer()
  604. return self._iter (RbtreeIterator (self.val), node)
  605. def display_hint (self):
  606. return 'map'
  607. class StdSetPrinter:
  608. "Print a std::set or std::multiset"
  609. # Turn an RbtreeIterator into a pretty-print iterator.
  610. class _iter(Iterator):
  611. def __init__(self, rbiter, type):
  612. self.rbiter = rbiter
  613. self.count = 0
  614. self.type = type
  615. def __iter__(self):
  616. return self
  617. def __next__(self):
  618. item = next(self.rbiter)
  619. item = item.cast(self.type).dereference()
  620. item = get_value_from_Rb_tree_node(item)
  621. # FIXME: this is weird ... what to do?
  622. # Maybe a 'set' display hint?
  623. result = ('[%d]' % self.count, item)
  624. self.count = self.count + 1
  625. return result
  626. def __init__ (self, typename, val):
  627. self.typename = strip_versioned_namespace(typename)
  628. self.val = val
  629. def to_string (self):
  630. return '%s with %s' % (self.typename,
  631. num_elements(len(RbtreeIterator (self.val))))
  632. def children (self):
  633. node = lookup_node_type('_Rb_tree_node', self.val.type).pointer()
  634. return self._iter (RbtreeIterator (self.val), node)
  635. class StdBitsetPrinter:
  636. "Print a std::bitset"
  637. def __init__(self, typename, val):
  638. self.typename = strip_versioned_namespace(typename)
  639. self.val = val
  640. def to_string (self):
  641. # If template_argument handled values, we could print the
  642. # size. Or we could use a regexp on the type.
  643. return '%s' % (self.typename)
  644. def children (self):
  645. try:
  646. # An empty bitset may not have any members which will
  647. # result in an exception being thrown.
  648. words = self.val['_M_w']
  649. except:
  650. return []
  651. wtype = words.type
  652. # The _M_w member can be either an unsigned long, or an
  653. # array. This depends on the template specialization used.
  654. # If it is a single long, convert to a single element list.
  655. if wtype.code == gdb.TYPE_CODE_ARRAY:
  656. tsize = wtype.target ().sizeof
  657. else:
  658. words = [words]
  659. tsize = wtype.sizeof
  660. nwords = wtype.sizeof / tsize
  661. result = []
  662. byte = 0
  663. while byte < nwords:
  664. w = words[byte]
  665. bit = 0
  666. while w != 0:
  667. if (w & 1) != 0:
  668. # Another spot where we could use 'set'?
  669. result.append(('[%d]' % (byte * tsize * 8 + bit), 1))
  670. bit = bit + 1
  671. w = w >> 1
  672. byte = byte + 1
  673. return result
  674. class StdDequePrinter:
  675. "Print a std::deque"
  676. class _iter(Iterator):
  677. def __init__(self, node, start, end, last, buffer_size):
  678. self.node = node
  679. self.p = start
  680. self.end = end
  681. self.last = last
  682. self.buffer_size = buffer_size
  683. self.count = 0
  684. def __iter__(self):
  685. return self
  686. def __next__(self):
  687. if self.p == self.last:
  688. raise StopIteration
  689. result = ('[%d]' % self.count, self.p.dereference())
  690. self.count = self.count + 1
  691. # Advance the 'cur' pointer.
  692. self.p = self.p + 1
  693. if self.p == self.end:
  694. # If we got to the end of this bucket, move to the
  695. # next bucket.
  696. self.node = self.node + 1
  697. self.p = self.node[0]
  698. self.end = self.p + self.buffer_size
  699. return result
  700. def __init__(self, typename, val):
  701. self.typename = strip_versioned_namespace(typename)
  702. self.val = val
  703. self.elttype = val.type.template_argument(0)
  704. size = self.elttype.sizeof
  705. if size < 512:
  706. self.buffer_size = int (512 / size)
  707. else:
  708. self.buffer_size = 1
  709. def to_string(self):
  710. start = self.val['_M_impl']['_M_start']
  711. end = self.val['_M_impl']['_M_finish']
  712. delta_n = end['_M_node'] - start['_M_node'] - 1
  713. delta_s = start['_M_last'] - start['_M_cur']
  714. delta_e = end['_M_cur'] - end['_M_first']
  715. size = self.buffer_size * delta_n + delta_s + delta_e
  716. return '%s with %s' % (self.typename, num_elements(long(size)))
  717. def children(self):
  718. start = self.val['_M_impl']['_M_start']
  719. end = self.val['_M_impl']['_M_finish']
  720. return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
  721. end['_M_cur'], self.buffer_size)
  722. def display_hint (self):
  723. return 'array'
  724. class StdDequeIteratorPrinter:
  725. "Print std::deque::iterator"
  726. def __init__(self, typename, val):
  727. self.val = val
  728. def to_string(self):
  729. if not self.val['_M_cur']:
  730. return 'non-dereferenceable iterator for std::deque'
  731. return str(self.val['_M_cur'].dereference())
  732. class StdStringPrinter:
  733. "Print a std::basic_string of some kind"
  734. def __init__(self, typename, val):
  735. self.val = val
  736. self.new_string = typename.find("::__cxx11::basic_string") != -1
  737. def to_string(self):
  738. # Make sure &string works, too.
  739. type = self.val.type
  740. if type.code == gdb.TYPE_CODE_REF:
  741. type = type.target ()
  742. # Calculate the length of the string so that to_string returns
  743. # the string according to length, not according to first null
  744. # encountered.
  745. ptr = self.val ['_M_dataplus']['_M_p']
  746. if self.new_string:
  747. length = self.val['_M_string_length']
  748. # https://sourceware.org/bugzilla/show_bug.cgi?id=17728
  749. ptr = ptr.cast(ptr.type.strip_typedefs())
  750. else:
  751. realtype = type.unqualified ().strip_typedefs ()
  752. reptype = gdb.lookup_type (str (realtype) + '::_Rep').pointer ()
  753. header = ptr.cast(reptype) - 1
  754. length = header.dereference ()['_M_length']
  755. if hasattr(ptr, "lazy_string"):
  756. return ptr.lazy_string (length = length)
  757. return ptr.string (length = length)
  758. def display_hint (self):
  759. return 'string'
  760. class Tr1HashtableIterator(Iterator):
  761. def __init__ (self, hashtable):
  762. self.buckets = hashtable['_M_buckets']
  763. self.bucket = 0
  764. self.bucket_count = hashtable['_M_bucket_count']
  765. self.node_type = find_type(hashtable.type, '_Node').pointer()
  766. self.node = 0
  767. while self.bucket != self.bucket_count:
  768. self.node = self.buckets[self.bucket]
  769. if self.node:
  770. break
  771. self.bucket = self.bucket + 1
  772. def __iter__ (self):
  773. return self
  774. def __next__ (self):
  775. if self.node == 0:
  776. raise StopIteration
  777. node = self.node.cast(self.node_type)
  778. result = node.dereference()['_M_v']
  779. self.node = node.dereference()['_M_next'];
  780. if self.node == 0:
  781. self.bucket = self.bucket + 1
  782. while self.bucket != self.bucket_count:
  783. self.node = self.buckets[self.bucket]
  784. if self.node:
  785. break
  786. self.bucket = self.bucket + 1
  787. return result
  788. class StdHashtableIterator(Iterator):
  789. def __init__(self, hashtable):
  790. self.node = hashtable['_M_before_begin']['_M_nxt']
  791. valtype = hashtable.type.template_argument(1)
  792. cached = hashtable.type.template_argument(9).template_argument(0)
  793. node_type = lookup_templ_spec('std::__detail::_Hash_node', str(valtype),
  794. 'true' if cached else 'false')
  795. self.node_type = node_type.pointer()
  796. def __iter__(self):
  797. return self
  798. def __next__(self):
  799. if self.node == 0:
  800. raise StopIteration
  801. elt = self.node.cast(self.node_type).dereference()
  802. self.node = elt['_M_nxt']
  803. valptr = elt['_M_storage'].address
  804. valptr = valptr.cast(elt.type.template_argument(0).pointer())
  805. return valptr.dereference()
  806. class Tr1UnorderedSetPrinter:
  807. "Print a std::unordered_set or tr1::unordered_set"
  808. def __init__ (self, typename, val):
  809. self.typename = strip_versioned_namespace(typename)
  810. self.val = val
  811. def hashtable (self):
  812. if self.typename.startswith('std::tr1'):
  813. return self.val
  814. return self.val['_M_h']
  815. def to_string (self):
  816. count = self.hashtable()['_M_element_count']
  817. return '%s with %s' % (self.typename, num_elements(count))
  818. @staticmethod
  819. def format_count (i):
  820. return '[%d]' % i
  821. def children (self):
  822. counter = imap (self.format_count, itertools.count())
  823. if self.typename.startswith('std::tr1'):
  824. return izip (counter, Tr1HashtableIterator (self.hashtable()))
  825. return izip (counter, StdHashtableIterator (self.hashtable()))
  826. class Tr1UnorderedMapPrinter:
  827. "Print a std::unordered_map or tr1::unordered_map"
  828. def __init__ (self, typename, val):
  829. self.typename = strip_versioned_namespace(typename)
  830. self.val = val
  831. def hashtable (self):
  832. if self.typename.startswith('std::tr1'):
  833. return self.val
  834. return self.val['_M_h']
  835. def to_string (self):
  836. count = self.hashtable()['_M_element_count']
  837. return '%s with %s' % (self.typename, num_elements(count))
  838. @staticmethod
  839. def flatten (list):
  840. for elt in list:
  841. for i in elt:
  842. yield i
  843. @staticmethod
  844. def format_one (elt):
  845. return (elt['first'], elt['second'])
  846. @staticmethod
  847. def format_count (i):
  848. return '[%d]' % i
  849. def children (self):
  850. counter = imap (self.format_count, itertools.count())
  851. # Map over the hash table and flatten the result.
  852. if self.typename.startswith('std::tr1'):
  853. data = self.flatten (imap (self.format_one, Tr1HashtableIterator (self.hashtable())))
  854. # Zip the two iterators together.
  855. return izip (counter, data)
  856. data = self.flatten (imap (self.format_one, StdHashtableIterator (self.hashtable())))
  857. # Zip the two iterators together.
  858. return izip (counter, data)
  859. def display_hint (self):
  860. return 'map'
  861. class StdForwardListPrinter:
  862. "Print a std::forward_list"
  863. class _iterator(Iterator):
  864. def __init__(self, nodetype, head):
  865. self.nodetype = nodetype
  866. self.base = head['_M_next']
  867. self.count = 0
  868. def __iter__(self):
  869. return self
  870. def __next__(self):
  871. if self.base == 0:
  872. raise StopIteration
  873. elt = self.base.cast(self.nodetype).dereference()
  874. self.base = elt['_M_next']
  875. count = self.count
  876. self.count = self.count + 1
  877. valptr = elt['_M_storage'].address
  878. valptr = valptr.cast(elt.type.template_argument(0).pointer())
  879. return ('[%d]' % count, valptr.dereference())
  880. def __init__(self, typename, val):
  881. self.val = val
  882. self.typename = strip_versioned_namespace(typename)
  883. def children(self):
  884. nodetype = lookup_node_type('_Fwd_list_node', self.val.type).pointer()
  885. return self._iterator(nodetype, self.val['_M_impl']['_M_head'])
  886. def to_string(self):
  887. if self.val['_M_impl']['_M_head']['_M_next'] == 0:
  888. return 'empty %s' % self.typename
  889. return '%s' % self.typename
  890. class SingleObjContainerPrinter(object):
  891. "Base class for printers of containers of single objects"
  892. def __init__ (self, val, viz, hint = None):
  893. self.contained_value = val
  894. self.visualizer = viz
  895. self.hint = hint
  896. def _recognize(self, type):
  897. """Return TYPE as a string after applying type printers"""
  898. global _use_type_printing
  899. if not _use_type_printing:
  900. return str(type)
  901. return gdb.types.apply_type_recognizers(gdb.types.get_type_recognizers(),
  902. type) or str(type)
  903. class _contained(Iterator):
  904. def __init__ (self, val):
  905. self.val = val
  906. def __iter__ (self):
  907. return self
  908. def __next__(self):
  909. if self.val is None:
  910. raise StopIteration
  911. retval = self.val
  912. self.val = None
  913. return ('[contained value]', retval)
  914. def children (self):
  915. if self.contained_value is None:
  916. return self._contained (None)
  917. if hasattr (self.visualizer, 'children'):
  918. return self.visualizer.children ()
  919. return self._contained (self.contained_value)
  920. def display_hint (self):
  921. # if contained value is a map we want to display in the same way
  922. if hasattr (self.visualizer, 'children') and hasattr (self.visualizer, 'display_hint'):
  923. return self.visualizer.display_hint ()
  924. return self.hint
  925. class StdExpAnyPrinter(SingleObjContainerPrinter):
  926. "Print a std::any or std::experimental::any"
  927. def __init__ (self, typename, val):
  928. self.typename = strip_versioned_namespace(typename)
  929. self.typename = re.sub('^std::experimental::fundamentals_v\d::', 'std::experimental::', self.typename, 1)
  930. self.val = val
  931. self.contained_type = None
  932. contained_value = None
  933. visualizer = None
  934. mgr = self.val['_M_manager']
  935. if mgr != 0:
  936. func = gdb.block_for_pc(int(mgr.cast(gdb.lookup_type('intptr_t'))))
  937. if not func:
  938. raise ValueError("Invalid function pointer in %s" % self.typename)
  939. rx = r"""({0}::_Manager_\w+<.*>)::_S_manage\((enum )?{0}::_Op, (const {0}|{0} const) ?\*, (union )?{0}::_Arg ?\*\)""".format(typename)
  940. m = re.match(rx, func.function.name)
  941. if not m:
  942. raise ValueError("Unknown manager function in %s" % self.typename)
  943. mgrname = m.group(1)
  944. # FIXME need to expand 'std::string' so that gdb.lookup_type works
  945. if 'std::string' in mgrname:
  946. mgrname = re.sub("std::string(?!\w)", str(gdb.lookup_type('std::string').strip_typedefs()), m.group(1))
  947. mgrtype = gdb.lookup_type(mgrname)
  948. self.contained_type = mgrtype.template_argument(0)
  949. valptr = None
  950. if '::_Manager_internal' in mgrname:
  951. valptr = self.val['_M_storage']['_M_buffer'].address
  952. elif '::_Manager_external' in mgrname:
  953. valptr = self.val['_M_storage']['_M_ptr']
  954. else:
  955. raise ValueError("Unknown manager function in %s" % self.typename)
  956. contained_value = valptr.cast(self.contained_type.pointer()).dereference()
  957. visualizer = gdb.default_visualizer(contained_value)
  958. super(StdExpAnyPrinter, self).__init__ (contained_value, visualizer)
  959. def to_string (self):
  960. if self.contained_type is None:
  961. return '%s [no contained value]' % self.typename
  962. desc = "%s containing " % self.typename
  963. if hasattr (self.visualizer, 'children'):
  964. return desc + self.visualizer.to_string ()
  965. valtype = self._recognize (self.contained_type)
  966. return desc + strip_versioned_namespace(str(valtype))
  967. class StdExpOptionalPrinter(SingleObjContainerPrinter):
  968. "Print a std::optional or std::experimental::optional"
  969. def __init__ (self, typename, val):
  970. valtype = self._recognize (val.type.template_argument(0))
  971. typename = strip_versioned_namespace(typename)
  972. self.typename = re.sub('^std::(experimental::|)(fundamentals_v\d::|)(.*)', r'std::\1\3<%s>' % valtype, typename, 1)
  973. payload = val['_M_payload']
  974. if self.typename.startswith('std::experimental'):
  975. engaged = val['_M_engaged']
  976. contained_value = payload
  977. else:
  978. engaged = payload['_M_engaged']
  979. contained_value = payload['_M_payload']
  980. try:
  981. # Since GCC 9
  982. contained_value = contained_value['_M_value']
  983. except:
  984. pass
  985. visualizer = gdb.default_visualizer (contained_value)
  986. if not engaged:
  987. contained_value = None
  988. super (StdExpOptionalPrinter, self).__init__ (contained_value, visualizer)
  989. def to_string (self):
  990. if self.contained_value is None:
  991. return "%s [no contained value]" % self.typename
  992. if hasattr (self.visualizer, 'children'):
  993. return "%s containing %s" % (self.typename,
  994. self.visualizer.to_string())
  995. return self.typename
  996. class StdVariantPrinter(SingleObjContainerPrinter):
  997. "Print a std::variant"
  998. def __init__(self, typename, val):
  999. alternatives = get_template_arg_list(val.type)
  1000. self.typename = strip_versioned_namespace(typename)
  1001. self.typename = "%s<%s>" % (self.typename, ', '.join([self._recognize(alt) for alt in alternatives]))
  1002. self.index = val['_M_index']
  1003. if self.index >= len(alternatives):
  1004. self.contained_type = None
  1005. contained_value = None
  1006. visualizer = None
  1007. else:
  1008. self.contained_type = alternatives[int(self.index)]
  1009. addr = val['_M_u']['_M_first']['_M_storage'].address
  1010. contained_value = addr.cast(self.contained_type.pointer()).dereference()
  1011. visualizer = gdb.default_visualizer(contained_value)
  1012. super (StdVariantPrinter, self).__init__(contained_value, visualizer, 'array')
  1013. def to_string(self):
  1014. if self.contained_value is None:
  1015. return "%s [no contained value]" % self.typename
  1016. if hasattr(self.visualizer, 'children'):
  1017. return "%s [index %d] containing %s" % (self.typename, self.index,
  1018. self.visualizer.to_string())
  1019. return "%s [index %d]" % (self.typename, self.index)
  1020. class StdNodeHandlePrinter(SingleObjContainerPrinter):
  1021. "Print a container node handle"
  1022. def __init__(self, typename, val):
  1023. self.value_type = val.type.template_argument(1)
  1024. nodetype = val.type.template_argument(2).template_argument(0)
  1025. self.is_rb_tree_node = is_specialization_of(nodetype.name, '_Rb_tree_node')
  1026. self.is_map_node = val.type.template_argument(0) != self.value_type
  1027. nodeptr = val['_M_ptr']
  1028. if nodeptr:
  1029. if self.is_rb_tree_node:
  1030. contained_value = get_value_from_Rb_tree_node(nodeptr.dereference())
  1031. else:
  1032. contained_value = get_value_from_aligned_membuf(nodeptr['_M_storage'],
  1033. self.value_type)
  1034. visualizer = gdb.default_visualizer(contained_value)
  1035. else:
  1036. contained_value = None
  1037. visualizer = None
  1038. optalloc = val['_M_alloc']
  1039. self.alloc = optalloc['_M_payload'] if optalloc['_M_engaged'] else None
  1040. super(StdNodeHandlePrinter, self).__init__(contained_value, visualizer,
  1041. 'array')
  1042. def to_string(self):
  1043. desc = 'node handle for '
  1044. if not self.is_rb_tree_node:
  1045. desc += 'unordered '
  1046. if self.is_map_node:
  1047. desc += 'map';
  1048. else:
  1049. desc += 'set';
  1050. if self.contained_value:
  1051. desc += ' with element'
  1052. if hasattr(self.visualizer, 'children'):
  1053. return "%s = %s" % (desc, self.visualizer.to_string())
  1054. return desc
  1055. else:
  1056. return 'empty %s' % desc
  1057. class StdExpStringViewPrinter:
  1058. "Print a std::basic_string_view or std::experimental::basic_string_view"
  1059. def __init__ (self, typename, val):
  1060. self.val = val
  1061. def to_string (self):
  1062. ptr = self.val['_M_str']
  1063. len = self.val['_M_len']
  1064. if hasattr (ptr, "lazy_string"):
  1065. return ptr.lazy_string (length = len)
  1066. return ptr.string (length = len)
  1067. def display_hint (self):
  1068. return 'string'
  1069. class StdExpPathPrinter:
  1070. "Print a std::experimental::filesystem::path"
  1071. def __init__ (self, typename, val):
  1072. self.val = val
  1073. start = self.val['_M_cmpts']['_M_impl']['_M_start']
  1074. finish = self.val['_M_cmpts']['_M_impl']['_M_finish']
  1075. self.num_cmpts = int (finish - start)
  1076. def _path_type(self):
  1077. t = str(self.val['_M_type'])
  1078. if t[-9:] == '_Root_dir':
  1079. return "root-directory"
  1080. if t[-10:] == '_Root_name':
  1081. return "root-name"
  1082. return None
  1083. def to_string (self):
  1084. path = "%s" % self.val ['_M_pathname']
  1085. if self.num_cmpts == 0:
  1086. t = self._path_type()
  1087. if t:
  1088. path = '%s [%s]' % (path, t)
  1089. return "filesystem::path %s" % path
  1090. class _iterator(Iterator):
  1091. def __init__(self, cmpts):
  1092. self.item = cmpts['_M_impl']['_M_start']
  1093. self.finish = cmpts['_M_impl']['_M_finish']
  1094. self.count = 0
  1095. def __iter__(self):
  1096. return self
  1097. def __next__(self):
  1098. if self.item == self.finish:
  1099. raise StopIteration
  1100. item = self.item.dereference()
  1101. count = self.count
  1102. self.count = self.count + 1
  1103. self.item = self.item + 1
  1104. path = item['_M_pathname']
  1105. t = StdExpPathPrinter(item.type.name, item)._path_type()
  1106. if not t:
  1107. t = count
  1108. return ('[%s]' % t, path)
  1109. def children(self):
  1110. return self._iterator(self.val['_M_cmpts'])
  1111. class StdPathPrinter:
  1112. "Print a std::filesystem::path"
  1113. def __init__ (self, typename, val):
  1114. self.val = val
  1115. self.typename = typename
  1116. impl = self.val['_M_cmpts']['_M_impl']['_M_t']['_M_t']['_M_head_impl']
  1117. self.type = impl.cast(gdb.lookup_type('uintptr_t')) & 3
  1118. if self.type == 0:
  1119. self.impl = impl
  1120. else:
  1121. self.impl = None
  1122. def _path_type(self):
  1123. t = str(self.type.cast(gdb.lookup_type(self.typename + '::_Type')))
  1124. if t[-9:] == '_Root_dir':
  1125. return "root-directory"
  1126. if t[-10:] == '_Root_name':
  1127. return "root-name"
  1128. return None
  1129. def to_string (self):
  1130. path = "%s" % self.val ['_M_pathname']
  1131. if self.type != 0:
  1132. t = self._path_type()
  1133. if t:
  1134. path = '%s [%s]' % (path, t)
  1135. return "filesystem::path %s" % path
  1136. class _iterator(Iterator):
  1137. def __init__(self, impl, pathtype):
  1138. if impl:
  1139. # We can't access _Impl::_M_size because _Impl is incomplete
  1140. # so cast to int* to access the _M_size member at offset zero,
  1141. int_type = gdb.lookup_type('int')
  1142. cmpt_type = gdb.lookup_type(pathtype+'::_Cmpt')
  1143. char_type = gdb.lookup_type('char')
  1144. impl = impl.cast(int_type.pointer())
  1145. size = impl.dereference()
  1146. #self.capacity = (impl + 1).dereference()
  1147. if hasattr(gdb.Type, 'alignof'):
  1148. sizeof_Impl = max(2 * int_type.sizeof, cmpt_type.alignof)
  1149. else:
  1150. sizeof_Impl = 2 * int_type.sizeof
  1151. begin = impl.cast(char_type.pointer()) + sizeof_Impl
  1152. self.item = begin.cast(cmpt_type.pointer())
  1153. self.finish = self.item + size
  1154. self.count = 0
  1155. else:
  1156. self.item = None
  1157. self.finish = None
  1158. def __iter__(self):
  1159. return self
  1160. def __next__(self):
  1161. if self.item == self.finish:
  1162. raise StopIteration
  1163. item = self.item.dereference()
  1164. count = self.count
  1165. self.count = self.count + 1
  1166. self.item = self.item + 1
  1167. path = item['_M_pathname']
  1168. t = StdPathPrinter(item.type.name, item)._path_type()
  1169. if not t:
  1170. t = count
  1171. return ('[%s]' % t, path)
  1172. def children(self):
  1173. return self._iterator(self.impl, self.typename)
  1174. class StdPairPrinter:
  1175. "Print a std::pair object, with 'first' and 'second' as children"
  1176. def __init__(self, typename, val):
  1177. self.val = val
  1178. class _iter(Iterator):
  1179. "An iterator for std::pair types. Returns 'first' then 'second'."
  1180. def __init__(self, val):
  1181. self.val = val
  1182. self.which = 'first'
  1183. def __iter__(self):
  1184. return self
  1185. def __next__(self):
  1186. if self.which is None:
  1187. raise StopIteration
  1188. which = self.which
  1189. if which == 'first':
  1190. self.which = 'second'
  1191. else:
  1192. self.which = None
  1193. return (which, self.val[which])
  1194. def children(self):
  1195. return self._iter(self.val)
  1196. def to_string(self):
  1197. return None
  1198. class StdCmpCatPrinter:
  1199. "Print a comparison category object"
  1200. def __init__ (self, typename, val):
  1201. self.typename = typename[typename.rfind(':')+1:]
  1202. self.val = val['_M_value']
  1203. def to_string (self):
  1204. if self.typename == 'strong_ordering' and self.val == 0:
  1205. name = 'equal'
  1206. else:
  1207. names = {2:'unordered', -1:'less', 0:'equivalent', 1:'greater'}
  1208. name = names[int(self.val)]
  1209. return 'std::{}::{}'.format(self.typename, name)
  1210. # A "regular expression" printer which conforms to the
  1211. # "SubPrettyPrinter" protocol from gdb.printing.
  1212. class RxPrinter(object):
  1213. def __init__(self, name, function):
  1214. super(RxPrinter, self).__init__()
  1215. self.name = name
  1216. self.function = function
  1217. self.enabled = True
  1218. def invoke(self, value):
  1219. if not self.enabled:
  1220. return None
  1221. if value.type.code == gdb.TYPE_CODE_REF:
  1222. if hasattr(gdb.Value,"referenced_value"):
  1223. value = value.referenced_value()
  1224. return self.function(self.name, value)
  1225. # A pretty-printer that conforms to the "PrettyPrinter" protocol from
  1226. # gdb.printing. It can also be used directly as an old-style printer.
  1227. class Printer(object):
  1228. def __init__(self, name):
  1229. super(Printer, self).__init__()
  1230. self.name = name
  1231. self.subprinters = []
  1232. self.lookup = {}
  1233. self.enabled = True
  1234. self.compiled_rx = re.compile('^([a-zA-Z0-9_:]+)(<.*>)?$')
  1235. def add(self, name, function):
  1236. # A small sanity check.
  1237. # FIXME
  1238. if not self.compiled_rx.match(name):
  1239. raise ValueError('libstdc++ programming error: "%s" does not match' % name)
  1240. printer = RxPrinter(name, function)
  1241. self.subprinters.append(printer)
  1242. self.lookup[name] = printer
  1243. # Add a name using _GLIBCXX_BEGIN_NAMESPACE_VERSION.
  1244. def add_version(self, base, name, function):
  1245. self.add(base + name, function)
  1246. if _versioned_namespace:
  1247. vbase = re.sub('^(std|__gnu_cxx)::', r'\g<0>%s' % _versioned_namespace, base)
  1248. self.add(vbase + name, function)
  1249. # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
  1250. def add_container(self, base, name, function):
  1251. self.add_version(base, name, function)
  1252. self.add_version(base + '__cxx1998::', name, function)
  1253. @staticmethod
  1254. def get_basic_type(type):
  1255. # If it points to a reference, get the reference.
  1256. if type.code == gdb.TYPE_CODE_REF:
  1257. type = type.target ()
  1258. # Get the unqualified type, stripped of typedefs.
  1259. type = type.unqualified ().strip_typedefs ()
  1260. return type.tag
  1261. def __call__(self, val):
  1262. typename = self.get_basic_type(val.type)
  1263. if not typename:
  1264. return None
  1265. # All the types we match are template types, so we can use a
  1266. # dictionary.
  1267. match = self.compiled_rx.match(typename)
  1268. if not match:
  1269. return None
  1270. basename = match.group(1)
  1271. if val.type.code == gdb.TYPE_CODE_REF:
  1272. if hasattr(gdb.Value,"referenced_value"):
  1273. val = val.referenced_value()
  1274. if basename in self.lookup:
  1275. return self.lookup[basename].invoke(val)
  1276. # Cannot find a pretty printer. Return None.
  1277. return None
  1278. libstdcxx_printer = None
  1279. class TemplateTypePrinter(object):
  1280. r"""
  1281. A type printer for class templates with default template arguments.
  1282. Recognizes specializations of class templates and prints them without
  1283. any template arguments that use a default template argument.
  1284. Type printers are recursively applied to the template arguments.
  1285. e.g. replace "std::vector<T, std::allocator<T> >" with "std::vector<T>".
  1286. """
  1287. def __init__(self, name, defargs):
  1288. self.name = name
  1289. self.defargs = defargs
  1290. self.enabled = True
  1291. class _recognizer(object):
  1292. "The recognizer class for TemplateTypePrinter."
  1293. def __init__(self, name, defargs):
  1294. self.name = name
  1295. self.defargs = defargs
  1296. # self.type_obj = None
  1297. def recognize(self, type_obj):
  1298. """
  1299. If type_obj is a specialization of self.name that uses all the
  1300. default template arguments for the class template, then return
  1301. a string representation of the type without default arguments.
  1302. Otherwise, return None.
  1303. """
  1304. if type_obj.tag is None:
  1305. return None
  1306. if not type_obj.tag.startswith(self.name):
  1307. return None
  1308. template_args = get_template_arg_list(type_obj)
  1309. displayed_args = []
  1310. require_defaulted = False
  1311. for n in range(len(template_args)):
  1312. # The actual template argument in the type:
  1313. targ = template_args[n]
  1314. # The default template argument for the class template:
  1315. defarg = self.defargs.get(n)
  1316. if defarg is not None:
  1317. # Substitute other template arguments into the default:
  1318. defarg = defarg.format(*template_args)
  1319. # Fail to recognize the type (by returning None)
  1320. # unless the actual argument is the same as the default.
  1321. try:
  1322. if targ != gdb.lookup_type(defarg):
  1323. return None
  1324. except gdb.error:
  1325. # Type lookup failed, just use string comparison:
  1326. if targ.tag != defarg:
  1327. return None
  1328. # All subsequent args must have defaults:
  1329. require_defaulted = True
  1330. elif require_defaulted:
  1331. return None
  1332. else:
  1333. # Recursively apply recognizers to the template argument
  1334. # and add it to the arguments that will be displayed:
  1335. displayed_args.append(self._recognize_subtype(targ))
  1336. # This assumes no class templates in the nested-name-specifier:
  1337. template_name = type_obj.tag[0:type_obj.tag.find('<')]
  1338. template_name = strip_inline_namespaces(template_name)
  1339. return template_name + '<' + ', '.join(displayed_args) + '>'
  1340. def _recognize_subtype(self, type_obj):
  1341. """Convert a gdb.Type to a string by applying recognizers,
  1342. or if that fails then simply converting to a string."""
  1343. if type_obj.code == gdb.TYPE_CODE_PTR:
  1344. return self._recognize_subtype(type_obj.target()) + '*'
  1345. if type_obj.code == gdb.TYPE_CODE_ARRAY:
  1346. type_str = self._recognize_subtype(type_obj.target())
  1347. if str(type_obj.strip_typedefs()).endswith('[]'):
  1348. return type_str + '[]' # array of unknown bound
  1349. return "%s[%d]" % (type_str, type_obj.range()[1] + 1)
  1350. if type_obj.code == gdb.TYPE_CODE_REF:
  1351. return self._recognize_subtype(type_obj.target()) + '&'
  1352. if hasattr(gdb, 'TYPE_CODE_RVALUE_REF'):
  1353. if type_obj.code == gdb.TYPE_CODE_RVALUE_REF:
  1354. return self._recognize_subtype(type_obj.target()) + '&&'
  1355. type_str = gdb.types.apply_type_recognizers(
  1356. gdb.types.get_type_recognizers(), type_obj)
  1357. if type_str:
  1358. return type_str
  1359. return str(type_obj)
  1360. def instantiate(self):
  1361. "Return a recognizer object for this type printer."
  1362. return self._recognizer(self.name, self.defargs)
  1363. def add_one_template_type_printer(obj, name, defargs):
  1364. r"""
  1365. Add a type printer for a class template with default template arguments.
  1366. Args:
  1367. name (str): The template-name of the class template.
  1368. defargs (dict int:string) The default template arguments.
  1369. Types in defargs can refer to the Nth template-argument using {N}
  1370. (with zero-based indices).
  1371. e.g. 'unordered_map' has these defargs:
  1372. { 2: 'std::hash<{0}>',
  1373. 3: 'std::equal_to<{0}>',
  1374. 4: 'std::allocator<std::pair<const {0}, {1}> >' }
  1375. """
  1376. printer = TemplateTypePrinter('std::'+name, defargs)
  1377. gdb.types.register_type_printer(obj, printer)
  1378. # Add type printer for same type in debug namespace:
  1379. printer = TemplateTypePrinter('std::__debug::'+name, defargs)
  1380. gdb.types.register_type_printer(obj, printer)
  1381. if _versioned_namespace:
  1382. # Add second type printer for same type in versioned namespace:
  1383. ns = 'std::' + _versioned_namespace
  1384. # PR 86112 Cannot use dict comprehension here:
  1385. defargs = dict((n, d.replace('std::', ns)) for (n,d) in defargs.items())
  1386. printer = TemplateTypePrinter(ns+name, defargs)
  1387. gdb.types.register_type_printer(obj, printer)
  1388. class FilteringTypePrinter(object):
  1389. r"""
  1390. A type printer that uses typedef names for common template specializations.
  1391. Args:
  1392. match (str): The class template to recognize.
  1393. name (str): The typedef-name that will be used instead.
  1394. Checks if a specialization of the class template 'match' is the same type
  1395. as the typedef 'name', and prints it as 'name' instead.
  1396. e.g. if an instantiation of std::basic_istream<C, T> is the same type as
  1397. std::istream then print it as std::istream.
  1398. """
  1399. def __init__(self, match, name):
  1400. self.match = match
  1401. self.name = name
  1402. self.enabled = True
  1403. class _recognizer(object):
  1404. "The recognizer class for TemplateTypePrinter."
  1405. def __init__(self, match, name):
  1406. self.match = match
  1407. self.name = name
  1408. self.type_obj = None
  1409. def recognize(self, type_obj):
  1410. """
  1411. If type_obj starts with self.match and is the same type as
  1412. self.name then return self.name, otherwise None.
  1413. """
  1414. if type_obj.tag is None:
  1415. return None
  1416. if self.type_obj is None:
  1417. if not type_obj.tag.startswith(self.match):
  1418. # Filter didn't match.
  1419. return None
  1420. try:
  1421. self.type_obj = gdb.lookup_type(self.name).strip_typedefs()
  1422. except:
  1423. pass
  1424. if self.type_obj == type_obj:
  1425. return strip_inline_namespaces(self.name)
  1426. return None
  1427. def instantiate(self):
  1428. "Return a recognizer object for this type printer."
  1429. return self._recognizer(self.match, self.name)
  1430. def add_one_type_printer(obj, match, name):
  1431. printer = FilteringTypePrinter('std::' + match, 'std::' + name)
  1432. gdb.types.register_type_printer(obj, printer)
  1433. if _versioned_namespace:
  1434. ns = 'std::' + _versioned_namespace
  1435. printer = FilteringTypePrinter(ns + match, ns + name)
  1436. gdb.types.register_type_printer(obj, printer)
  1437. def register_type_printers(obj):
  1438. global _use_type_printing
  1439. if not _use_type_printing:
  1440. return
  1441. # Add type printers for typedefs std::string, std::wstring etc.
  1442. for ch in ('', 'w', 'u8', 'u16', 'u32'):
  1443. add_one_type_printer(obj, 'basic_string', ch + 'string')
  1444. add_one_type_printer(obj, '__cxx11::basic_string', ch + 'string')
  1445. # Typedefs for __cxx11::basic_string used to be in namespace __cxx11:
  1446. add_one_type_printer(obj, '__cxx11::basic_string',
  1447. '__cxx11::' + ch + 'string')
  1448. add_one_type_printer(obj, 'basic_string_view', ch + 'string_view')
  1449. # Add type printers for typedefs std::istream, std::wistream etc.
  1450. for ch in ('', 'w'):
  1451. for x in ('ios', 'streambuf', 'istream', 'ostream', 'iostream',
  1452. 'filebuf', 'ifstream', 'ofstream', 'fstream'):
  1453. add_one_type_printer(obj, 'basic_' + x, ch + x)
  1454. for x in ('stringbuf', 'istringstream', 'ostringstream',
  1455. 'stringstream'):
  1456. add_one_type_printer(obj, 'basic_' + x, ch + x)
  1457. # <sstream> types are in __cxx11 namespace, but typedefs aren't:
  1458. add_one_type_printer(obj, '__cxx11::basic_' + x, ch + x)
  1459. # Add type printers for typedefs regex, wregex, cmatch, wcmatch etc.
  1460. for abi in ('', '__cxx11::'):
  1461. for ch in ('', 'w'):
  1462. add_one_type_printer(obj, abi + 'basic_regex', abi + ch + 'regex')
  1463. for ch in ('c', 's', 'wc', 'ws'):
  1464. add_one_type_printer(obj, abi + 'match_results', abi + ch + 'match')
  1465. for x in ('sub_match', 'regex_iterator', 'regex_token_iterator'):
  1466. add_one_type_printer(obj, abi + x, abi + ch + x)
  1467. # Note that we can't have a printer for std::wstreampos, because
  1468. # it is the same type as std::streampos.
  1469. add_one_type_printer(obj, 'fpos', 'streampos')
  1470. # Add type printers for <chrono> typedefs.
  1471. for dur in ('nanoseconds', 'microseconds', 'milliseconds',
  1472. 'seconds', 'minutes', 'hours'):
  1473. add_one_type_printer(obj, 'duration', dur)
  1474. # Add type printers for <random> typedefs.
  1475. add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand0')
  1476. add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand')
  1477. add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937')
  1478. add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937_64')
  1479. add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux24_base')
  1480. add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux48_base')
  1481. add_one_type_printer(obj, 'discard_block_engine', 'ranlux24')
  1482. add_one_type_printer(obj, 'discard_block_engine', 'ranlux48')
  1483. add_one_type_printer(obj, 'shuffle_order_engine', 'knuth_b')
  1484. # Add type printers for experimental::basic_string_view typedefs.
  1485. ns = 'experimental::fundamentals_v1::'
  1486. for ch in ('', 'w', 'u8', 'u16', 'u32'):
  1487. add_one_type_printer(obj, ns + 'basic_string_view',
  1488. ns + ch + 'string_view')
  1489. # Do not show defaulted template arguments in class templates.
  1490. add_one_template_type_printer(obj, 'unique_ptr',
  1491. { 1: 'std::default_delete<{0}>' })
  1492. add_one_template_type_printer(obj, 'deque', { 1: 'std::allocator<{0}>'})
  1493. add_one_template_type_printer(obj, 'forward_list', { 1: 'std::allocator<{0}>'})
  1494. add_one_template_type_printer(obj, 'list', { 1: 'std::allocator<{0}>'})
  1495. add_one_template_type_printer(obj, '__cxx11::list', { 1: 'std::allocator<{0}>'})
  1496. add_one_template_type_printer(obj, 'vector', { 1: 'std::allocator<{0}>'})
  1497. add_one_template_type_printer(obj, 'map',
  1498. { 2: 'std::less<{0}>',
  1499. 3: 'std::allocator<std::pair<{0} const, {1}>>' })
  1500. add_one_template_type_printer(obj, 'multimap',
  1501. { 2: 'std::less<{0}>',
  1502. 3: 'std::allocator<std::pair<{0} const, {1}>>' })
  1503. add_one_template_type_printer(obj, 'set',
  1504. { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
  1505. add_one_template_type_printer(obj, 'multiset',
  1506. { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
  1507. add_one_template_type_printer(obj, 'unordered_map',
  1508. { 2: 'std::hash<{0}>',
  1509. 3: 'std::equal_to<{0}>',
  1510. 4: 'std::allocator<std::pair<{0} const, {1}>>'})
  1511. add_one_template_type_printer(obj, 'unordered_multimap',
  1512. { 2: 'std::hash<{0}>',
  1513. 3: 'std::equal_to<{0}>',
  1514. 4: 'std::allocator<std::pair<{0} const, {1}>>'})
  1515. add_one_template_type_printer(obj, 'unordered_set',
  1516. { 1: 'std::hash<{0}>',
  1517. 2: 'std::equal_to<{0}>',
  1518. 3: 'std::allocator<{0}>'})
  1519. add_one_template_type_printer(obj, 'unordered_multiset',
  1520. { 1: 'std::hash<{0}>',
  1521. 2: 'std::equal_to<{0}>',
  1522. 3: 'std::allocator<{0}>'})
  1523. def register_libstdcxx_printers (obj):
  1524. "Register libstdc++ pretty-printers with objfile Obj."
  1525. global _use_gdb_pp
  1526. global libstdcxx_printer
  1527. if _use_gdb_pp:
  1528. gdb.printing.register_pretty_printer(obj, libstdcxx_printer)
  1529. else:
  1530. if obj is None:
  1531. obj = gdb
  1532. obj.pretty_printers.append(libstdcxx_printer)
  1533. register_type_printers(obj)
  1534. def build_libstdcxx_dictionary ():
  1535. global libstdcxx_printer
  1536. libstdcxx_printer = Printer("libstdc++-v6")
  1537. # libstdc++ objects requiring pretty-printing.
  1538. # In order from:
  1539. # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
  1540. libstdcxx_printer.add_version('std::', 'basic_string', StdStringPrinter)
  1541. libstdcxx_printer.add_version('std::__cxx11::', 'basic_string', StdStringPrinter)
  1542. libstdcxx_printer.add_container('std::', 'bitset', StdBitsetPrinter)
  1543. libstdcxx_printer.add_container('std::', 'deque', StdDequePrinter)
  1544. libstdcxx_printer.add_container('std::', 'list', StdListPrinter)
  1545. libstdcxx_printer.add_container('std::__cxx11::', 'list', StdListPrinter)
  1546. libstdcxx_printer.add_container('std::', 'map', StdMapPrinter)
  1547. libstdcxx_printer.add_container('std::', 'multimap', StdMapPrinter)
  1548. libstdcxx_printer.add_container('std::', 'multiset', StdSetPrinter)
  1549. libstdcxx_printer.add_version('std::', 'pair', StdPairPrinter)
  1550. libstdcxx_printer.add_version('std::', 'priority_queue',
  1551. StdStackOrQueuePrinter)
  1552. libstdcxx_printer.add_version('std::', 'queue', StdStackOrQueuePrinter)
  1553. libstdcxx_printer.add_version('std::', 'tuple', StdTuplePrinter)
  1554. libstdcxx_printer.add_container('std::', 'set', StdSetPrinter)
  1555. libstdcxx_printer.add_version('std::', 'stack', StdStackOrQueuePrinter)
  1556. libstdcxx_printer.add_version('std::', 'unique_ptr', UniquePointerPrinter)
  1557. libstdcxx_printer.add_container('std::', 'vector', StdVectorPrinter)
  1558. # vector<bool>
  1559. # Printer registrations for classes compiled with -D_GLIBCXX_DEBUG.
  1560. libstdcxx_printer.add('std::__debug::bitset', StdBitsetPrinter)
  1561. libstdcxx_printer.add('std::__debug::deque', StdDequePrinter)
  1562. libstdcxx_printer.add('std::__debug::list', StdListPrinter)
  1563. libstdcxx_printer.add('std::__debug::map', StdMapPrinter)
  1564. libstdcxx_printer.add('std::__debug::multimap', StdMapPrinter)
  1565. libstdcxx_printer.add('std::__debug::multiset', StdSetPrinter)
  1566. libstdcxx_printer.add('std::__debug::priority_queue',
  1567. StdStackOrQueuePrinter)
  1568. libstdcxx_printer.add('std::__debug::queue', StdStackOrQueuePrinter)
  1569. libstdcxx_printer.add('std::__debug::set', StdSetPrinter)
  1570. libstdcxx_printer.add('std::__debug::stack', StdStackOrQueuePrinter)
  1571. libstdcxx_printer.add('std::__debug::unique_ptr', UniquePointerPrinter)
  1572. libstdcxx_printer.add('std::__debug::vector', StdVectorPrinter)
  1573. # These are the TR1 and C++11 printers.
  1574. # For array - the default GDB pretty-printer seems reasonable.
  1575. libstdcxx_printer.add_version('std::', 'shared_ptr', SharedPointerPrinter)
  1576. libstdcxx_printer.add_version('std::', 'weak_ptr', SharedPointerPrinter)
  1577. libstdcxx_printer.add_container('std::', 'unordered_map',
  1578. Tr1UnorderedMapPrinter)
  1579. libstdcxx_printer.add_container('std::', 'unordered_set',
  1580. Tr1UnorderedSetPrinter)
  1581. libstdcxx_printer.add_container('std::', 'unordered_multimap',
  1582. Tr1UnorderedMapPrinter)
  1583. libstdcxx_printer.add_container('std::', 'unordered_multiset',
  1584. Tr1UnorderedSetPrinter)
  1585. libstdcxx_printer.add_container('std::', 'forward_list',
  1586. StdForwardListPrinter)
  1587. libstdcxx_printer.add_version('std::tr1::', 'shared_ptr', SharedPointerPrinter)
  1588. libstdcxx_printer.add_version('std::tr1::', 'weak_ptr', SharedPointerPrinter)
  1589. libstdcxx_printer.add_version('std::tr1::', 'unordered_map',
  1590. Tr1UnorderedMapPrinter)
  1591. libstdcxx_printer.add_version('std::tr1::', 'unordered_set',
  1592. Tr1UnorderedSetPrinter)
  1593. libstdcxx_printer.add_version('std::tr1::', 'unordered_multimap',
  1594. Tr1UnorderedMapPrinter)
  1595. libstdcxx_printer.add_version('std::tr1::', 'unordered_multiset',
  1596. Tr1UnorderedSetPrinter)
  1597. # These are the C++11 printer registrations for -D_GLIBCXX_DEBUG cases.
  1598. # The tr1 namespace containers do not have any debug equivalents,
  1599. # so do not register printers for them.
  1600. libstdcxx_printer.add('std::__debug::unordered_map',
  1601. Tr1UnorderedMapPrinter)
  1602. libstdcxx_printer.add('std::__debug::unordered_set',
  1603. Tr1UnorderedSetPrinter)
  1604. libstdcxx_printer.add('std::__debug::unordered_multimap',
  1605. Tr1UnorderedMapPrinter)
  1606. libstdcxx_printer.add('std::__debug::unordered_multiset',
  1607. Tr1UnorderedSetPrinter)
  1608. libstdcxx_printer.add('std::__debug::forward_list',
  1609. StdForwardListPrinter)
  1610. # Library Fundamentals TS components
  1611. libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
  1612. 'any', StdExpAnyPrinter)
  1613. libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
  1614. 'optional', StdExpOptionalPrinter)
  1615. libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
  1616. 'basic_string_view', StdExpStringViewPrinter)
  1617. # Filesystem TS components
  1618. libstdcxx_printer.add_version('std::experimental::filesystem::v1::',
  1619. 'path', StdExpPathPrinter)
  1620. libstdcxx_printer.add_version('std::experimental::filesystem::v1::__cxx11::',
  1621. 'path', StdExpPathPrinter)
  1622. libstdcxx_printer.add_version('std::filesystem::',
  1623. 'path', StdPathPrinter)
  1624. libstdcxx_printer.add_version('std::filesystem::__cxx11::',
  1625. 'path', StdPathPrinter)
  1626. # C++17 components
  1627. libstdcxx_printer.add_version('std::',
  1628. 'any', StdExpAnyPrinter)
  1629. libstdcxx_printer.add_version('std::',
  1630. 'optional', StdExpOptionalPrinter)
  1631. libstdcxx_printer.add_version('std::',
  1632. 'basic_string_view', StdExpStringViewPrinter)
  1633. libstdcxx_printer.add_version('std::',
  1634. 'variant', StdVariantPrinter)
  1635. libstdcxx_printer.add_version('std::',
  1636. '_Node_handle', StdNodeHandlePrinter)
  1637. # C++20 components
  1638. libstdcxx_printer.add_version('std::', 'partial_ordering', StdCmpCatPrinter)
  1639. libstdcxx_printer.add_version('std::', 'weak_ordering', StdCmpCatPrinter)
  1640. libstdcxx_printer.add_version('std::', 'strong_ordering', StdCmpCatPrinter)
  1641. # Extensions.
  1642. libstdcxx_printer.add_version('__gnu_cxx::', 'slist', StdSlistPrinter)
  1643. if True:
  1644. # These shouldn't be necessary, if GDB "print *i" worked.
  1645. # But it often doesn't, so here they are.
  1646. libstdcxx_printer.add_container('std::', '_List_iterator',
  1647. StdListIteratorPrinter)
  1648. libstdcxx_printer.add_container('std::', '_List_const_iterator',
  1649. StdListIteratorPrinter)
  1650. libstdcxx_printer.add_version('std::', '_Rb_tree_iterator',
  1651. StdRbtreeIteratorPrinter)
  1652. libstdcxx_printer.add_version('std::', '_Rb_tree_const_iterator',
  1653. StdRbtreeIteratorPrinter)
  1654. libstdcxx_printer.add_container('std::', '_Deque_iterator',
  1655. StdDequeIteratorPrinter)
  1656. libstdcxx_printer.add_container('std::', '_Deque_const_iterator',
  1657. StdDequeIteratorPrinter)
  1658. libstdcxx_printer.add_version('__gnu_cxx::', '__normal_iterator',
  1659. StdVectorIteratorPrinter)
  1660. libstdcxx_printer.add_version('__gnu_cxx::', '_Slist_iterator',
  1661. StdSlistIteratorPrinter)
  1662. libstdcxx_printer.add_container('std::', '_Fwd_list_iterator',
  1663. StdFwdListIteratorPrinter)
  1664. libstdcxx_printer.add_container('std::', '_Fwd_list_const_iterator',
  1665. StdFwdListIteratorPrinter)
  1666. # Debug (compiled with -D_GLIBCXX_DEBUG) printer
  1667. # registrations.
  1668. libstdcxx_printer.add('__gnu_debug::_Safe_iterator',
  1669. StdDebugIteratorPrinter)
  1670. build_libstdcxx_dictionary ()