1 # Pretty-printers for libstdc++.
3 # Copyright (C) 2008-2018 Free Software Foundation, Inc.
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
23 ### Python 2 + Python 3 compatibility code
25 # Resources about compatibility:
27 # * <http://pythonhosted.org/six/>: Documentation of the "six" module
29 # FIXME: The handling of e.g. std::basic_string (at least on char)
30 # probably needs updating to work with Python 3's new string rules.
32 # In particular, Python 3 has a separate type (called byte) for
33 # bytestrings, and a special b"" syntax for the byte literals; the old
34 # str() type has been redefined to always store Unicode text.
36 # We probably can't do much about this until this GDB PR is addressed:
37 # <https://sourceware.org/bugzilla/show_bug.cgi?id=17138>
39 if sys
.version_info
[0] > 2:
42 # Python 3 folds these into the normal functions.
45 # Also, int subsumes long
50 """Compatibility mixin for iterators
52 Instead of writing next() methods for iterators, write
53 __next__() methods and use this mixin to make them work in
54 Python 2 as well as Python 3.
56 Idea stolen from the "six" documentation:
57 <http://pythonhosted.org/six/#six.Iterator>
61 return self
.__next
__()
63 # In Python 2, we still need these from itertools
64 from itertools
import imap
, izip
66 # Try to use the new-style pretty-printing if available.
73 # Try to install type-printers.
74 _use_type_printing
= False
77 if hasattr(gdb
.types
, 'TypePrinter'):
78 _use_type_printing
= True
82 # Starting with the type ORIG, search for the member type NAME. This
83 # handles searching upward through superclasses. This is needed to
84 # work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
85 def find_type(orig
, name
):
86 typ
= orig
.strip_typedefs()
88 # Strip cv-qualifiers. PR 67440.
89 search
= '%s::%s' % (typ
.unqualified(), name
)
91 return gdb
.lookup_type(search
)
94 # The type was not found, so try the superclass. We only need
95 # to check the first superclass, so we don't bother with
96 # anything fancier here.
97 field
= typ
.fields()[0]
98 if not field
.is_base_class
:
99 raise ValueError("Cannot find type %s::%s" % (str(orig
), name
))
102 _versioned_namespace
= '__8::'
104 def is_specialization_of(x
, template_name
):
105 "Test if a type is a given template instantiation."
106 global _versioned_namespace
107 if type(x
) is gdb
.Type
:
109 if _versioned_namespace
:
110 return re
.match('^std::(%s)?%s<.*>$' % (_versioned_namespace
, template_name
), x
) is not None
111 return re
.match('^std::%s<.*>$' % template_name
, x
) is not None
113 def strip_versioned_namespace(typename
):
114 global _versioned_namespace
115 if _versioned_namespace
:
116 return typename
.replace(_versioned_namespace
, '')
119 def strip_inline_namespaces(type_str
):
120 "Remove known inline namespaces from the canonical name of a type."
121 type_str
= strip_versioned_namespace(type_str
)
122 type_str
= type_str
.replace('std::__cxx11::', 'std::')
123 expt_ns
= 'std::experimental::'
124 for lfts_ns
in ('fundamentals_v1', 'fundamentals_v2'):
125 type_str
= type_str
.replace(expt_ns
+lfts_ns
+'::', expt_ns
)
126 fs_ns
= expt_ns
+ 'filesystem::'
127 type_str
= type_str
.replace(fs_ns
+'v1::', fs_ns
)
130 def get_template_arg_list(type_obj
):
131 "Return a type's template arguments as a list"
136 template_args
.append(type_obj
.template_argument(n
))
141 class SmartPtrIterator(Iterator
):
142 "An iterator for smart pointer types with a single 'child' value"
144 def __init__(self
, val
):
153 self
.val
, val
= None, self
.val
154 return ('get()', val
)
156 class SharedPointerPrinter
:
157 "Print a shared_ptr or weak_ptr"
159 def __init__ (self
, typename
, val
):
160 self
.typename
= strip_versioned_namespace(typename
)
162 self
.pointer
= val
['_M_ptr']
165 return SmartPtrIterator(self
.pointer
)
167 def to_string (self
):
169 refcounts
= self
.val
['_M_refcount']['_M_pi']
171 usecount
= refcounts
['_M_use_count']
172 weakcount
= refcounts
['_M_weak_count']
174 state
= 'expired, weak count %d' % weakcount
176 state
= 'use count %d, weak count %d' % (usecount
, weakcount
- 1)
177 return '%s<%s> (%s)' % (self
.typename
, str(self
.val
.type.template_argument(0)), state
)
179 class UniquePointerPrinter
:
182 def __init__ (self
, typename
, val
):
184 impl_type
= val
.type.fields()[0].type.tag
185 if is_specialization_of(impl_type
, '__uniq_ptr_impl'): # New implementation
186 self
.pointer
= val
['_M_t']['_M_t']['_M_head_impl']
187 elif is_specialization_of(impl_type
, 'tuple'):
188 self
.pointer
= val
['_M_t']['_M_head_impl']
190 raise ValueError("Unsupported implementation for unique_ptr: %s" % impl_type
)
193 return SmartPtrIterator(self
.pointer
)
195 def to_string (self
):
196 return ('std::unique_ptr<%s>' % (str(self
.val
.type.template_argument(0))))
198 def get_value_from_aligned_membuf(buf
, valtype
):
199 """Returns the value held in a __gnu_cxx::__aligned_membuf."""
200 return buf
['_M_storage'].address
.cast(valtype
.pointer()).dereference()
202 def get_value_from_list_node(node
):
203 """Returns the value held in an _List_node<_Val>"""
205 member
= node
.type.fields()[1].name
206 if member
== '_M_data':
207 # C++03 implementation, node contains the value as a member
208 return node
['_M_data']
209 elif member
== '_M_storage':
210 # C++11 implementation, node stores value in __aligned_membuf
211 valtype
= node
.type.template_argument(0)
212 return get_value_from_aligned_membuf(node
['_M_storage'], valtype
)
215 raise ValueError("Unsupported implementation for %s" % str(node
.type))
217 class StdListPrinter
:
220 class _iterator(Iterator
):
221 def __init__(self
, nodetype
, head
):
222 self
.nodetype
= nodetype
223 self
.base
= head
['_M_next']
224 self
.head
= head
.address
231 if self
.base
== self
.head
:
233 elt
= self
.base
.cast(self
.nodetype
).dereference()
234 self
.base
= elt
['_M_next']
236 self
.count
= self
.count
+ 1
237 val
= get_value_from_list_node(elt
)
238 return ('[%d]' % count
, val
)
240 def __init__(self
, typename
, val
):
241 self
.typename
= strip_versioned_namespace(typename
)
245 nodetype
= find_type(self
.val
.type, '_Node')
246 nodetype
= nodetype
.strip_typedefs().pointer()
247 return self
._iterator
(nodetype
, self
.val
['_M_impl']['_M_node'])
250 if self
.val
['_M_impl']['_M_node'].address
== self
.val
['_M_impl']['_M_node']['_M_next']:
251 return 'empty %s' % (self
.typename
)
252 return '%s' % (self
.typename
)
254 class NodeIteratorPrinter
:
255 def __init__(self
, typename
, val
, contname
):
257 self
.typename
= typename
258 self
.contname
= contname
261 if not self
.val
['_M_node']:
262 return 'non-dereferenceable iterator for std::%s' % (self
.contname
)
263 nodetype
= find_type(self
.val
.type, '_Node')
264 nodetype
= nodetype
.strip_typedefs().pointer()
265 node
= self
.val
['_M_node'].cast(nodetype
).dereference()
266 return str(get_value_from_list_node(node
))
268 class StdListIteratorPrinter(NodeIteratorPrinter
):
269 "Print std::list::iterator"
271 def __init__(self
, typename
, val
):
272 NodeIteratorPrinter
.__init
__(self
, typename
, val
, 'list')
274 class StdFwdListIteratorPrinter(NodeIteratorPrinter
):
275 "Print std::forward_list::iterator"
277 def __init__(self
, typename
, val
):
278 NodeIteratorPrinter
.__init
__(self
, typename
, val
, 'forward_list')
280 class StdSlistPrinter
:
281 "Print a __gnu_cxx::slist"
283 class _iterator(Iterator
):
284 def __init__(self
, nodetype
, head
):
285 self
.nodetype
= nodetype
286 self
.base
= head
['_M_head']['_M_next']
295 elt
= self
.base
.cast(self
.nodetype
).dereference()
296 self
.base
= elt
['_M_next']
298 self
.count
= self
.count
+ 1
299 return ('[%d]' % count
, elt
['_M_data'])
301 def __init__(self
, typename
, val
):
305 nodetype
= find_type(self
.val
.type, '_Node')
306 nodetype
= nodetype
.strip_typedefs().pointer()
307 return self
._iterator
(nodetype
, self
.val
)
310 if self
.val
['_M_head']['_M_next'] == 0:
311 return 'empty __gnu_cxx::slist'
312 return '__gnu_cxx::slist'
314 class StdSlistIteratorPrinter
:
315 "Print __gnu_cxx::slist::iterator"
317 def __init__(self
, typename
, val
):
321 if not self
.val
['_M_node']:
322 return 'non-dereferenceable iterator for __gnu_cxx::slist'
323 nodetype
= find_type(self
.val
.type, '_Node')
324 nodetype
= nodetype
.strip_typedefs().pointer()
325 return str(self
.val
['_M_node'].cast(nodetype
).dereference()['_M_data'])
327 class StdVectorPrinter
:
328 "Print a std::vector"
330 class _iterator(Iterator
):
331 def __init__ (self
, start
, finish
, bitvec
):
334 self
.item
= start
['_M_p']
335 self
.so
= start
['_M_offset']
336 self
.finish
= finish
['_M_p']
337 self
.fo
= finish
['_M_offset']
338 itype
= self
.item
.dereference().type
339 self
.isize
= 8 * itype
.sizeof
350 self
.count
= self
.count
+ 1
352 if self
.item
== self
.finish
and self
.so
>= self
.fo
:
354 elt
= self
.item
.dereference()
355 if elt
& (1 << self
.so
):
359 self
.so
= self
.so
+ 1
360 if self
.so
>= self
.isize
:
361 self
.item
= self
.item
+ 1
363 return ('[%d]' % count
, obit
)
365 if self
.item
== self
.finish
:
367 elt
= self
.item
.dereference()
368 self
.item
= self
.item
+ 1
369 return ('[%d]' % count
, elt
)
371 def __init__(self
, typename
, val
):
372 self
.typename
= strip_versioned_namespace(typename
)
374 self
.is_bool
= val
.type.template_argument(0).code
== gdb
.TYPE_CODE_BOOL
377 return self
._iterator
(self
.val
['_M_impl']['_M_start'],
378 self
.val
['_M_impl']['_M_finish'],
382 start
= self
.val
['_M_impl']['_M_start']
383 finish
= self
.val
['_M_impl']['_M_finish']
384 end
= self
.val
['_M_impl']['_M_end_of_storage']
386 start
= self
.val
['_M_impl']['_M_start']['_M_p']
387 so
= self
.val
['_M_impl']['_M_start']['_M_offset']
388 finish
= self
.val
['_M_impl']['_M_finish']['_M_p']
389 fo
= self
.val
['_M_impl']['_M_finish']['_M_offset']
390 itype
= start
.dereference().type
391 bl
= 8 * itype
.sizeof
392 length
= (bl
- so
) + bl
* ((finish
- start
) - 1) + fo
393 capacity
= bl
* (end
- start
)
394 return ('%s<bool> of length %d, capacity %d'
395 % (self
.typename
, int (length
), int (capacity
)))
397 return ('%s of length %d, capacity %d'
398 % (self
.typename
, int (finish
- start
), int (end
- start
)))
400 def display_hint(self
):
403 class StdVectorIteratorPrinter
:
404 "Print std::vector::iterator"
406 def __init__(self
, typename
, val
):
410 if not self
.val
['_M_current']:
411 return 'non-dereferenceable iterator for std::vector'
412 return str(self
.val
['_M_current'].dereference())
414 class StdTuplePrinter
:
417 class _iterator(Iterator
):
419 def _is_nonempty_tuple (nodes
):
421 if is_specialization_of (nodes
[1].type, '__tuple_base'):
423 elif len (nodes
) == 1:
425 elif len (nodes
) == 0:
427 raise ValueError("Top of tuple tree does not consist of a single node.")
429 def __init__ (self
, head
):
432 # Set the base class as the initial head of the
434 nodes
= self
.head
.type.fields ()
435 if self
._is
_nonempty
_tuple
(nodes
):
436 # Set the actual head to the first pair.
437 self
.head
= self
.head
.cast (nodes
[0].type)
444 # Check for further recursions in the inheritance tree.
445 # For a GCC 5+ tuple self.head is None after visiting all nodes:
448 nodes
= self
.head
.type.fields ()
449 # For a GCC 4.x tuple there is a final node with no fields:
452 # Check that this iteration has an expected structure.
454 raise ValueError("Cannot parse more than 2 nodes in a tuple tree.")
457 # This is the last node of a GCC 5+ std::tuple.
458 impl
= self
.head
.cast (nodes
[0].type)
461 # Either a node before the last node, or the last node of
462 # a GCC 4.x tuple (which has an empty parent).
464 # - Left node is the next recursion parent.
465 # - Right node is the actual class contained in the tuple.
467 # Process right node.
468 impl
= self
.head
.cast (nodes
[1].type)
470 # Process left node and set it as head.
471 self
.head
= self
.head
.cast (nodes
[0].type)
473 self
.count
= self
.count
+ 1
475 # Finally, check the implementation. If it is
476 # wrapped in _M_head_impl return that, otherwise return
478 fields
= impl
.type.fields ()
479 if len (fields
) < 1 or fields
[0].name
!= "_M_head_impl":
480 return ('[%d]' % self
.count
, impl
)
482 return ('[%d]' % self
.count
, impl
['_M_head_impl'])
484 def __init__ (self
, typename
, val
):
485 self
.typename
= strip_versioned_namespace(typename
)
489 return self
._iterator
(self
.val
)
491 def to_string (self
):
492 if len (self
.val
.type.fields ()) == 0:
493 return 'empty %s' % (self
.typename
)
494 return '%s containing' % (self
.typename
)
496 class StdStackOrQueuePrinter
:
497 "Print a std::stack or std::queue"
499 def __init__ (self
, typename
, val
):
500 self
.typename
= strip_versioned_namespace(typename
)
501 self
.visualizer
= gdb
.default_visualizer(val
['c'])
504 return self
.visualizer
.children()
506 def to_string (self
):
507 return '%s wrapping: %s' % (self
.typename
,
508 self
.visualizer
.to_string())
510 def display_hint (self
):
511 if hasattr (self
.visualizer
, 'display_hint'):
512 return self
.visualizer
.display_hint ()
515 class RbtreeIterator(Iterator
):
517 Turn an RB-tree-based container (std::map, std::set etc.) into
518 a Python iterable object.
521 def __init__(self
, rbtree
):
522 self
.size
= rbtree
['_M_t']['_M_impl']['_M_node_count']
523 self
.node
= rbtree
['_M_t']['_M_impl']['_M_header']['_M_left']
530 return int (self
.size
)
533 if self
.count
== self
.size
:
536 self
.count
= self
.count
+ 1
537 if self
.count
< self
.size
:
538 # Compute the next node.
540 if node
.dereference()['_M_right']:
541 node
= node
.dereference()['_M_right']
542 while node
.dereference()['_M_left']:
543 node
= node
.dereference()['_M_left']
545 parent
= node
.dereference()['_M_parent']
546 while node
== parent
.dereference()['_M_right']:
548 parent
= parent
.dereference()['_M_parent']
549 if node
.dereference()['_M_right'] != parent
:
554 def get_value_from_Rb_tree_node(node
):
555 """Returns the value held in an _Rb_tree_node<_Val>"""
557 member
= node
.type.fields()[1].name
558 if member
== '_M_value_field':
559 # C++03 implementation, node contains the value as a member
560 return node
['_M_value_field']
561 elif member
== '_M_storage':
562 # C++11 implementation, node stores value in __aligned_membuf
563 valtype
= node
.type.template_argument(0)
564 return get_value_from_aligned_membuf(node
['_M_storage'], valtype
)
567 raise ValueError("Unsupported implementation for %s" % str(node
.type))
569 # This is a pretty printer for std::_Rb_tree_iterator (which is
570 # std::map::iterator), and has nothing to do with the RbtreeIterator
572 class StdRbtreeIteratorPrinter
:
573 "Print std::map::iterator, std::set::iterator, etc."
575 def __init__ (self
, typename
, val
):
577 valtype
= self
.val
.type.template_argument(0).strip_typedefs()
578 nodetype
= '_Rb_tree_node<' + str(valtype
) + '>'
579 if _versioned_namespace
and typename
.startswith('std::' + _versioned_namespace
):
580 nodetype
= _versioned_namespace
+ nodetype
581 nodetype
= gdb
.lookup_type('std::' + nodetype
)
582 self
.link_type
= nodetype
.strip_typedefs().pointer()
584 def to_string (self
):
585 if not self
.val
['_M_node']:
586 return 'non-dereferenceable iterator for associative container'
587 node
= self
.val
['_M_node'].cast(self
.link_type
).dereference()
588 return str(get_value_from_Rb_tree_node(node
))
590 class StdDebugIteratorPrinter
:
591 "Print a debug enabled version of an iterator"
593 def __init__ (self
, typename
, val
):
596 # Just strip away the encapsulating __gnu_debug::_Safe_iterator
597 # and return the wrapped iterator value.
598 def to_string (self
):
599 base_type
= gdb
.lookup_type('__gnu_debug::_Safe_iterator_base')
600 itype
= self
.val
.type.template_argument(0)
601 safe_seq
= self
.val
.cast(base_type
)['_M_sequence']
603 return str(self
.val
.cast(itype
))
604 if self
.val
['_M_version'] != safe_seq
['_M_version']:
605 return "invalid iterator"
606 return str(self
.val
.cast(itype
))
608 def num_elements(num
):
609 """Return either "1 element" or "N elements" depending on the argument."""
610 return '1 element' if num
== 1 else '%d elements' % num
613 "Print a std::map or std::multimap"
615 # Turn an RbtreeIterator into a pretty-print iterator.
616 class _iter(Iterator
):
617 def __init__(self
, rbiter
, type):
626 if self
.count
% 2 == 0:
627 n
= next(self
.rbiter
)
628 n
= n
.cast(self
.type).dereference()
629 n
= get_value_from_Rb_tree_node(n
)
633 item
= self
.pair
['second']
634 result
= ('[%d]' % self
.count
, item
)
635 self
.count
= self
.count
+ 1
638 def __init__ (self
, typename
, val
):
639 self
.typename
= strip_versioned_namespace(typename
)
642 def to_string (self
):
643 return '%s with %s' % (self
.typename
,
644 num_elements(len(RbtreeIterator (self
.val
))))
647 rep_type
= find_type(self
.val
.type, '_Rep_type')
648 node
= find_type(rep_type
, '_Link_type')
649 node
= node
.strip_typedefs()
650 return self
._iter
(RbtreeIterator (self
.val
), node
)
652 def display_hint (self
):
656 "Print a std::set or std::multiset"
658 # Turn an RbtreeIterator into a pretty-print iterator.
659 class _iter(Iterator
):
660 def __init__(self
, rbiter
, type):
669 item
= next(self
.rbiter
)
670 item
= item
.cast(self
.type).dereference()
671 item
= get_value_from_Rb_tree_node(item
)
672 # FIXME: this is weird ... what to do?
673 # Maybe a 'set' display hint?
674 result
= ('[%d]' % self
.count
, item
)
675 self
.count
= self
.count
+ 1
678 def __init__ (self
, typename
, val
):
679 self
.typename
= strip_versioned_namespace(typename
)
682 def to_string (self
):
683 return '%s with %s' % (self
.typename
,
684 num_elements(len(RbtreeIterator (self
.val
))))
687 rep_type
= find_type(self
.val
.type, '_Rep_type')
688 node
= find_type(rep_type
, '_Link_type')
689 node
= node
.strip_typedefs()
690 return self
._iter
(RbtreeIterator (self
.val
), node
)
692 class StdBitsetPrinter
:
693 "Print a std::bitset"
695 def __init__(self
, typename
, val
):
696 self
.typename
= strip_versioned_namespace(typename
)
699 def to_string (self
):
700 # If template_argument handled values, we could print the
701 # size. Or we could use a regexp on the type.
702 return '%s' % (self
.typename
)
705 words
= self
.val
['_M_w']
708 # The _M_w member can be either an unsigned long, or an
709 # array. This depends on the template specialization used.
710 # If it is a single long, convert to a single element list.
711 if wtype
.code
== gdb
.TYPE_CODE_ARRAY
:
712 tsize
= wtype
.target ().sizeof
717 nwords
= wtype
.sizeof
/ tsize
725 # Another spot where we could use 'set'?
726 result
.append(('[%d]' % (byte
* tsize
* 8 + bit
), 1))
732 class StdDequePrinter
:
735 class _iter(Iterator
):
736 def __init__(self
, node
, start
, end
, last
, buffer_size
):
741 self
.buffer_size
= buffer_size
748 if self
.p
== self
.last
:
751 result
= ('[%d]' % self
.count
, self
.p
.dereference())
752 self
.count
= self
.count
+ 1
754 # Advance the 'cur' pointer.
756 if self
.p
== self
.end
:
757 # If we got to the end of this bucket, move to the
759 self
.node
= self
.node
+ 1
760 self
.p
= self
.node
[0]
761 self
.end
= self
.p
+ self
.buffer_size
765 def __init__(self
, typename
, val
):
766 self
.typename
= strip_versioned_namespace(typename
)
768 self
.elttype
= val
.type.template_argument(0)
769 size
= self
.elttype
.sizeof
771 self
.buffer_size
= int (512 / size
)
776 start
= self
.val
['_M_impl']['_M_start']
777 end
= self
.val
['_M_impl']['_M_finish']
779 delta_n
= end
['_M_node'] - start
['_M_node'] - 1
780 delta_s
= start
['_M_last'] - start
['_M_cur']
781 delta_e
= end
['_M_cur'] - end
['_M_first']
783 size
= self
.buffer_size
* delta_n
+ delta_s
+ delta_e
785 return '%s with %s' % (self
.typename
, num_elements(long(size
)))
788 start
= self
.val
['_M_impl']['_M_start']
789 end
= self
.val
['_M_impl']['_M_finish']
790 return self
._iter
(start
['_M_node'], start
['_M_cur'], start
['_M_last'],
791 end
['_M_cur'], self
.buffer_size
)
793 def display_hint (self
):
796 class StdDequeIteratorPrinter
:
797 "Print std::deque::iterator"
799 def __init__(self
, typename
, val
):
803 if not self
.val
['_M_cur']:
804 return 'non-dereferenceable iterator for std::deque'
805 return str(self
.val
['_M_cur'].dereference())
807 class StdStringPrinter
:
808 "Print a std::basic_string of some kind"
810 def __init__(self
, typename
, val
):
812 self
.new_string
= typename
.find("::__cxx11::basic_string") != -1
815 # Make sure &string works, too.
817 if type.code
== gdb
.TYPE_CODE_REF
:
818 type = type.target ()
820 # Calculate the length of the string so that to_string returns
821 # the string according to length, not according to first null
823 ptr
= self
.val
['_M_dataplus']['_M_p']
825 length
= self
.val
['_M_string_length']
826 # https://sourceware.org/bugzilla/show_bug.cgi?id=17728
827 ptr
= ptr
.cast(ptr
.type.strip_typedefs())
829 realtype
= type.unqualified ().strip_typedefs ()
830 reptype
= gdb
.lookup_type (str (realtype
) + '::_Rep').pointer ()
831 header
= ptr
.cast(reptype
) - 1
832 length
= header
.dereference ()['_M_length']
833 if hasattr(ptr
, "lazy_string"):
834 return ptr
.lazy_string (length
= length
)
835 return ptr
.string (length
= length
)
837 def display_hint (self
):
840 class Tr1HashtableIterator(Iterator
):
841 def __init__ (self
, hash):
842 self
.buckets
= hash['_M_buckets']
844 self
.bucket_count
= hash['_M_bucket_count']
845 self
.node_type
= find_type(hash.type, '_Node').pointer()
847 while self
.bucket
!= self
.bucket_count
:
848 self
.node
= self
.buckets
[self
.bucket
]
851 self
.bucket
= self
.bucket
+ 1
859 node
= self
.node
.cast(self
.node_type
)
860 result
= node
.dereference()['_M_v']
861 self
.node
= node
.dereference()['_M_next'];
863 self
.bucket
= self
.bucket
+ 1
864 while self
.bucket
!= self
.bucket_count
:
865 self
.node
= self
.buckets
[self
.bucket
]
868 self
.bucket
= self
.bucket
+ 1
871 class StdHashtableIterator(Iterator
):
872 def __init__(self
, hash):
873 self
.node
= hash['_M_before_begin']['_M_nxt']
874 self
.node_type
= find_type(hash.type, '__node_type').pointer()
882 elt
= self
.node
.cast(self
.node_type
).dereference()
883 self
.node
= elt
['_M_nxt']
884 valptr
= elt
['_M_storage'].address
885 valptr
= valptr
.cast(elt
.type.template_argument(0).pointer())
886 return valptr
.dereference()
888 class Tr1UnorderedSetPrinter
:
889 "Print a tr1::unordered_set"
891 def __init__ (self
, typename
, val
):
892 self
.typename
= strip_versioned_namespace(typename
)
895 def hashtable (self
):
896 if self
.typename
.startswith('std::tr1'):
898 return self
.val
['_M_h']
900 def to_string (self
):
901 count
= self
.hashtable()['_M_element_count']
902 return '%s with %s' % (self
.typename
, num_elements(count
))
905 def format_count (i
):
909 counter
= imap (self
.format_count
, itertools
.count())
910 if self
.typename
.startswith('std::tr1'):
911 return izip (counter
, Tr1HashtableIterator (self
.hashtable()))
912 return izip (counter
, StdHashtableIterator (self
.hashtable()))
914 class Tr1UnorderedMapPrinter
:
915 "Print a tr1::unordered_map"
917 def __init__ (self
, typename
, val
):
918 self
.typename
= strip_versioned_namespace(typename
)
921 def hashtable (self
):
922 if self
.typename
.startswith('std::tr1'):
924 return self
.val
['_M_h']
926 def to_string (self
):
927 count
= self
.hashtable()['_M_element_count']
928 return '%s with %s' % (self
.typename
, num_elements(count
))
937 def format_one (elt
):
938 return (elt
['first'], elt
['second'])
941 def format_count (i
):
945 counter
= imap (self
.format_count
, itertools
.count())
946 # Map over the hash table and flatten the result.
947 if self
.typename
.startswith('std::tr1'):
948 data
= self
.flatten (imap (self
.format_one
, Tr1HashtableIterator (self
.hashtable())))
949 # Zip the two iterators together.
950 return izip (counter
, data
)
951 data
= self
.flatten (imap (self
.format_one
, StdHashtableIterator (self
.hashtable())))
952 # Zip the two iterators together.
953 return izip (counter
, data
)
956 def display_hint (self
):
959 class StdForwardListPrinter
:
960 "Print a std::forward_list"
962 class _iterator(Iterator
):
963 def __init__(self
, nodetype
, head
):
964 self
.nodetype
= nodetype
965 self
.base
= head
['_M_next']
974 elt
= self
.base
.cast(self
.nodetype
).dereference()
975 self
.base
= elt
['_M_next']
977 self
.count
= self
.count
+ 1
978 valptr
= elt
['_M_storage'].address
979 valptr
= valptr
.cast(elt
.type.template_argument(0).pointer())
980 return ('[%d]' % count
, valptr
.dereference())
982 def __init__(self
, typename
, val
):
984 self
.typename
= strip_versioned_namespace(typename
)
987 nodetype
= find_type(self
.val
.type, '_Node')
988 nodetype
= nodetype
.strip_typedefs().pointer()
989 return self
._iterator
(nodetype
, self
.val
['_M_impl']['_M_head'])
992 if self
.val
['_M_impl']['_M_head']['_M_next'] == 0:
993 return 'empty %s' % self
.typename
994 return '%s' % self
.typename
996 class SingleObjContainerPrinter(object):
997 "Base class for printers of containers of single objects"
999 def __init__ (self
, val
, viz
, hint
= None):
1000 self
.contained_value
= val
1001 self
.visualizer
= viz
1004 def _recognize(self
, type):
1005 """Return TYPE as a string after applying type printers"""
1006 global _use_type_printing
1007 if not _use_type_printing
:
1009 return gdb
.types
.apply_type_recognizers(gdb
.types
.get_type_recognizers(),
1012 class _contained(Iterator
):
1013 def __init__ (self
, val
):
1016 def __iter__ (self
):
1020 if self
.val
is None:
1024 return ('[contained value]', retval
)
1026 def children (self
):
1027 if self
.contained_value
is None:
1028 return self
._contained
(None)
1029 if hasattr (self
.visualizer
, 'children'):
1030 return self
.visualizer
.children ()
1031 return self
._contained
(self
.contained_value
)
1033 def display_hint (self
):
1034 # if contained value is a map we want to display in the same way
1035 if hasattr (self
.visualizer
, 'children') and hasattr (self
.visualizer
, 'display_hint'):
1036 return self
.visualizer
.display_hint ()
1039 class StdExpAnyPrinter(SingleObjContainerPrinter
):
1040 "Print a std::any or std::experimental::any"
1042 def __init__ (self
, typename
, val
):
1043 self
.typename
= strip_versioned_namespace(typename
)
1044 self
.typename
= re
.sub('^std::experimental::fundamentals_v\d::', 'std::experimental::', self
.typename
, 1)
1046 self
.contained_type
= None
1047 contained_value
= None
1049 mgr
= self
.val
['_M_manager']
1051 func
= gdb
.block_for_pc(int(mgr
.cast(gdb
.lookup_type('intptr_t'))))
1053 raise ValueError("Invalid function pointer in %s" % self
.typename
)
1054 rx
= r
"""({0}::_Manager_\w+<.*>)::_S_manage\((enum )?{0}::_Op, (const {0}|{0} const) ?\*, (union )?{0}::_Arg ?\*\)""".format(typename
)
1055 m
= re
.match(rx
, func
.function
.name
)
1057 raise ValueError("Unknown manager function in %s" % self
.typename
)
1059 mgrname
= m
.group(1)
1060 # FIXME need to expand 'std::string' so that gdb.lookup_type works
1061 if 'std::string' in mgrname
:
1062 mgrname
= re
.sub("std::string(?!\w)", str(gdb
.lookup_type('std::string').strip_typedefs()), m
.group(1))
1064 mgrtype
= gdb
.lookup_type(mgrname
)
1065 self
.contained_type
= mgrtype
.template_argument(0)
1067 if '::_Manager_internal' in mgrname
:
1068 valptr
= self
.val
['_M_storage']['_M_buffer'].address
1069 elif '::_Manager_external' in mgrname
:
1070 valptr
= self
.val
['_M_storage']['_M_ptr']
1072 raise ValueError("Unknown manager function in %s" % self
.typename
)
1073 contained_value
= valptr
.cast(self
.contained_type
.pointer()).dereference()
1074 visualizer
= gdb
.default_visualizer(contained_value
)
1075 super(StdExpAnyPrinter
, self
).__init
__ (contained_value
, visualizer
)
1077 def to_string (self
):
1078 if self
.contained_type
is None:
1079 return '%s [no contained value]' % self
.typename
1080 desc
= "%s containing " % self
.typename
1081 if hasattr (self
.visualizer
, 'children'):
1082 return desc
+ self
.visualizer
.to_string ()
1083 valtype
= self
._recognize
(self
.contained_type
)
1084 return desc
+ strip_versioned_namespace(str(valtype
))
1086 class StdExpOptionalPrinter(SingleObjContainerPrinter
):
1087 "Print a std::optional or std::experimental::optional"
1089 def __init__ (self
, typename
, val
):
1090 valtype
= self
._recognize
(val
.type.template_argument(0))
1091 self
.typename
= strip_versioned_namespace(typename
)
1092 self
.typename
= re
.sub('^std::(experimental::|)(fundamentals_v\d::|)(.*)', r
'std::\1\3<%s>' % valtype
, self
.typename
, 1)
1093 if not self
.typename
.startswith('std::experimental'):
1094 val
= val
['_M_payload']
1096 contained_value
= val
['_M_payload'] if self
.val
['_M_engaged'] else None
1097 visualizer
= gdb
.default_visualizer (val
['_M_payload'])
1098 super (StdExpOptionalPrinter
, self
).__init
__ (contained_value
, visualizer
)
1100 def to_string (self
):
1101 if self
.contained_value
is None:
1102 return "%s [no contained value]" % self
.typename
1103 if hasattr (self
.visualizer
, 'children'):
1104 return "%s containing %s" % (self
.typename
,
1105 self
.visualizer
.to_string())
1106 return self
.typename
1108 class StdVariantPrinter(SingleObjContainerPrinter
):
1109 "Print a std::variant"
1111 def __init__(self
, typename
, val
):
1112 alternatives
= get_template_arg_list(val
.type)
1113 self
.typename
= strip_versioned_namespace(typename
)
1114 self
.typename
= "%s<%s>" % (self
.typename
, ', '.join([self
._recognize
(alt
) for alt
in alternatives
]))
1115 self
.index
= val
['_M_index']
1116 if self
.index
>= len(alternatives
):
1117 self
.contained_type
= None
1118 contained_value
= None
1121 self
.contained_type
= alternatives
[int(self
.index
)]
1122 addr
= val
['_M_u']['_M_first']['_M_storage'].address
1123 contained_value
= addr
.cast(self
.contained_type
.pointer()).dereference()
1124 visualizer
= gdb
.default_visualizer(contained_value
)
1125 super (StdVariantPrinter
, self
).__init
__(contained_value
, visualizer
, 'array')
1127 def to_string(self
):
1128 if self
.contained_value
is None:
1129 return "%s [no contained value]" % self
.typename
1130 if hasattr(self
.visualizer
, 'children'):
1131 return "%s [index %d] containing %s" % (self
.typename
, self
.index
,
1132 self
.visualizer
.to_string())
1133 return "%s [index %d]" % (self
.typename
, self
.index
)
1135 class StdNodeHandlePrinter(SingleObjContainerPrinter
):
1136 "Print a container node handle"
1138 def __init__(self
, typename
, val
):
1139 self
.value_type
= val
.type.template_argument(1)
1140 nodetype
= val
.type.template_argument(2).template_argument(0)
1141 self
.is_rb_tree_node
= is_specialization_of(nodetype
.name
, '_Rb_tree_node')
1142 self
.is_map_node
= val
.type.template_argument(0) != self
.value_type
1143 nodeptr
= val
['_M_ptr']
1145 if self
.is_rb_tree_node
:
1146 contained_value
= get_value_from_Rb_tree_node(nodeptr
.dereference())
1148 contained_value
= get_value_from_aligned_membuf(nodeptr
['_M_storage'],
1150 visualizer
= gdb
.default_visualizer(contained_value
)
1152 contained_value
= None
1154 optalloc
= val
['_M_alloc']
1155 self
.alloc
= optalloc
['_M_payload'] if optalloc
['_M_engaged'] else None
1156 super(StdNodeHandlePrinter
, self
).__init
__(contained_value
, visualizer
,
1159 def to_string(self
):
1160 desc
= 'node handle for '
1161 if not self
.is_rb_tree_node
:
1162 desc
+= 'unordered '
1163 if self
.is_map_node
:
1168 if self
.contained_value
:
1169 desc
+= ' with element'
1170 if hasattr(self
.visualizer
, 'children'):
1171 return "%s = %s" % (desc
, self
.visualizer
.to_string())
1174 return 'empty %s' % desc
1176 class StdExpStringViewPrinter
:
1177 "Print a std::basic_string_view or std::experimental::basic_string_view"
1179 def __init__ (self
, typename
, val
):
1182 def to_string (self
):
1183 ptr
= self
.val
['_M_str']
1184 len = self
.val
['_M_len']
1185 if hasattr (ptr
, "lazy_string"):
1186 return ptr
.lazy_string (length
= len)
1187 return ptr
.string (length
= len)
1189 def display_hint (self
):
1192 class StdExpPathPrinter
:
1193 "Print a std::experimental::filesystem::path"
1195 def __init__ (self
, typename
, val
):
1197 start
= self
.val
['_M_cmpts']['_M_impl']['_M_start']
1198 finish
= self
.val
['_M_cmpts']['_M_impl']['_M_finish']
1199 self
.num_cmpts
= int (finish
- start
)
1201 def _path_type(self
):
1202 t
= str(self
.val
['_M_type'])
1203 if t
[-9:] == '_Root_dir':
1204 return "root-directory"
1205 if t
[-10:] == '_Root_name':
1209 def to_string (self
):
1210 path
= "%s" % self
.val
['_M_pathname']
1211 if self
.num_cmpts
== 0:
1212 t
= self
._path
_type
()
1214 path
= '%s [%s]' % (path
, t
)
1215 return "filesystem::path %s" % path
1217 class _iterator(Iterator
):
1218 def __init__(self
, cmpts
):
1219 self
.item
= cmpts
['_M_impl']['_M_start']
1220 self
.finish
= cmpts
['_M_impl']['_M_finish']
1227 if self
.item
== self
.finish
:
1229 item
= self
.item
.dereference()
1231 self
.count
= self
.count
+ 1
1232 self
.item
= self
.item
+ 1
1233 path
= item
['_M_pathname']
1234 t
= StdExpPathPrinter(item
.type.name
, item
)._path
_type
()
1237 return ('[%s]' % t
, path
)
1240 return self
._iterator
(self
.val
['_M_cmpts'])
1243 class StdPairPrinter
:
1244 "Print a std::pair object, with 'first' and 'second' as children"
1246 def __init__(self
, typename
, val
):
1249 class _iter(Iterator
):
1250 "An iterator for std::pair types. Returns 'first' then 'second'."
1252 def __init__(self
, val
):
1254 self
.which
= 'first'
1260 if self
.which
is None:
1263 if which
== 'first':
1264 self
.which
= 'second'
1267 return (which
, self
.val
[which
])
1270 return self
._iter
(self
.val
)
1272 def to_string(self
):
1276 # A "regular expression" printer which conforms to the
1277 # "SubPrettyPrinter" protocol from gdb.printing.
1278 class RxPrinter(object):
1279 def __init__(self
, name
, function
):
1280 super(RxPrinter
, self
).__init
__()
1282 self
.function
= function
1285 def invoke(self
, value
):
1286 if not self
.enabled
:
1289 if value
.type.code
== gdb
.TYPE_CODE_REF
:
1290 if hasattr(gdb
.Value
,"referenced_value"):
1291 value
= value
.referenced_value()
1293 return self
.function(self
.name
, value
)
1295 # A pretty-printer that conforms to the "PrettyPrinter" protocol from
1296 # gdb.printing. It can also be used directly as an old-style printer.
1297 class Printer(object):
1298 def __init__(self
, name
):
1299 super(Printer
, self
).__init
__()
1301 self
.subprinters
= []
1304 self
.compiled_rx
= re
.compile('^([a-zA-Z0-9_:]+)(<.*>)?$')
1306 def add(self
, name
, function
):
1307 # A small sanity check.
1309 if not self
.compiled_rx
.match(name
):
1310 raise ValueError('libstdc++ programming error: "%s" does not match' % name
)
1311 printer
= RxPrinter(name
, function
)
1312 self
.subprinters
.append(printer
)
1313 self
.lookup
[name
] = printer
1315 # Add a name using _GLIBCXX_BEGIN_NAMESPACE_VERSION.
1316 def add_version(self
, base
, name
, function
):
1317 self
.add(base
+ name
, function
)
1318 if _versioned_namespace
:
1319 vbase
= re
.sub('^(std|__gnu_cxx)::', r
'\g<0>%s' % _versioned_namespace
, base
)
1320 self
.add(vbase
+ name
, function
)
1322 # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
1323 def add_container(self
, base
, name
, function
):
1324 self
.add_version(base
, name
, function
)
1325 self
.add_version(base
+ '__cxx1998::', name
, function
)
1328 def get_basic_type(type):
1329 # If it points to a reference, get the reference.
1330 if type.code
== gdb
.TYPE_CODE_REF
:
1331 type = type.target ()
1333 # Get the unqualified type, stripped of typedefs.
1334 type = type.unqualified ().strip_typedefs ()
1338 def __call__(self
, val
):
1339 typename
= self
.get_basic_type(val
.type)
1343 # All the types we match are template types, so we can use a
1345 match
= self
.compiled_rx
.match(typename
)
1349 basename
= match
.group(1)
1351 if val
.type.code
== gdb
.TYPE_CODE_REF
:
1352 if hasattr(gdb
.Value
,"referenced_value"):
1353 val
= val
.referenced_value()
1355 if basename
in self
.lookup
:
1356 return self
.lookup
[basename
].invoke(val
)
1358 # Cannot find a pretty printer. Return None.
1361 libstdcxx_printer
= None
1363 class TemplateTypePrinter(object):
1365 A type printer for class templates with default template arguments.
1367 Recognizes specializations of class templates and prints them without
1368 any template arguments that use a default template argument.
1369 Type printers are recursively applied to the template arguments.
1371 e.g. replace "std::vector<T, std::allocator<T> >" with "std::vector<T>".
1374 def __init__(self
, name
, defargs
):
1376 self
.defargs
= defargs
1379 class _recognizer(object):
1380 "The recognizer class for TemplateTypePrinter."
1382 def __init__(self
, name
, defargs
):
1384 self
.defargs
= defargs
1385 # self.type_obj = None
1387 def recognize(self
, type_obj
):
1389 If type_obj is a specialization of self.name that uses all the
1390 default template arguments for the class template, then return
1391 a string representation of the type without default arguments.
1392 Otherwise, return None.
1395 if type_obj
.tag
is None:
1398 if not type_obj
.tag
.startswith(self
.name
):
1401 template_args
= get_template_arg_list(type_obj
)
1403 require_defaulted
= False
1404 for n
in range(len(template_args
)):
1405 # The actual template argument in the type:
1406 targ
= template_args
[n
]
1407 # The default template argument for the class template:
1408 defarg
= self
.defargs
.get(n
)
1409 if defarg
is not None:
1410 # Substitute other template arguments into the default:
1411 defarg
= defarg
.format(*template_args
)
1412 # Fail to recognize the type (by returning None)
1413 # unless the actual argument is the same as the default.
1415 if targ
!= gdb
.lookup_type(defarg
):
1418 # Type lookup failed, just use string comparison:
1419 if targ
.tag
!= defarg
:
1421 # All subsequent args must have defaults:
1422 require_defaulted
= True
1423 elif require_defaulted
:
1426 # Recursively apply recognizers to the template argument
1427 # and add it to the arguments that will be displayed:
1428 displayed_args
.append(self
._recognize
_subtype
(targ
))
1430 # This assumes no class templates in the nested-name-specifier:
1431 template_name
= type_obj
.tag
[0:type_obj
.tag
.find('<')]
1432 template_name
= strip_inline_namespaces(template_name
)
1434 return template_name
+ '<' + ', '.join(displayed_args
) + '>'
1436 def _recognize_subtype(self
, type_obj
):
1437 """Convert a gdb.Type to a string by applying recognizers,
1438 or if that fails then simply converting to a string."""
1440 if type_obj
.code
== gdb
.TYPE_CODE_PTR
:
1441 return self
._recognize
_subtype
(type_obj
.target()) + '*'
1442 if type_obj
.code
== gdb
.TYPE_CODE_ARRAY
:
1443 type_str
= self
._recognize
_subtype
(type_obj
.target())
1444 if str(type_obj
.strip_typedefs()).endswith('[]'):
1445 return type_str
+ '[]' # array of unknown bound
1446 return "%s[%d]" % (type_str
, type_obj
.range()[1] + 1)
1447 if type_obj
.code
== gdb
.TYPE_CODE_REF
:
1448 return self
._recognize
_subtype
(type_obj
.target()) + '&'
1449 if hasattr(gdb
, 'TYPE_CODE_RVALUE_REF'):
1450 if type_obj
.code
== gdb
.TYPE_CODE_RVALUE_REF
:
1451 return self
._recognize
_subtype
(type_obj
.target()) + '&&'
1453 type_str
= gdb
.types
.apply_type_recognizers(
1454 gdb
.types
.get_type_recognizers(), type_obj
)
1457 return str(type_obj
)
1459 def instantiate(self
):
1460 "Return a recognizer object for this type printer."
1461 return self
._recognizer
(self
.name
, self
.defargs
)
1463 def add_one_template_type_printer(obj
, name
, defargs
):
1465 Add a type printer for a class template with default template arguments.
1468 name (str): The template-name of the class template.
1469 defargs (dict int:string) The default template arguments.
1471 Types in defargs can refer to the Nth template-argument using {N}
1472 (with zero-based indices).
1474 e.g. 'unordered_map' has these defargs:
1475 { 2: 'std::hash<{0}>',
1476 3: 'std::equal_to<{0}>',
1477 4: 'std::allocator<std::pair<const {0}, {1}> >' }
1480 printer
= TemplateTypePrinter('std::'+name
, defargs
)
1481 gdb
.types
.register_type_printer(obj
, printer
)
1482 if _versioned_namespace
:
1483 # Add second type printer for same type in versioned namespace:
1484 ns
= 'std::' + _versioned_namespace
1485 # PR 86112 Cannot use dict comprehension here:
1486 defargs
= dict((n
, d
.replace('std::', ns
)) for (n
,d
) in defargs
.items())
1487 printer
= TemplateTypePrinter(ns
+name
, defargs
)
1488 gdb
.types
.register_type_printer(obj
, printer
)
1490 class FilteringTypePrinter(object):
1492 A type printer that uses typedef names for common template specializations.
1495 match (str): The class template to recognize.
1496 name (str): The typedef-name that will be used instead.
1498 Checks if a specialization of the class template 'match' is the same type
1499 as the typedef 'name', and prints it as 'name' instead.
1501 e.g. if an instantiation of std::basic_istream<C, T> is the same type as
1502 std::istream then print it as std::istream.
1505 def __init__(self
, match
, name
):
1510 class _recognizer(object):
1511 "The recognizer class for TemplateTypePrinter."
1513 def __init__(self
, match
, name
):
1516 self
.type_obj
= None
1518 def recognize(self
, type_obj
):
1520 If type_obj starts with self.match and is the same type as
1521 self.name then return self.name, otherwise None.
1523 if type_obj
.tag
is None:
1526 if self
.type_obj
is None:
1527 if not type_obj
.tag
.startswith(self
.match
):
1528 # Filter didn't match.
1531 self
.type_obj
= gdb
.lookup_type(self
.name
).strip_typedefs()
1534 if self
.type_obj
== type_obj
:
1535 return strip_inline_namespaces(self
.name
)
1538 def instantiate(self
):
1539 "Return a recognizer object for this type printer."
1540 return self
._recognizer
(self
.match
, self
.name
)
1542 def add_one_type_printer(obj
, match
, name
):
1543 printer
= FilteringTypePrinter('std::' + match
, 'std::' + name
)
1544 gdb
.types
.register_type_printer(obj
, printer
)
1545 if _versioned_namespace
:
1546 ns
= 'std::' + _versioned_namespace
1547 printer
= FilteringTypePrinter(ns
+ match
, ns
+ name
)
1548 gdb
.types
.register_type_printer(obj
, printer
)
1550 def register_type_printers(obj
):
1551 global _use_type_printing
1553 if not _use_type_printing
:
1556 # Add type printers for typedefs std::string, std::wstring etc.
1557 for ch
in ('', 'w', 'u16', 'u32'):
1558 add_one_type_printer(obj
, 'basic_string', ch
+ 'string')
1559 add_one_type_printer(obj
, '__cxx11::basic_string', ch
+ 'string')
1560 # Typedefs for __cxx11::basic_string used to be in namespace __cxx11:
1561 add_one_type_printer(obj
, '__cxx11::basic_string',
1562 '__cxx11::' + ch
+ 'string')
1563 add_one_type_printer(obj
, 'basic_string_view', ch
+ 'string_view')
1565 # Add type printers for typedefs std::istream, std::wistream etc.
1566 for ch
in ('', 'w'):
1567 for x
in ('ios', 'streambuf', 'istream', 'ostream', 'iostream',
1568 'filebuf', 'ifstream', 'ofstream', 'fstream'):
1569 add_one_type_printer(obj
, 'basic_' + x
, ch
+ x
)
1570 for x
in ('stringbuf', 'istringstream', 'ostringstream',
1572 add_one_type_printer(obj
, 'basic_' + x
, ch
+ x
)
1573 # <sstream> types are in __cxx11 namespace, but typedefs aren't:
1574 add_one_type_printer(obj
, '__cxx11::basic_' + x
, ch
+ x
)
1576 # Add type printers for typedefs regex, wregex, cmatch, wcmatch etc.
1577 for abi
in ('', '__cxx11::'):
1578 for ch
in ('', 'w'):
1579 add_one_type_printer(obj
, abi
+ 'basic_regex', abi
+ ch
+ 'regex')
1580 for ch
in ('c', 's', 'wc', 'ws'):
1581 add_one_type_printer(obj
, abi
+ 'match_results', abi
+ ch
+ 'match')
1582 for x
in ('sub_match', 'regex_iterator', 'regex_token_iterator'):
1583 add_one_type_printer(obj
, abi
+ x
, abi
+ ch
+ x
)
1585 # Note that we can't have a printer for std::wstreampos, because
1586 # it is the same type as std::streampos.
1587 add_one_type_printer(obj
, 'fpos', 'streampos')
1589 # Add type printers for <chrono> typedefs.
1590 for dur
in ('nanoseconds', 'microseconds', 'milliseconds',
1591 'seconds', 'minutes', 'hours'):
1592 add_one_type_printer(obj
, 'duration', dur
)
1594 # Add type printers for <random> typedefs.
1595 add_one_type_printer(obj
, 'linear_congruential_engine', 'minstd_rand0')
1596 add_one_type_printer(obj
, 'linear_congruential_engine', 'minstd_rand')
1597 add_one_type_printer(obj
, 'mersenne_twister_engine', 'mt19937')
1598 add_one_type_printer(obj
, 'mersenne_twister_engine', 'mt19937_64')
1599 add_one_type_printer(obj
, 'subtract_with_carry_engine', 'ranlux24_base')
1600 add_one_type_printer(obj
, 'subtract_with_carry_engine', 'ranlux48_base')
1601 add_one_type_printer(obj
, 'discard_block_engine', 'ranlux24')
1602 add_one_type_printer(obj
, 'discard_block_engine', 'ranlux48')
1603 add_one_type_printer(obj
, 'shuffle_order_engine', 'knuth_b')
1605 # Add type printers for experimental::basic_string_view typedefs.
1606 ns
= 'experimental::fundamentals_v1::'
1607 for ch
in ('', 'w', 'u16', 'u32'):
1608 add_one_type_printer(obj
, ns
+ 'basic_string_view',
1609 ns
+ ch
+ 'string_view')
1611 # Do not show defaulted template arguments in class templates.
1612 add_one_template_type_printer(obj
, 'unique_ptr',
1613 { 1: 'std::default_delete<{0}>' })
1614 add_one_template_type_printer(obj
, 'deque', { 1: 'std::allocator<{0}>'})
1615 add_one_template_type_printer(obj
, 'forward_list', { 1: 'std::allocator<{0}>'})
1616 add_one_template_type_printer(obj
, 'list', { 1: 'std::allocator<{0}>'})
1617 add_one_template_type_printer(obj
, '__cxx11::list', { 1: 'std::allocator<{0}>'})
1618 add_one_template_type_printer(obj
, 'vector', { 1: 'std::allocator<{0}>'})
1619 add_one_template_type_printer(obj
, 'map',
1620 { 2: 'std::less<{0}>',
1621 3: 'std::allocator<std::pair<{0} const, {1}>>' })
1622 add_one_template_type_printer(obj
, 'multimap',
1623 { 2: 'std::less<{0}>',
1624 3: 'std::allocator<std::pair<{0} const, {1}>>' })
1625 add_one_template_type_printer(obj
, 'set',
1626 { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
1627 add_one_template_type_printer(obj
, 'multiset',
1628 { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
1629 add_one_template_type_printer(obj
, 'unordered_map',
1630 { 2: 'std::hash<{0}>',
1631 3: 'std::equal_to<{0}>',
1632 4: 'std::allocator<std::pair<{0} const, {1}>>'})
1633 add_one_template_type_printer(obj
, 'unordered_multimap',
1634 { 2: 'std::hash<{0}>',
1635 3: 'std::equal_to<{0}>',
1636 4: 'std::allocator<std::pair<{0} const, {1}>>'})
1637 add_one_template_type_printer(obj
, 'unordered_set',
1638 { 1: 'std::hash<{0}>',
1639 2: 'std::equal_to<{0}>',
1640 3: 'std::allocator<{0}>'})
1641 add_one_template_type_printer(obj
, 'unordered_multiset',
1642 { 1: 'std::hash<{0}>',
1643 2: 'std::equal_to<{0}>',
1644 3: 'std::allocator<{0}>'})
1646 def register_libstdcxx_printers (obj
):
1647 "Register libstdc++ pretty-printers with objfile Obj."
1650 global libstdcxx_printer
1653 gdb
.printing
.register_pretty_printer(obj
, libstdcxx_printer
)
1657 obj
.pretty_printers
.append(libstdcxx_printer
)
1659 register_type_printers(obj
)
1661 def build_libstdcxx_dictionary ():
1662 global libstdcxx_printer
1664 libstdcxx_printer
= Printer("libstdc++-v6")
1666 # libstdc++ objects requiring pretty-printing.
1668 # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
1669 libstdcxx_printer
.add_version('std::', 'basic_string', StdStringPrinter
)
1670 libstdcxx_printer
.add_version('std::__cxx11::', 'basic_string', StdStringPrinter
)
1671 libstdcxx_printer
.add_container('std::', 'bitset', StdBitsetPrinter
)
1672 libstdcxx_printer
.add_container('std::', 'deque', StdDequePrinter
)
1673 libstdcxx_printer
.add_container('std::', 'list', StdListPrinter
)
1674 libstdcxx_printer
.add_container('std::__cxx11::', 'list', StdListPrinter
)
1675 libstdcxx_printer
.add_container('std::', 'map', StdMapPrinter
)
1676 libstdcxx_printer
.add_container('std::', 'multimap', StdMapPrinter
)
1677 libstdcxx_printer
.add_container('std::', 'multiset', StdSetPrinter
)
1678 libstdcxx_printer
.add_version('std::', 'pair', StdPairPrinter
)
1679 libstdcxx_printer
.add_version('std::', 'priority_queue',
1680 StdStackOrQueuePrinter
)
1681 libstdcxx_printer
.add_version('std::', 'queue', StdStackOrQueuePrinter
)
1682 libstdcxx_printer
.add_version('std::', 'tuple', StdTuplePrinter
)
1683 libstdcxx_printer
.add_container('std::', 'set', StdSetPrinter
)
1684 libstdcxx_printer
.add_version('std::', 'stack', StdStackOrQueuePrinter
)
1685 libstdcxx_printer
.add_version('std::', 'unique_ptr', UniquePointerPrinter
)
1686 libstdcxx_printer
.add_container('std::', 'vector', StdVectorPrinter
)
1689 # Printer registrations for classes compiled with -D_GLIBCXX_DEBUG.
1690 libstdcxx_printer
.add('std::__debug::bitset', StdBitsetPrinter
)
1691 libstdcxx_printer
.add('std::__debug::deque', StdDequePrinter
)
1692 libstdcxx_printer
.add('std::__debug::list', StdListPrinter
)
1693 libstdcxx_printer
.add('std::__debug::map', StdMapPrinter
)
1694 libstdcxx_printer
.add('std::__debug::multimap', StdMapPrinter
)
1695 libstdcxx_printer
.add('std::__debug::multiset', StdSetPrinter
)
1696 libstdcxx_printer
.add('std::__debug::priority_queue',
1697 StdStackOrQueuePrinter
)
1698 libstdcxx_printer
.add('std::__debug::queue', StdStackOrQueuePrinter
)
1699 libstdcxx_printer
.add('std::__debug::set', StdSetPrinter
)
1700 libstdcxx_printer
.add('std::__debug::stack', StdStackOrQueuePrinter
)
1701 libstdcxx_printer
.add('std::__debug::unique_ptr', UniquePointerPrinter
)
1702 libstdcxx_printer
.add('std::__debug::vector', StdVectorPrinter
)
1704 # These are the TR1 and C++11 printers.
1705 # For array - the default GDB pretty-printer seems reasonable.
1706 libstdcxx_printer
.add_version('std::', 'shared_ptr', SharedPointerPrinter
)
1707 libstdcxx_printer
.add_version('std::', 'weak_ptr', SharedPointerPrinter
)
1708 libstdcxx_printer
.add_container('std::', 'unordered_map',
1709 Tr1UnorderedMapPrinter
)
1710 libstdcxx_printer
.add_container('std::', 'unordered_set',
1711 Tr1UnorderedSetPrinter
)
1712 libstdcxx_printer
.add_container('std::', 'unordered_multimap',
1713 Tr1UnorderedMapPrinter
)
1714 libstdcxx_printer
.add_container('std::', 'unordered_multiset',
1715 Tr1UnorderedSetPrinter
)
1716 libstdcxx_printer
.add_container('std::', 'forward_list',
1717 StdForwardListPrinter
)
1719 libstdcxx_printer
.add_version('std::tr1::', 'shared_ptr', SharedPointerPrinter
)
1720 libstdcxx_printer
.add_version('std::tr1::', 'weak_ptr', SharedPointerPrinter
)
1721 libstdcxx_printer
.add_version('std::tr1::', 'unordered_map',
1722 Tr1UnorderedMapPrinter
)
1723 libstdcxx_printer
.add_version('std::tr1::', 'unordered_set',
1724 Tr1UnorderedSetPrinter
)
1725 libstdcxx_printer
.add_version('std::tr1::', 'unordered_multimap',
1726 Tr1UnorderedMapPrinter
)
1727 libstdcxx_printer
.add_version('std::tr1::', 'unordered_multiset',
1728 Tr1UnorderedSetPrinter
)
1730 # These are the C++11 printer registrations for -D_GLIBCXX_DEBUG cases.
1731 # The tr1 namespace containers do not have any debug equivalents,
1732 # so do not register printers for them.
1733 libstdcxx_printer
.add('std::__debug::unordered_map',
1734 Tr1UnorderedMapPrinter
)
1735 libstdcxx_printer
.add('std::__debug::unordered_set',
1736 Tr1UnorderedSetPrinter
)
1737 libstdcxx_printer
.add('std::__debug::unordered_multimap',
1738 Tr1UnorderedMapPrinter
)
1739 libstdcxx_printer
.add('std::__debug::unordered_multiset',
1740 Tr1UnorderedSetPrinter
)
1741 libstdcxx_printer
.add('std::__debug::forward_list',
1742 StdForwardListPrinter
)
1744 # Library Fundamentals TS components
1745 libstdcxx_printer
.add_version('std::experimental::fundamentals_v1::',
1746 'any', StdExpAnyPrinter
)
1747 libstdcxx_printer
.add_version('std::experimental::fundamentals_v1::',
1748 'optional', StdExpOptionalPrinter
)
1749 libstdcxx_printer
.add_version('std::experimental::fundamentals_v1::',
1750 'basic_string_view', StdExpStringViewPrinter
)
1751 # Filesystem TS components
1752 libstdcxx_printer
.add_version('std::experimental::filesystem::v1::',
1753 'path', StdExpPathPrinter
)
1754 libstdcxx_printer
.add_version('std::experimental::filesystem::v1::__cxx11::',
1755 'path', StdExpPathPrinter
)
1756 libstdcxx_printer
.add_version('std::filesystem::',
1757 'path', StdExpPathPrinter
)
1758 libstdcxx_printer
.add_version('std::filesystem::__cxx11::',
1759 'path', StdExpPathPrinter
)
1762 libstdcxx_printer
.add_version('std::',
1763 'any', StdExpAnyPrinter
)
1764 libstdcxx_printer
.add_version('std::',
1765 'optional', StdExpOptionalPrinter
)
1766 libstdcxx_printer
.add_version('std::',
1767 'basic_string_view', StdExpStringViewPrinter
)
1768 libstdcxx_printer
.add_version('std::',
1769 'variant', StdVariantPrinter
)
1770 libstdcxx_printer
.add_version('std::',
1771 '_Node_handle', StdNodeHandlePrinter
)
1774 libstdcxx_printer
.add_version('__gnu_cxx::', 'slist', StdSlistPrinter
)
1777 # These shouldn't be necessary, if GDB "print *i" worked.
1778 # But it often doesn't, so here they are.
1779 libstdcxx_printer
.add_container('std::', '_List_iterator',
1780 StdListIteratorPrinter
)
1781 libstdcxx_printer
.add_container('std::', '_List_const_iterator',
1782 StdListIteratorPrinter
)
1783 libstdcxx_printer
.add_version('std::', '_Rb_tree_iterator',
1784 StdRbtreeIteratorPrinter
)
1785 libstdcxx_printer
.add_version('std::', '_Rb_tree_const_iterator',
1786 StdRbtreeIteratorPrinter
)
1787 libstdcxx_printer
.add_container('std::', '_Deque_iterator',
1788 StdDequeIteratorPrinter
)
1789 libstdcxx_printer
.add_container('std::', '_Deque_const_iterator',
1790 StdDequeIteratorPrinter
)
1791 libstdcxx_printer
.add_version('__gnu_cxx::', '__normal_iterator',
1792 StdVectorIteratorPrinter
)
1793 libstdcxx_printer
.add_version('__gnu_cxx::', '_Slist_iterator',
1794 StdSlistIteratorPrinter
)
1795 libstdcxx_printer
.add_container('std::', '_Fwd_list_iterator',
1796 StdFwdListIteratorPrinter
)
1797 libstdcxx_printer
.add_container('std::', '_Fwd_list_const_iterator',
1798 StdFwdListIteratorPrinter
)
1800 # Debug (compiled with -D_GLIBCXX_DEBUG) printer
1802 libstdcxx_printer
.add('__gnu_debug::_Safe_iterator',
1803 StdDebugIteratorPrinter
)
1805 build_libstdcxx_dictionary ()