1 # Pretty-printers for libstdc++.
3 # Copyright (C) 2008-2025 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/>.
25 # Python 2 + Python 3 compatibility code
27 # Resources about compatibility:
29 # * <http://pythonhosted.org/six/>: Documentation of the "six" module
31 # FIXME: The handling of e.g. std::basic_string (at least on char)
32 # probably needs updating to work with Python 3's new string rules.
34 # In particular, Python 3 has a separate type (called byte) for
35 # bytestrings, and a special b"" syntax for the byte literals; the old
36 # str() type has been redefined to always store Unicode text.
38 # We probably can't do much about this until this GDB PR is addressed:
39 # <https://sourceware.org/bugzilla/show_bug.cgi?id=17138>
41 if sys
.version_info
[0] > 2:
44 # Python 3 folds these into the normal functions.
47 # Also, int subsumes long
49 _utc_timezone
= datetime
.timezone
.utc
53 """Compatibility mixin for iterators
55 Instead of writing next() methods for iterators, write
56 __next__() methods and use this mixin to make them work in
57 Python 2 as well as Python 3.
59 Idea stolen from the "six" documentation:
60 <http://pythonhosted.org/six/#six.Iterator>
64 return self
.__next
__()
66 # In Python 2, we still need these from itertools
67 from itertools
import imap
, izip
69 # Python 2 does not provide the datetime.UTC singleton.
70 class UTC(datetime
.tzinfo
):
71 """Concrete tzinfo class representing the UTC time zone."""
73 def utcoffset(self
, dt
):
74 return datetime
.timedelta(0)
80 return datetime
.timedelta(0)
83 # Try to use the new-style pretty-printing if available.
90 # Try to install type-printers.
91 _use_type_printing
= False
94 if hasattr(gdb
.types
, 'TypePrinter'):
95 _use_type_printing
= True
99 # Use the base class if available.
100 if hasattr(gdb
, 'ValuePrinter'):
101 printer_base
= gdb
.ValuePrinter
103 printer_base
= object
105 # Starting with the type ORIG, search for the member type NAME. This
106 # handles searching upward through superclasses. This is needed to
107 # work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
110 def find_type(orig
, name
):
111 typ
= orig
.strip_typedefs()
113 # Use Type.tag to ignore cv-qualifiers. PR 67440.
114 search
= '%s::%s' % (typ
.tag
, name
)
116 return gdb
.lookup_type(search
)
119 # The type was not found, so try the superclass. We only need
120 # to check the first superclass, so we don't bother with
121 # anything fancier here.
122 fields
= typ
.fields()
123 if len(fields
) and fields
[0].is_base_class
:
126 raise ValueError("Cannot find type %s::%s" % (str(orig
), name
))
129 _versioned_namespace
= '__8::'
132 def lookup_templ_spec(templ
, *args
):
134 Lookup template specialization templ<args...>.
136 t
= '{}<{}>'.format(templ
, ', '.join([str(a
) for a
in args
]))
138 return gdb
.lookup_type(t
)
139 except gdb
.error
as e
:
140 # Type not found, try again in versioned namespace.
141 global _versioned_namespace
142 if _versioned_namespace
not in templ
:
143 t
= t
.replace('::', '::' + _versioned_namespace
, 1)
145 return gdb
.lookup_type(t
)
147 # If that also fails, rethrow the original exception
151 # Use this to find container node types instead of find_type,
152 # see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91997 for details.
153 def lookup_node_type(nodename
, containertype
):
155 Lookup specialization of template nodename corresponding to containertype.
157 nodename - The name of a class template, as a String
158 containertype - The container, as a gdb.Type
160 Return a gdb.Type for the corresponding specialization of nodename,
161 or None if the type cannot be found.
163 e.g. lookup_node_type('_List_node', gdb.lookup_type('std::list<int>'))
164 will return a gdb.Type for the type std::_List_node<int>.
166 # If nodename is unqualified, assume it's in namespace std.
167 if '::' not in nodename
:
168 nodename
= 'std::' + nodename
169 # Use either containertype's value_type or its first template argument.
171 valtype
= find_type(containertype
, 'value_type')
173 valtype
= containertype
.template_argument(0)
174 valtype
= valtype
.strip_typedefs()
176 return lookup_templ_spec(nodename
, valtype
)
178 # For debug mode containers the node is in std::__cxx1998.
179 if is_member_of_namespace(nodename
, 'std'):
180 if is_member_of_namespace(containertype
, 'std::__cxx1998',
181 'std::__debug', '__gnu_debug'):
182 nodename
= nodename
.replace('::', '::__cxx1998::', 1)
184 return lookup_templ_spec(nodename
, valtype
)
190 def is_member_of_namespace(typ
, *namespaces
):
192 Test whether a type is a member of one of the specified namespaces.
193 The type can be specified as a string or a gdb.Type object.
195 if isinstance(typ
, gdb
.Type
):
197 typ
= strip_versioned_namespace(typ
)
198 for namespace
in namespaces
:
199 if typ
.startswith(namespace
+ '::'):
204 def is_specialization_of(x
, template_name
):
206 Test whether a type is a specialization of the named class template.
207 The type can be specified as a string or a gdb.Type object.
208 The template should be the name of a class template as a string,
209 without any 'std' qualification.
211 global _versioned_namespace
212 if isinstance(x
, gdb
.Type
):
214 template_name
= '(%s)?%s' % (_versioned_namespace
, template_name
)
215 return re
.match('^std::%s<.*>$' % template_name
, x
) is not None
218 def strip_versioned_namespace(typename
):
219 global _versioned_namespace
220 return typename
.replace(_versioned_namespace
, '')
223 def strip_fundts_namespace(typ
):
224 """Remove "fundamentals_vN" inline namespace from qualified type name."""
225 pattern
= r
'^std::experimental::fundamentals_v\d::'
226 repl
= 'std::experimental::'
227 if sys
.version_info
[0] == 2:
228 return re
.sub(pattern
, repl
, typ
, 1)
229 else: # Technically this needs Python 3.1 but nobody should be using 3.0
230 return re
.sub(pattern
, repl
, typ
, count
=1)
233 def strip_inline_namespaces(type_str
):
234 """Remove known inline namespaces from the canonical name of a type."""
235 type_str
= strip_versioned_namespace(type_str
)
236 type_str
= type_str
.replace('std::__cxx11::', 'std::')
237 expt_ns
= 'std::experimental::'
238 for lfts_ns
in ('fundamentals_v1', 'fundamentals_v2'):
239 type_str
= type_str
.replace(expt_ns
+ lfts_ns
+ '::', expt_ns
)
240 fs_ns
= expt_ns
+ 'filesystem::'
241 type_str
= type_str
.replace(fs_ns
+ 'v1::', fs_ns
)
245 def get_template_arg_list(type_obj
):
246 """Return a type's template arguments as a list."""
251 template_args
.append(type_obj
.template_argument(n
))
257 class SmartPtrIterator(Iterator
):
258 """An iterator for smart pointer types with a single 'child' value."""
260 def __init__(self
, val
):
267 if self
._val
is None:
269 self
._val
, val
= None, self
._val
270 return ('get()', val
)
273 class SharedPointerPrinter(printer_base
):
275 Print a shared_ptr, weak_ptr, atomic<shared_ptr>, or atomic<weak_ptr>.
278 def __init__(self
, typename
, val
):
279 self
._typename
= strip_versioned_namespace(typename
)
281 self
._pointer
= val
['_M_ptr']
284 return SmartPtrIterator(self
._pointer
)
286 # Return the _Sp_counted_base<>* that holds the refcounts.
287 def _get_refcounts(self
):
288 if self
._typename
== 'std::atomic':
289 # A tagged pointer is stored as uintptr_t.
290 ptr_val
= self
._val
['_M_refcount']['_M_val']['_M_i']
291 ptr_val
= ptr_val
- (ptr_val
% 2) # clear lock bit
292 ptr_type
= find_type(self
._val
['_M_refcount'].type, 'pointer')
293 return ptr_val
.cast(ptr_type
)
294 return self
._val
['_M_refcount']['_M_pi']
298 refcounts
= self
._get
_refcounts
()
299 targ
= self
._val
.type.template_argument(0)
300 targ
= strip_versioned_namespace(str(targ
))
303 usecount
= refcounts
['_M_use_count']
304 weakcount
= refcounts
['_M_weak_count']
306 state
= 'expired, weak count %d' % weakcount
308 state
= 'use count %d, weak count %d' % (
309 usecount
, weakcount
- 1)
310 return '%s<%s> (%s)' % (self
._typename
, targ
, state
)
313 def _tuple_impl_get(val
):
314 """Return the tuple element stored in a _Tuple_impl<N, T> base class."""
315 bases
= val
.type.fields()
316 if not bases
[-1].is_base_class
:
318 "Unsupported implementation for std::tuple: %s" % str(val
.type))
319 # Get the _Head_base<N, T> base class:
320 head_base
= val
.cast(bases
[-1].type)
321 fields
= head_base
.type.fields()
324 "Unsupported implementation for std::tuple: %s" % str(val
.type))
325 if fields
[0].name
== '_M_head_impl':
326 # The tuple element is the _Head_base::_M_head_impl data member.
327 return head_base
['_M_head_impl']
328 elif fields
[0].is_base_class
:
329 # The tuple element is an empty base class of _Head_base.
330 # Cast to that empty base class.
331 return head_base
.cast(fields
[0].type)
334 "Unsupported implementation for std::tuple: %s" % str(val
.type))
337 def tuple_get(n
, val
):
338 """Return the result of std::get<n>(val) on a std::tuple."""
339 tuple_size
= len(get_template_arg_list(val
.type))
341 raise ValueError("Out of range index for std::get<N> on std::tuple")
342 # Get the first _Tuple_impl<0, T...> base class:
343 node
= val
.cast(val
.type.fields()[0].type)
345 # Descend through the base classes until the Nth one.
346 node
= node
.cast(node
.type.fields()[0].type)
348 return _tuple_impl_get(node
)
351 def unique_ptr_get(val
):
352 """Return the result of val.get() on a std::unique_ptr."""
353 # std::unique_ptr<T, D> contains a std::tuple<D::pointer, D>,
354 # either as a direct data member _M_t (the old implementation)
355 # or within a data member of type __uniq_ptr_data.
356 impl_type
= val
.type.fields()[0].type.strip_typedefs()
357 # Check for new implementations first:
358 if is_specialization_of(impl_type
, '__uniq_ptr_data') \
359 or is_specialization_of(impl_type
, '__uniq_ptr_impl'):
360 tuple_member
= val
['_M_t']['_M_t']
361 elif is_specialization_of(impl_type
, 'tuple'):
362 tuple_member
= val
['_M_t']
365 "Unsupported implementation for unique_ptr: %s" % str(impl_type
))
366 return tuple_get(0, tuple_member
)
369 class UniquePointerPrinter(printer_base
):
370 """Print a unique_ptr."""
372 def __init__(self
, typename
, val
):
376 return SmartPtrIterator(unique_ptr_get(self
._val
))
379 t
= self
._val
.type.template_argument(0)
380 return 'std::unique_ptr<{}>'.format(str(t
))
383 def get_value_from_aligned_membuf(buf
, valtype
):
384 """Return the value held in a __gnu_cxx::__aligned_membuf."""
385 return buf
['_M_storage'].address
.cast(valtype
.pointer()).dereference()
388 def get_value_from_list_node(node
):
389 """Return the value held in an _List_node<_Val>."""
391 member
= node
.type.fields()[1].name
392 if member
== '_M_data':
393 # C++03 implementation, node contains the value as a member
394 return node
['_M_data']
395 elif member
== '_M_storage':
396 # C++11 implementation, node stores value in __aligned_membuf
397 valtype
= node
.type.template_argument(0)
398 return get_value_from_aligned_membuf(node
['_M_storage'], valtype
)
401 raise ValueError("Unsupported implementation for %s" % str(node
.type))
404 class StdListPrinter(printer_base
):
405 """Print a std::list."""
407 class _iterator(Iterator
):
408 def __init__(self
, nodetype
, head
):
409 self
._nodetype
= nodetype
410 self
._base
= head
['_M_next']
411 self
._head
= head
.address
418 if self
._base
== self
._head
:
420 elt
= self
._base
.cast(self
._nodetype
).dereference()
421 self
._base
= elt
['_M_next']
423 self
._count
= self
._count
+ 1
424 val
= get_value_from_list_node(elt
)
425 return ('[%d]' % count
, val
)
427 def __init__(self
, typename
, val
):
428 self
._typename
= strip_versioned_namespace(typename
)
432 nodetype
= lookup_node_type('_List_node', self
._val
.type).pointer()
433 return self
._iterator
(nodetype
, self
._val
['_M_impl']['_M_node'])
436 headnode
= self
._val
['_M_impl']['_M_node']
437 if headnode
['_M_next'] == headnode
.address
:
438 return 'empty %s' % (self
._typename
)
439 return '%s' % (self
._typename
)
442 class NodeIteratorPrinter(printer_base
):
443 def __init__(self
, typename
, val
, contname
, nodename
):
445 self
._typename
= typename
446 self
._contname
= contname
447 self
._nodetype
= lookup_node_type(nodename
, val
.type)
450 if not self
._val
['_M_node']:
451 return 'non-dereferenceable iterator for std::%s' % (self
._contname
)
452 node
= self
._val
['_M_node'].cast(
453 self
._nodetype
.pointer()).dereference()
454 return str(get_value_from_list_node(node
))
457 class StdListIteratorPrinter(NodeIteratorPrinter
):
458 """Print std::list::iterator."""
460 def __init__(self
, typename
, val
):
461 NodeIteratorPrinter
.__init
__(self
, typename
, val
, 'list', '_List_node')
464 class StdFwdListIteratorPrinter(NodeIteratorPrinter
):
465 """Print std::forward_list::iterator."""
467 def __init__(self
, typename
, val
):
468 NodeIteratorPrinter
.__init
__(self
, typename
, val
, 'forward_list',
472 class StdSlistPrinter(printer_base
):
473 """Print a __gnu_cxx::slist."""
475 class _iterator(Iterator
):
476 def __init__(self
, nodetype
, head
):
477 self
._nodetype
= nodetype
478 self
._base
= head
['_M_head']['_M_next']
487 elt
= self
._base
.cast(self
._nodetype
).dereference()
488 self
._base
= elt
['_M_next']
490 self
._count
= self
._count
+ 1
491 return ('[%d]' % count
, elt
['_M_data'])
493 def __init__(self
, typename
, val
):
497 nodetype
= lookup_node_type('__gnu_cxx::_Slist_node', self
._val
.type)
498 return self
._iterator
(nodetype
.pointer(), self
._val
)
501 if self
._val
['_M_head']['_M_next'] == 0:
502 return 'empty __gnu_cxx::slist'
503 return '__gnu_cxx::slist'
506 class StdSlistIteratorPrinter(printer_base
):
507 """Print __gnu_cxx::slist::iterator."""
509 def __init__(self
, typename
, val
):
513 if not self
._val
['_M_node']:
514 return 'non-dereferenceable iterator for __gnu_cxx::slist'
515 nodetype
= lookup_node_type(
516 '__gnu_cxx::_Slist_node', self
._val
.type).pointer()
517 return str(self
._val
['_M_node'].cast(nodetype
).dereference()['_M_data'])
520 class StdVectorPrinter(printer_base
):
521 """Print a std::vector."""
523 class _iterator(Iterator
):
524 def __init__(self
, start
, finish
, bitvec
):
525 self
._bitvec
= bitvec
527 self
._item
= start
['_M_p']
529 self
._finish
= finish
['_M_p']
530 self
._fo
= finish
['_M_offset']
531 itype
= self
._item
.dereference().type
532 self
._isize
= 8 * itype
.sizeof
535 self
._finish
= finish
543 self
._count
= self
._count
+ 1
545 if self
._item
== self
._finish
and self
._so
>= self
._fo
:
547 elt
= bool(self
._item
.dereference() & (1 << self
._so
))
548 self
._so
= self
._so
+ 1
549 if self
._so
>= self
._isize
:
550 self
._item
= self
._item
+ 1
552 return ('[%d]' % count
, elt
)
554 if self
._item
== self
._finish
:
556 elt
= self
._item
.dereference()
557 self
._item
= self
._item
+ 1
558 return ('[%d]' % count
, elt
)
560 def __init__(self
, typename
, val
):
561 self
._typename
= strip_versioned_namespace(typename
)
563 self
._is
_bool
= val
.type.template_argument(
564 0).code
== gdb
.TYPE_CODE_BOOL
567 return self
._iterator
(self
._val
['_M_impl']['_M_start'],
568 self
._val
['_M_impl']['_M_finish'],
572 start
= self
._val
['_M_impl']['_M_start']
573 finish
= self
._val
['_M_impl']['_M_finish']
574 end
= self
._val
['_M_impl']['_M_end_of_storage']
576 start
= self
._val
['_M_impl']['_M_start']['_M_p']
577 finish
= self
._val
['_M_impl']['_M_finish']['_M_p']
578 fo
= self
._val
['_M_impl']['_M_finish']['_M_offset']
579 itype
= start
.dereference().type
580 bl
= 8 * itype
.sizeof
581 length
= bl
* (finish
- start
) + fo
582 capacity
= bl
* (end
- start
)
583 return ('%s<bool> of length %d, capacity %d'
584 % (self
._typename
, int(length
), int(capacity
)))
586 return ('%s of length %d, capacity %d'
587 % (self
._typename
, int(finish
- start
), int(end
- start
)))
589 def display_hint(self
):
593 class StdVectorIteratorPrinter(printer_base
):
594 """Print std::vector::iterator."""
596 def __init__(self
, typename
, val
):
600 if not self
._val
['_M_current']:
601 return 'non-dereferenceable iterator for std::vector'
602 return str(self
._val
['_M_current'].dereference())
605 class StdBitIteratorPrinter(printer_base
):
606 """Print std::vector<bool>'s _Bit_iterator and _Bit_const_iterator."""
608 def __init__(self
, typename
, val
):
612 if not self
._val
['_M_p']:
613 return 'non-dereferenceable iterator for std::vector<bool>'
614 return bool(self
._val
['_M_p'].dereference()
615 & (1 << self
._val
['_M_offset']))
618 class StdBitReferencePrinter(printer_base
):
619 """Print std::vector<bool>::reference."""
621 def __init__(self
, typename
, val
):
625 if not self
._val
['_M_p']:
626 # PR libstdc++/115098 removed the reference default constructor
627 # that this case relates to. New code should never need this,
628 # but we still handle it for compatibility with old binaries.
629 return 'invalid std::vector<bool>::reference'
630 return bool(self
._val
['_M_p'].dereference() & (self
._val
['_M_mask']))
633 class StdTuplePrinter(printer_base
):
634 """Print a std::tuple."""
636 class _iterator(Iterator
):
638 def _is_nonempty_tuple(nodes
):
640 if is_specialization_of(nodes
[1].type, '__tuple_base'):
642 elif len(nodes
) == 1:
644 elif len(nodes
) == 0:
647 "Top of tuple tree does not consist of a single node.")
649 def __init__(self
, head
):
652 # Set the base class as the initial head of the
654 nodes
= self
._head
.type.fields()
655 if self
._is
_nonempty
_tuple
(nodes
):
656 # Set the actual head to the first pair.
657 self
._head
= self
._head
.cast(nodes
[0].type)
664 # Check for further recursions in the inheritance tree.
665 # For a GCC 5+ tuple self._head is None after visiting all nodes:
668 nodes
= self
._head
.type.fields()
669 # For a GCC 4.x tuple there is a final node with no fields:
672 # Check that this iteration has an expected structure.
675 "Cannot parse more than 2 nodes in a tuple tree.")
678 # This is the last node of a GCC 5+ std::tuple.
679 impl
= self
._head
.cast(nodes
[0].type)
682 # Either a node before the last node, or the last node of
683 # a GCC 4.x tuple (which has an empty parent).
685 # - Left node is the next recursion parent.
686 # - Right node is the actual class contained in the tuple.
688 # Process right node.
689 impl
= self
._head
.cast(nodes
[1].type)
691 # Process left node and set it as head.
692 self
._head
= self
._head
.cast(nodes
[0].type)
694 self
._count
= self
._count
+ 1
696 # Finally, check the implementation. If it is
697 # wrapped in _M_head_impl return that, otherwise return
699 fields
= impl
.type.fields()
700 if len(fields
) < 1 or fields
[0].name
!= "_M_head_impl":
701 return ('[%d]' % (self
._count
- 1), impl
)
703 return ('[%d]' % (self
._count
- 1), impl
['_M_head_impl'])
705 def __init__(self
, typename
, val
):
706 self
._typename
= strip_versioned_namespace(typename
)
710 return self
._iterator
(self
._val
)
713 if len(self
._val
.type.fields()) == 0:
714 return 'empty %s' % (self
._typename
)
715 return '%s containing' % (self
._typename
)
718 class StdStackOrQueuePrinter(printer_base
):
719 """Print a std::stack or std::queue."""
721 def __init__(self
, typename
, val
):
722 self
._typename
= strip_versioned_namespace(typename
)
723 self
._visualizer
= gdb
.default_visualizer(val
['c'])
726 return self
._visualizer
.children()
729 return '%s wrapping: %s' % (self
._typename
,
730 self
._visualizer
.to_string())
732 def display_hint(self
):
733 if hasattr(self
._visualizer
, 'display_hint'):
734 return self
._visualizer
.display_hint()
738 class RbtreeIterator(Iterator
):
740 Turn an RB-tree-based container (std::map, std::set etc.) into
741 a Python iterable object.
744 def __init__(self
, rbtree
):
745 self
._size
= rbtree
['_M_t']['_M_impl']['_M_node_count']
746 self
._node
= rbtree
['_M_t']['_M_impl']['_M_header']['_M_left']
753 return int(self
._size
)
756 if self
._count
== self
._size
:
759 self
._count
= self
._count
+ 1
760 if self
._count
< self
._size
:
761 # Compute the next node.
763 if node
.dereference()['_M_right']:
764 node
= node
.dereference()['_M_right']
765 while node
.dereference()['_M_left']:
766 node
= node
.dereference()['_M_left']
768 parent
= node
.dereference()['_M_parent']
769 while node
== parent
.dereference()['_M_right']:
771 parent
= parent
.dereference()['_M_parent']
772 if node
.dereference()['_M_right'] != parent
:
778 def get_value_from_Rb_tree_node(node
):
779 """Return the value held in an _Rb_tree_node<_Val>."""
781 member
= node
.type.fields()[1].name
782 if member
== '_M_value_field':
783 # C++03 implementation, node contains the value as a member
784 return node
['_M_value_field']
785 elif member
== '_M_storage':
786 # C++11 implementation, node stores value in __aligned_membuf
787 valtype
= node
.type.template_argument(0)
788 return get_value_from_aligned_membuf(node
['_M_storage'], valtype
)
791 raise ValueError("Unsupported implementation for %s" % str(node
.type))
793 # This is a pretty printer for std::_Rb_tree_iterator (which is
794 # std::map::iterator), and has nothing to do with the RbtreeIterator
798 class StdRbtreeIteratorPrinter(printer_base
):
799 """Print std::map::iterator, std::set::iterator, etc."""
801 def __init__(self
, typename
, val
):
803 nodetype
= lookup_node_type('_Rb_tree_node', self
._val
.type)
804 self
._link
_type
= nodetype
.pointer()
807 if not self
._val
['_M_node']:
808 return 'non-dereferenceable iterator for associative container'
809 node
= self
._val
['_M_node'].cast(self
._link
_type
).dereference()
810 return str(get_value_from_Rb_tree_node(node
))
813 class StdDebugIteratorPrinter(printer_base
):
814 """Print a debug enabled version of an iterator."""
816 def __init__(self
, typename
, val
):
819 # Just strip away the encapsulating __gnu_debug::_Safe_iterator
820 # and return the wrapped iterator value.
822 base_type
= gdb
.lookup_type('__gnu_debug::_Safe_iterator_base')
823 itype
= self
._val
.type.template_argument(0)
824 safe_seq
= self
._val
.cast(base_type
)['_M_sequence']
826 return str(self
._val
.cast(itype
))
827 if self
._val
['_M_version'] != safe_seq
['_M_version']:
828 return "invalid iterator"
829 return str(self
._val
.cast(itype
))
832 def num_elements(num
):
833 """Return either "1 element" or "N elements" depending on the argument."""
834 return '1 element' if num
== 1 else '%d elements' % num
837 class StdMapPrinter(printer_base
):
838 """Print a std::map or std::multimap."""
840 # Turn an RbtreeIterator into a pretty-print iterator.
841 class _iter(Iterator
):
842 def __init__(self
, rbiter
, type):
843 self
._rbiter
= rbiter
851 if self
._count
% 2 == 0:
852 n
= next(self
._rbiter
)
853 n
= n
.cast(self
._type
).dereference()
854 n
= get_value_from_Rb_tree_node(n
)
858 item
= self
._pair
['second']
859 result
= ('[%d]' % self
._count
, item
)
860 self
._count
= self
._count
+ 1
863 def __init__(self
, typename
, val
):
864 self
._typename
= strip_versioned_namespace(typename
)
868 return '%s with %s' % (self
._typename
,
869 num_elements(len(RbtreeIterator(self
._val
))))
872 node
= lookup_node_type('_Rb_tree_node', self
._val
.type).pointer()
873 return self
._iter
(RbtreeIterator(self
._val
), node
)
875 def display_hint(self
):
879 class StdSetPrinter(printer_base
):
880 """Print a std::set or std::multiset."""
882 # Turn an RbtreeIterator into a pretty-print iterator.
883 class _iter(Iterator
):
884 def __init__(self
, rbiter
, type):
885 self
._rbiter
= rbiter
893 item
= next(self
._rbiter
)
894 item
= item
.cast(self
._type
).dereference()
895 item
= get_value_from_Rb_tree_node(item
)
896 # FIXME: this is weird ... what to do?
897 # Maybe a 'set' display hint?
898 result
= ('[%d]' % self
._count
, item
)
899 self
._count
= self
._count
+ 1
902 def __init__(self
, typename
, val
):
903 self
._typename
= strip_versioned_namespace(typename
)
907 return '%s with %s' % (self
._typename
,
908 num_elements(len(RbtreeIterator(self
._val
))))
911 node
= lookup_node_type('_Rb_tree_node', self
._val
.type).pointer()
912 return self
._iter
(RbtreeIterator(self
._val
), node
)
915 class StdBitsetPrinter(printer_base
):
916 """Print a std::bitset."""
918 def __init__(self
, typename
, val
):
919 self
._typename
= strip_versioned_namespace(typename
)
923 # If template_argument handled values, we could print the
924 # size. Or we could use a regexp on the type.
925 return '%s' % (self
._typename
)
929 # An empty bitset may not have any members which will
930 # result in an exception being thrown.
931 words
= self
._val
['_M_w']
937 # The _M_w member can be either an unsigned long, or an
938 # array. This depends on the template specialization used.
939 # If it is a single long, convert to a single element list.
940 if wtype
.code
== gdb
.TYPE_CODE_ARRAY
:
941 tsize
= wtype
.target().sizeof
946 nwords
= wtype
.sizeof
/ tsize
954 # Another spot where we could use 'set'?
955 result
.append(('[%d]' % (byte
* tsize
* 8 + bit
), 1))
962 class StdDequePrinter(printer_base
):
963 """Print a std::deque."""
965 class _iter(Iterator
):
966 def __init__(self
, node
, start
, end
, last
, buffer_size
):
971 self
._buffer
_size
= buffer_size
978 if self
._p
== self
._last
:
981 result
= ('[%d]' % self
._count
, self
._p
.dereference())
982 self
._count
= self
._count
+ 1
984 # Advance the 'cur' pointer.
985 self
._p
= self
._p
+ 1
986 if self
._p
== self
._end
:
987 # If we got to the end of this bucket, move to the
989 self
._node
= self
._node
+ 1
990 self
._p
= self
._node
[0]
991 self
._end
= self
._p
+ self
._buffer
_size
995 def __init__(self
, typename
, val
):
996 self
._typename
= strip_versioned_namespace(typename
)
998 self
._elttype
= val
.type.template_argument(0)
999 size
= self
._elttype
.sizeof
1001 self
._buffer
_size
= int(512 / size
)
1003 self
._buffer
_size
= 1
1005 def to_string(self
):
1006 start
= self
._val
['_M_impl']['_M_start']
1007 end
= self
._val
['_M_impl']['_M_finish']
1009 delta_n
= end
['_M_node'] - start
['_M_node'] - 1
1010 delta_s
= start
['_M_last'] - start
['_M_cur']
1011 delta_e
= end
['_M_cur'] - end
['_M_first']
1013 size
= self
._buffer
_size
* delta_n
+ delta_s
+ delta_e
1015 return '%s with %s' % (self
._typename
, num_elements(long(size
)))
1018 start
= self
._val
['_M_impl']['_M_start']
1019 end
= self
._val
['_M_impl']['_M_finish']
1020 return self
._iter
(start
['_M_node'], start
['_M_cur'], start
['_M_last'],
1021 end
['_M_cur'], self
._buffer
_size
)
1023 def display_hint(self
):
1027 class StdDequeIteratorPrinter(printer_base
):
1028 """Print std::deque::iterator."""
1030 def __init__(self
, typename
, val
):
1033 def to_string(self
):
1034 if not self
._val
['_M_cur']:
1035 return 'non-dereferenceable iterator for std::deque'
1036 return str(self
._val
['_M_cur'].dereference())
1039 class StdStringPrinter(printer_base
):
1040 """Print a std::basic_string of some kind."""
1042 def __init__(self
, typename
, val
):
1044 self
._new
_string
= typename
.find("::__cxx11::basic_string") != -1
1046 def to_string(self
):
1047 # Make sure &string works, too.
1048 type = self
._val
.type
1049 if type.code
== gdb
.TYPE_CODE_REF
:
1050 type = type.target()
1052 # Calculate the length of the string so that to_string returns
1053 # the string according to length, not according to first null
1055 ptr
= self
._val
['_M_dataplus']['_M_p']
1056 if self
._new
_string
:
1057 length
= self
._val
['_M_string_length']
1058 # https://sourceware.org/bugzilla/show_bug.cgi?id=17728
1059 ptr
= ptr
.cast(ptr
.type.strip_typedefs())
1061 realtype
= type.unqualified().strip_typedefs()
1062 reptype
= gdb
.lookup_type(str(realtype
) + '::_Rep').pointer()
1063 header
= ptr
.cast(reptype
) - 1
1064 length
= header
.dereference()['_M_length']
1065 if hasattr(ptr
, "lazy_string"):
1066 return ptr
.lazy_string(length
=length
)
1067 return ptr
.string(length
=length
)
1069 def display_hint(self
):
1073 def access_streambuf_ptrs(streambuf
):
1074 """Access the streambuf put area pointers."""
1075 pbase
= streambuf
['_M_out_beg']
1076 pptr
= streambuf
['_M_out_cur']
1077 egptr
= streambuf
['_M_in_end']
1078 return pbase
, pptr
, egptr
1081 class StdStringBufPrinter(printer_base
):
1082 """Print a std::basic_stringbuf."""
1084 def __init__(self
, _
, val
):
1087 def to_string(self
):
1088 (pbase
, pptr
, egptr
) = access_streambuf_ptrs(self
._val
)
1089 # Logic from basic_stringbuf::_M_high_mark()
1091 if not egptr
or pptr
> egptr
:
1092 return pbase
.string(length
=pptr
- pbase
)
1094 return pbase
.string(length
=egptr
- pbase
)
1095 return self
._val
['_M_string']
1097 def display_hint(self
):
1101 class StdStringStreamPrinter(printer_base
):
1102 """Print a std::basic_stringstream."""
1104 def __init__(self
, typename
, val
):
1106 self
._typename
= typename
1108 # Check if the stream was redirected. This is essentially:
1109 # val['_M_streambuf'] != val['_M_stringbuf'].address
1110 # However, GDB can't resolve the virtual inheritance, so we do that
1112 basetype
= [f
.type for f
in val
.type.fields() if f
.is_base_class
][0]
1113 gdb
.set_convenience_variable('__stream', val
.cast(basetype
).address
)
1114 self
._streambuf
= gdb
.parse_and_eval('$__stream->rdbuf()')
1115 self
._was
_redirected
= self
._streambuf
!= val
['_M_stringbuf'].address
1117 def to_string(self
):
1118 if self
._was
_redirected
:
1119 return "%s redirected to %s" % (
1120 self
._typename
, self
._streambuf
.dereference())
1121 return self
._val
['_M_stringbuf']
1123 def display_hint(self
):
1124 if self
._was
_redirected
:
1129 class Tr1HashtableIterator(Iterator
):
1130 def __init__(self
, hashtable
):
1131 self
._buckets
= hashtable
['_M_buckets']
1133 self
._bucket
_count
= hashtable
['_M_bucket_count']
1134 self
._node
_type
= find_type(hashtable
.type, '_Node').pointer()
1136 while self
._bucket
!= self
._bucket
_count
:
1137 self
._node
= self
._buckets
[self
._bucket
]
1140 self
._bucket
= self
._bucket
+ 1
1148 node
= self
._node
.cast(self
._node
_type
)
1149 result
= node
.dereference()['_M_v']
1150 self
._node
= node
.dereference()['_M_next']
1152 self
._bucket
= self
._bucket
+ 1
1153 while self
._bucket
!= self
._bucket
_count
:
1154 self
._node
= self
._buckets
[self
._bucket
]
1157 self
._bucket
= self
._bucket
+ 1
1161 class StdHashtableIterator(Iterator
):
1162 def __init__(self
, hashtable
):
1163 self
._node
= hashtable
['_M_before_begin']['_M_nxt']
1164 valtype
= hashtable
.type.template_argument(1)
1165 cached
= hashtable
.type.template_argument(9).template_argument(0)
1166 node_type
= lookup_templ_spec('std::__detail::_Hash_node', str(valtype
),
1167 'true' if cached
else 'false')
1168 self
._node
_type
= node_type
.pointer()
1176 elt
= self
._node
.cast(self
._node
_type
).dereference()
1177 self
._node
= elt
['_M_nxt']
1178 valptr
= elt
['_M_storage'].address
1179 valptr
= valptr
.cast(elt
.type.template_argument(0).pointer())
1180 return valptr
.dereference()
1183 class Tr1UnorderedSetPrinter(printer_base
):
1184 """Print a std::unordered_set or tr1::unordered_set."""
1186 def __init__(self
, typename
, val
):
1187 self
._typename
= strip_versioned_namespace(typename
)
1190 def _hashtable(self
):
1191 if self
._typename
.startswith('std::tr1'):
1193 return self
._val
['_M_h']
1195 def to_string(self
):
1196 count
= self
._hashtable
()['_M_element_count']
1197 return '%s with %s' % (self
._typename
, num_elements(count
))
1200 def _format_count(i
):
1204 counter
= imap(self
._format
_count
, itertools
.count())
1205 if self
._typename
.startswith('std::tr1'):
1206 return izip(counter
, Tr1HashtableIterator(self
._hashtable
()))
1207 return izip(counter
, StdHashtableIterator(self
._hashtable
()))
1210 class Tr1UnorderedMapPrinter(printer_base
):
1211 """Print a std::unordered_map or tr1::unordered_map."""
1213 def __init__(self
, typename
, val
):
1214 self
._typename
= strip_versioned_namespace(typename
)
1217 def _hashtable(self
):
1218 if self
._typename
.startswith('std::tr1'):
1220 return self
._val
['_M_h']
1222 def to_string(self
):
1223 count
= self
._hashtable
()['_M_element_count']
1224 return '%s with %s' % (self
._typename
, num_elements(count
))
1233 def _format_one(elt
):
1234 return (elt
['first'], elt
['second'])
1237 def _format_count(i
):
1241 counter
= imap(self
._format
_count
, itertools
.count())
1242 # Map over the hash table and flatten the result.
1243 if self
._typename
.startswith('std::tr1'):
1244 data
= self
._flatten
(
1245 imap(self
._format
_one
, Tr1HashtableIterator(self
._hashtable
())))
1246 # Zip the two iterators together.
1247 return izip(counter
, data
)
1248 data
= self
._flatten
(
1249 imap(self
._format
_one
, StdHashtableIterator(self
._hashtable
())))
1250 # Zip the two iterators together.
1251 return izip(counter
, data
)
1253 def display_hint(self
):
1257 class StdForwardListPrinter(printer_base
):
1258 """Print a std::forward_list."""
1260 class _iterator(Iterator
):
1261 def __init__(self
, nodetype
, head
):
1262 self
._nodetype
= nodetype
1263 self
._base
= head
['_M_next']
1272 elt
= self
._base
.cast(self
._nodetype
).dereference()
1273 self
._base
= elt
['_M_next']
1275 self
._count
= self
._count
+ 1
1276 valptr
= elt
['_M_storage'].address
1277 valptr
= valptr
.cast(elt
.type.template_argument(0).pointer())
1278 return ('[%d]' % count
, valptr
.dereference())
1280 def __init__(self
, typename
, val
):
1282 self
._typename
= strip_versioned_namespace(typename
)
1285 nodetype
= lookup_node_type('_Fwd_list_node', self
._val
.type).pointer()
1286 return self
._iterator
(nodetype
, self
._val
['_M_impl']['_M_head'])
1288 def to_string(self
):
1289 if self
._val
['_M_impl']['_M_head']['_M_next'] == 0:
1290 return 'empty %s' % self
._typename
1291 return '%s' % self
._typename
1294 class SingleObjContainerPrinter(printer_base
):
1295 """Base class for printers of containers of single objects."""
1297 def __init__(self
, val
, viz
, hint
=None):
1298 self
._contained
_value
= val
1299 self
._visualizer
= viz
1302 def _recognize(self
, type):
1303 """Return type as a string after applying type printers."""
1304 global _use_type_printing
1305 if not _use_type_printing
:
1307 return gdb
.types
.apply_type_recognizers(gdb
.types
.get_type_recognizers(),
1310 class _contained(Iterator
):
1311 def __init__(self
, val
):
1318 if self
._val
is None:
1322 return ('[contained value]', retval
)
1325 if self
._contained
_value
is None:
1326 return self
._contained
(None)
1327 if hasattr(self
._visualizer
, 'children'):
1328 return self
._visualizer
.children()
1329 return self
._contained
(self
._contained
_value
)
1331 def display_hint(self
):
1332 if (hasattr(self
._visualizer
, 'children')
1333 and hasattr(self
._visualizer
, 'display_hint')):
1334 # If contained value is a map we want to display in the same way.
1335 return self
._visualizer
.display_hint()
1339 def function_pointer_to_name(f
):
1340 """Find the name of the function referred to by the gdb.Value f,
1341 which should contain a function pointer from the program."""
1343 # Turn the function pointer into an actual address.
1344 # This is needed to unpack ppc64 function descriptors.
1345 f
= f
.dereference().address
1347 if sys
.version_info
[0] == 2:
1348 # Older versions of GDB need to use long for Python 2,
1349 # because int(f) on 64-bit big-endian values raises a
1350 # gdb.error saying "Cannot convert value to int."
1356 # If the function can't be found older versions of GDB raise a
1357 # RuntimeError saying "Cannot locate object file for block."
1358 return gdb
.block_for_pc(f
).function
.name
1363 class StdExpAnyPrinter(SingleObjContainerPrinter
):
1364 """Print a std::any or std::experimental::any."""
1366 def __init__(self
, typename
, val
):
1367 self
._typename
= strip_versioned_namespace(typename
)
1368 self
._typename
= strip_fundts_namespace(self
._typename
)
1370 self
._contained
_type
= None
1371 contained_value
= None
1373 mgr
= self
._val
['_M_manager']
1375 func
= function_pointer_to_name(mgr
)
1378 "Invalid function pointer in %s" % (self
._typename
))
1379 # We want to use this regular expression:
1380 # T::_Manager_xxx<.*>::_S_manage\(T::_Op, const T\*, T::_Arg\*\)
1381 # where T is std::any or std::experimental::any.
1382 # But we need to account for variances in demangled names
1383 # between GDB versions, e.g. 'enum T::_Op' instead of 'T::_Op'.
1385 r
"({0}::_Manager_\w+<.*>)::_S_manage\("
1386 r
"(enum )?{0}::_Op, (const {0}|{0} const) ?\*, "
1387 r
"(union )?{0}::_Arg ?\*\)"
1389 m
= re
.match(rx
, func
)
1392 "Unknown manager function in %s" % self
._typename
)
1394 mgrname
= m
.group(1)
1395 # FIXME need to expand 'std::string' so that gdb.lookup_type works
1396 if 'std::string' in mgrname
:
1398 for s
in StdExpAnyPrinter
._string
_types
():
1400 x
= re
.sub(r
"std::string(?!\w)", s
, m
.group(1))
1401 # The following lookup might raise gdb.error if the
1402 # manager function was never instantiated for 's' in
1403 # the program, because there will be no such type.
1404 mgrtypes
.append(gdb
.lookup_type(x
))
1407 if len(mgrtypes
) != 1:
1408 # FIXME: this is unlikely in practice, but possible for
1409 # programs that use both old and new string types with
1410 # std::any in a single program. Can we do better?
1411 # Maybe find the address of each type's _S_manage and
1412 # compare to the address stored in _M_manager?
1414 'Cannot uniquely determine std::string type '
1417 mgrtype
= mgrtypes
[0]
1419 mgrtype
= gdb
.lookup_type(mgrname
)
1420 self
._contained
_type
= mgrtype
.template_argument(0)
1422 if '::_Manager_internal' in mgrname
:
1423 valptr
= self
._val
['_M_storage']['_M_buffer'].address
1424 elif '::_Manager_external' in mgrname
:
1425 valptr
= self
._val
['_M_storage']['_M_ptr']
1428 "Unknown manager function in %s" % self
._typename
)
1429 contained_value
= valptr
.cast(
1430 self
._contained
_type
.pointer()).dereference()
1431 visualizer
= gdb
.default_visualizer(contained_value
)
1432 super(StdExpAnyPrinter
, self
).__init
__(contained_value
, visualizer
)
1434 def to_string(self
):
1435 if self
._contained
_type
is None:
1436 return '%s [no contained value]' % self
._typename
1437 desc
= "%s containing " % self
._typename
1438 if hasattr(self
._visualizer
, 'children'):
1439 return desc
+ self
._visualizer
.to_string()
1440 valtype
= self
._recognize
(self
._contained
_type
)
1441 return desc
+ strip_versioned_namespace(str(valtype
))
1444 def _string_types():
1445 # This lookup for std::string might return the __cxx11 version,
1446 # but that's not necessarily the one used by the std::any
1447 # manager function we're trying to find.
1448 strings
= {str(gdb
.lookup_type('std::string').strip_typedefs())}
1449 # So also consider all the other possible std::string types!
1450 s
= 'basic_string<char, std::char_traits<char>, std::allocator<char> >'
1451 quals
= ['std::', 'std::__cxx11::',
1452 'std::' + _versioned_namespace
]
1453 strings |
= {q
+ s
for q
in quals
} # set of unique strings
1457 class StdExpOptionalPrinter(SingleObjContainerPrinter
):
1458 """Print a std::optional or std::experimental::optional."""
1460 def __init__(self
, typename
, val
):
1461 self
._typename
= strip_versioned_namespace(typename
)
1462 self
._typename
= strip_fundts_namespace(self
._typename
)
1463 payload
= val
['_M_payload']
1464 if self
._typename
.startswith('std::experimental'):
1465 engaged
= val
['_M_engaged']
1466 contained_value
= payload
1468 engaged
= payload
['_M_engaged']
1469 contained_value
= payload
['_M_payload']
1472 contained_value
= contained_value
['_M_value']
1475 visualizer
= gdb
.default_visualizer(contained_value
)
1477 contained_value
= None
1478 super(StdExpOptionalPrinter
, self
).__init
__(
1479 contained_value
, visualizer
)
1481 def to_string(self
):
1482 if self
._contained
_value
is None:
1483 return "%s [no contained value]" % self
._typename
1484 if hasattr(self
._visualizer
, 'children'):
1485 return "%s containing %s" % (self
._typename
,
1486 self
._visualizer
.to_string())
1487 return self
._typename
1490 class StdVariantPrinter(SingleObjContainerPrinter
):
1491 """Print a std::variant."""
1493 def __init__(self
, typename
, val
):
1494 alternatives
= get_template_arg_list(val
.type)
1495 self
._typename
= strip_versioned_namespace(typename
)
1496 self
._index
= val
['_M_index']
1497 if self
._index
>= len(alternatives
):
1498 self
._contained
_type
= None
1499 contained_value
= None
1502 self
._contained
_type
= alternatives
[int(self
._index
)]
1503 addr
= val
['_M_u']['_M_first']['_M_storage'].address
1504 contained_value
= addr
.cast(
1505 self
._contained
_type
.pointer()).dereference()
1506 visualizer
= gdb
.default_visualizer(contained_value
)
1507 super(StdVariantPrinter
, self
).__init
__(
1508 contained_value
, visualizer
, 'array')
1510 def to_string(self
):
1511 if self
._contained
_value
is None:
1512 return "%s [no contained value]" % self
._typename
1513 if hasattr(self
._visualizer
, 'children'):
1514 return "%s [index %d] containing %s" % (self
._typename
, self
._index
,
1515 self
._visualizer
.to_string())
1516 return "%s [index %d]" % (self
._typename
, self
._index
)
1519 class StdNodeHandlePrinter(SingleObjContainerPrinter
):
1520 """Print a container node handle."""
1522 def __init__(self
, typename
, val
):
1523 self
._value
_type
= val
.type.template_argument(1)
1524 nodetype
= val
.type.template_argument(2).template_argument(0)
1525 self
._is
_rb
_tree
_node
= is_specialization_of(
1526 nodetype
.name
, '_Rb_tree_node')
1527 self
._is
_map
_node
= val
.type.template_argument(0) != self
._value
_type
1528 nodeptr
= val
['_M_ptr']
1530 if self
._is
_rb
_tree
_node
:
1531 contained_value
= get_value_from_Rb_tree_node(
1532 nodeptr
.dereference())
1534 contained_value
= get_value_from_aligned_membuf(nodeptr
['_M_storage'],
1536 visualizer
= gdb
.default_visualizer(contained_value
)
1538 contained_value
= None
1540 optalloc
= val
['_M_alloc']
1541 self
._alloc
= optalloc
['_M_payload'] if optalloc
['_M_engaged'] else None
1542 super(StdNodeHandlePrinter
, self
).__init
__(contained_value
, visualizer
,
1545 def to_string(self
):
1546 desc
= 'node handle for '
1547 if not self
._is
_rb
_tree
_node
:
1548 desc
+= 'unordered '
1549 if self
._is
_map
_node
:
1554 if self
._contained
_value
:
1555 desc
+= ' with element'
1556 if hasattr(self
._visualizer
, 'children'):
1557 return "%s = %s" % (desc
, self
._visualizer
.to_string())
1560 return 'empty %s' % desc
1563 class StdExpStringViewPrinter(printer_base
):
1565 Print a std::basic_string_view or std::experimental::basic_string_view
1568 def __init__(self
, typename
, val
):
1571 def to_string(self
):
1572 ptr
= self
._val
['_M_str']
1573 len = self
._val
['_M_len']
1574 if hasattr(ptr
, "lazy_string"):
1575 return ptr
.lazy_string(length
=len)
1576 return ptr
.string(length
=len)
1578 def display_hint(self
):
1582 class StdExpPathPrinter(printer_base
):
1583 """Print a std::experimental::filesystem::path."""
1585 def __init__(self
, typename
, val
):
1587 self
._typename
= typename
1588 start
= self
._val
['_M_cmpts']['_M_impl']['_M_start']
1589 finish
= self
._val
['_M_cmpts']['_M_impl']['_M_finish']
1590 self
._num
_cmpts
= int(finish
- start
)
1592 def _path_type(self
):
1593 t
= str(self
._val
['_M_type'])
1594 if t
[-9:] == '_Root_dir':
1595 return "root-directory"
1596 if t
[-10:] == '_Root_name':
1600 def to_string(self
):
1601 path
= "%s" % self
._val
['_M_pathname']
1602 if self
._num
_cmpts
== 0:
1603 t
= self
._path
_type
()
1605 path
= '%s [%s]' % (path
, t
)
1606 return "experimental::filesystem::path %s" % path
1608 class _iterator(Iterator
):
1609 def __init__(self
, cmpts
, pathtype
):
1610 self
._pathtype
= pathtype
1611 self
._item
= cmpts
['_M_impl']['_M_start']
1612 self
._finish
= cmpts
['_M_impl']['_M_finish']
1619 if self
._item
== self
._finish
:
1621 item
= self
._item
.dereference()
1623 self
._count
= self
._count
+ 1
1624 self
._item
= self
._item
+ 1
1625 path
= item
['_M_pathname']
1626 t
= StdExpPathPrinter(self
._pathtype
, item
)._path
_type
()
1629 return ('[%s]' % t
, path
)
1632 return self
._iterator
(self
._val
['_M_cmpts'], self
._typename
)
1635 class StdPathPrinter(printer_base
):
1636 """Print a std::filesystem::path."""
1638 def __init__(self
, typename
, val
):
1640 self
._typename
= typename
1641 impl
= unique_ptr_get(self
._val
['_M_cmpts']['_M_impl'])
1642 self
._type
= impl
.cast(gdb
.lookup_type('uintptr_t')) & 3
1648 def _path_type(self
):
1649 t
= str(self
._type
.cast(gdb
.lookup_type(self
._typename
+ '::_Type')))
1650 if t
[-9:] == '_Root_dir':
1651 return "root-directory"
1652 if t
[-10:] == '_Root_name':
1656 def to_string(self
):
1657 path
= "%s" % self
._val
['_M_pathname']
1659 t
= self
._path
_type
()
1661 path
= '%s [%s]' % (path
, t
)
1662 return "filesystem::path %s" % path
1664 class _iterator(Iterator
):
1665 def __init__(self
, impl
, pathtype
):
1666 self
._pathtype
= pathtype
1668 # We can't access _Impl::_M_size because _Impl is incomplete
1669 # so cast to int* to access the _M_size member at offset zero,
1670 int_type
= gdb
.lookup_type('int')
1671 cmpt_type
= gdb
.lookup_type(pathtype
+ '::_Cmpt')
1672 char_type
= gdb
.lookup_type('char')
1673 impl
= impl
.cast(int_type
.pointer())
1674 size
= impl
.dereference()
1675 #self._capacity = (impl + 1).dereference()
1676 if hasattr(gdb
.Type
, 'alignof'):
1677 sizeof_Impl
= max(2 * int_type
.sizeof
, cmpt_type
.alignof
)
1679 sizeof_Impl
= 2 * int_type
.sizeof
1680 begin
= impl
.cast(char_type
.pointer()) + sizeof_Impl
1681 self
._item
= begin
.cast(cmpt_type
.pointer())
1682 self
._finish
= self
._item
+ size
1692 if self
._item
== self
._finish
:
1694 item
= self
._item
.dereference()
1696 self
._count
= self
._count
+ 1
1697 self
._item
= self
._item
+ 1
1698 path
= item
['_M_pathname']
1699 t
= StdPathPrinter(self
._pathtype
, item
)._path
_type
()
1702 return ('[%s]' % t
, path
)
1705 return self
._iterator
(self
._impl
, self
._typename
)
1708 class StdPairPrinter(printer_base
):
1709 """Print a std::pair object, with 'first' and 'second' as children."""
1711 def __init__(self
, typename
, val
):
1714 class _iter(Iterator
):
1715 """An iterator for std::pair types. Returns 'first' then 'second'."""
1717 def __init__(self
, val
):
1719 self
._which
= 'first'
1725 if self
._which
is None:
1728 if which
== 'first':
1729 self
._which
= 'second'
1732 return (which
, self
._val
[which
])
1735 return self
._iter
(self
._val
)
1737 def to_string(self
):
1741 class StdCmpCatPrinter(printer_base
):
1742 """Print a comparison category object."""
1744 def __init__(self
, typename
, val
):
1745 self
._typename
= typename
[typename
.rfind(':') + 1:]
1746 self
._val
= val
['_M_value']
1748 def to_string(self
):
1749 if self
._typename
== 'strong_ordering' and self
._val
== 0:
1752 names
= {2: 'unordered', -1: 'less', 0: 'equivalent', 1: 'greater'}
1753 name
= names
[int(self
._val
)]
1754 return 'std::{}::{}'.format(self
._typename
, name
)
1757 class StdErrorCodePrinter(printer_base
):
1758 """Print a std::error_code or std::error_condition."""
1760 _system_is_posix
= None # Whether std::system_category() use errno values.
1762 def __init__(self
, typename
, val
):
1764 self
._typename
= strip_versioned_namespace(typename
)
1765 # Do this only once ...
1766 if StdErrorCodePrinter
._system
_is
_posix
is None:
1769 StdErrorCodePrinter
._system
_is
_posix
= True
1771 StdErrorCodePrinter
._system
_is
_posix
= False
1774 def _find_errc_enum(name
):
1775 typ
= gdb
.lookup_type(name
)
1776 if typ
is not None and typ
.code
== gdb
.TYPE_CODE_ENUM
:
1781 def _find_standard_errc_enum(cls
, name
):
1782 for ns
in ['', _versioned_namespace
]:
1784 qname
= 'std::{}{}'.format(ns
, name
)
1785 return cls
._find
_errc
_enum
(qname
)
1786 except RuntimeError:
1790 def _match_net_ts_category(cls
, cat
):
1791 net_cats
= ['stream', 'socket', 'ip::resolver']
1793 func
= c
+ '_category()'
1794 for ns
in ['', _versioned_namespace
]:
1795 ns
= 'std::{}experimental::net::v1'.format(ns
)
1796 sym
= gdb
.lookup_symbol('{}::{}::__c'.format(ns
, func
))[0]
1798 if cat
== sym
.value().address
:
1799 name
= 'net::' + func
1800 enum
= cls
._find
_errc
_enum
('{}::{}_errc'.format(ns
, c
))
1805 def _category_info(cls
, cat
):
1806 """Return details of a std::error_category."""
1812 # Try these first, or we get "warning: RTTI symbol not found" when
1813 # using cat.dynamic_type on the local class types for Net TS
1815 func
, enum
= cls
._match
_net
_ts
_category
(cat
)
1816 if func
is not None:
1817 return (None, func
, enum
, is_errno
)
1819 # This might give a warning for a program-defined category defined as
1820 # a local class, but there doesn't seem to be any way to avoid that.
1821 typ
= cat
.dynamic_type
.target()
1822 # Shortcuts for the known categories defined by libstdc++.
1823 if typ
.tag
.endswith('::generic_error_category'):
1826 if typ
.tag
.endswith('::system_error_category'):
1828 is_errno
= cls
._system
_is
_posix
1829 if typ
.tag
.endswith('::future_error_category'):
1831 enum
= cls
._find
_standard
_errc
_enum
('future_errc')
1832 if typ
.tag
.endswith('::io_error_category'):
1834 enum
= cls
._find
_standard
_errc
_enum
('io_errc')
1838 # Want to call std::error_category::name() override, but it's
1839 # unsafe: https://sourceware.org/bugzilla/show_bug.cgi?id=28856
1840 # gdb.set_convenience_variable('__cat', cat)
1841 # return '"%s"' % gdb.parse_and_eval('$__cat->name()').string()
1845 return (name
, typ
.tag
, enum
, is_errno
)
1848 def _unqualified_name(name
):
1850 Strip any nested-name-specifier from name to give an unqualified name.
1852 return name
.split('::')[-1]
1854 def to_string(self
):
1855 value
= self
._val
['_M_value']
1856 cat
= self
._val
['_M_cat']
1857 name
, alt_name
, enum
, is_errno
= self
._category
_info
(cat
)
1859 default_cats
= {'error_code': 'system',
1860 'error_condition': 'generic'}
1861 if name
== default_cats
[self
._unqualified
_name
(self
._typename
)]:
1862 return self
._typename
+ ' = { }' # default-constructed value
1865 if is_errno
and value
!= 0:
1867 strval
= errno
.errorcode
[int(value
)]
1870 elif enum
is not None:
1871 strval
= self
._unqualified
_name
(str(value
.cast(enum
)))
1873 if name
is not None:
1874 name
= '"%s"' % name
1877 return '%s = {%s: %s}' % (self
._typename
, name
, strval
)
1880 class StdRegexStatePrinter(printer_base
):
1881 """Print a state node in the NFA for a std::regex."""
1883 def __init__(self
, typename
, val
):
1885 self
._typename
= typename
1887 def to_string(self
):
1888 opcode
= str(self
._val
['_M_opcode'])
1890 opcode
= opcode
[25:]
1891 next_id
= self
._val
['_M_next']
1893 variants
= {'repeat': 'alt', 'alternative': 'alt',
1894 'subexpr_begin': 'subexpr', 'subexpr_end': 'subexpr',
1895 'line_begin_assertion': None, 'line_end_assertion': None,
1896 'word_boundary': 'neg', 'subexpr_lookahead': 'neg',
1897 'backref': 'backref_index',
1898 'match': None, 'accept': None,
1899 'dummy': None, 'unknown': None
1901 v
= variants
[opcode
]
1903 s
= "opcode={}, next={}".format(opcode
, next_id
)
1904 if v
is not None and self
._val
['_M_' + v
] is not None:
1905 s
= "{}, {}={}".format(s
, v
, self
._val
['_M_' + v
])
1909 class StdSpanPrinter(printer_base
):
1910 """Print a std::span."""
1912 class _iterator(Iterator
):
1913 def __init__(self
, begin
, size
):
1922 if self
._count
== self
._size
:
1926 self
._count
= self
._count
+ 1
1927 return '[%d]' % count
, (self
._begin
+ count
).dereference()
1929 def __init__(self
, typename
, val
):
1930 self
._typename
= strip_versioned_namespace(typename
)
1932 size_max
= gdb
.parse_and_eval('static_cast<std::size_t>(-1)')
1933 if val
.type.template_argument(1) == size_max
:
1934 self
._size
= val
['_M_extent']['_M_extent_value']
1936 self
._size
= val
.type.template_argument(1)
1938 def to_string(self
):
1939 return '%s of length %d' % (self
._typename
, self
._size
)
1942 return self
._iterator
(self
._val
['_M_ptr'], self
._size
)
1944 def display_hint(self
):
1948 class StdInitializerListPrinter(printer_base
):
1949 """Print a std::initializer_list."""
1951 def __init__(self
, typename
, val
):
1952 self
._typename
= typename
1954 self
._size
= val
['_M_len']
1956 def to_string(self
):
1957 return '%s of length %d' % (self
._typename
, self
._size
)
1960 return StdSpanPrinter
._iterator
(self
._val
['_M_array'], self
._size
)
1962 def display_hint(self
):
1966 class StdAtomicPrinter(printer_base
):
1967 """Print a std:atomic."""
1969 def __init__(self
, typename
, val
):
1970 self
._typename
= strip_versioned_namespace(typename
)
1972 self
._shptr
_printer
= None
1973 self
._value
_type
= self
._val
.type.template_argument(0)
1974 if self
._value
_type
.tag
is not None:
1975 typ
= strip_versioned_namespace(self
._value
_type
.tag
)
1976 if (typ
.startswith('std::shared_ptr<')
1977 or typ
.startswith('std::weak_ptr<')):
1978 impl
= val
['_M_impl']
1979 self
._shptr
_printer
= SharedPointerPrinter(typename
, impl
)
1980 self
.children
= self
._shptr
_children
1982 def _shptr_children(self
):
1983 return SmartPtrIterator(self
._shptr
_printer
._pointer
)
1985 def to_string(self
):
1986 if self
._shptr
_printer
is not None:
1987 return self
._shptr
_printer
.to_string()
1989 if self
._value
_type
.code
== gdb
.TYPE_CODE_INT
:
1990 val
= self
._val
['_M_i']
1991 elif self
._value
_type
.code
== gdb
.TYPE_CODE_FLT
:
1992 val
= self
._val
['_M_fp']
1993 elif self
._value
_type
.code
== gdb
.TYPE_CODE_PTR
:
1994 val
= self
._val
['_M_b']['_M_p']
1995 elif self
._value
_type
.code
== gdb
.TYPE_CODE_BOOL
:
1996 val
= self
._val
['_M_base']['_M_i']
1998 val
= self
._val
['_M_i']
1999 return '%s<%s> = { %s }' % (self
._typename
, str(self
._value
_type
), val
)
2002 class StdFormatArgsPrinter(printer_base
):
2003 """Print a std::basic_format_args."""
2004 # TODO: add printer for basic_format_arg<Context> and print out children.
2005 # TODO: add printer for __format::_ArgStore<Context, Args...>.
2007 def __init__(self
, typename
, val
):
2008 self
._typename
= strip_versioned_namespace(typename
)
2011 def to_string(self
):
2012 targs
= get_template_arg_list(self
._val
.type)
2013 char_type
= get_template_arg_list(targs
[0])[1]
2014 if char_type
== gdb
.lookup_type('char'):
2015 typ
= 'std::format_args'
2016 elif char_type
== gdb
.lookup_type('wchar_t'):
2017 typ
= 'std::wformat_args'
2019 typ
= 'std::basic_format_args'
2021 size
= self
._val
['_M_packed_size']
2023 return "%s with 1 argument" % (typ
)
2025 size
= self
._val
['_M_unpacked_size']
2026 return "%s with %d arguments" % (typ
, size
)
2029 class StdChronoDurationPrinter(printer_base
):
2030 """Print a std::chrono::duration."""
2032 def __init__(self
, typename
, val
):
2033 self
._typename
= strip_versioned_namespace(typename
)
2037 # TODO use reduced period i.e. duration::period
2038 period
= self
._val
.type.template_argument(1)
2039 num
= period
.template_argument(0)
2040 den
= period
.template_argument(1)
2044 num
, den
= self
._ratio
()
2052 if den
== 1000000000:
2061 return '[{}]s'.format(num
)
2062 return "[{}/{}]s".format(num
, den
)
2064 def to_string(self
):
2065 r
= self
._val
['__r']
2066 if r
.type.strip_typedefs().code
== gdb
.TYPE_CODE_FLT
:
2068 return "std::chrono::duration = {{ {}{} }}".format(r
, self
._suffix
())
2071 class StdChronoTimePointPrinter(printer_base
):
2072 """Print a std::chrono::time_point."""
2074 def __init__(self
, typename
, val
):
2075 self
._typename
= strip_versioned_namespace(typename
)
2079 clock
= self
._val
.type.template_argument(0)
2080 name
= strip_versioned_namespace(clock
.name
)
2081 if name
== 'std::chrono::_V2::system_clock' \
2082 or name
== 'std::chrono::system_clock':
2083 return ('std::chrono::sys_time', 0)
2084 # XXX need to remove leap seconds from utc, gps, and tai
2085 if name
== 'std::chrono::utc_clock':
2086 return ('std::chrono::utc_time', None) # XXX
2087 if name
== 'std::chrono::gps_clock':
2088 return ('std::chrono::gps_time', None) # XXX 315964809
2089 if name
== 'std::chrono::tai_clock':
2090 return ('std::chrono::tai_time', None) # XXX -378691210
2091 if name
== 'std::filesystem::__file_clock':
2092 return ('std::chrono::file_time', 6437664000)
2093 if name
== 'std::chrono::local_t':
2094 return ('std::chrono::local_time', 0)
2095 return ('{} time_point'.format(name
), None)
2097 def to_string(self
, abbrev
=False):
2098 clock
, offset
= self
._clock
()
2099 d
= self
._val
['__d']
2101 printer
= StdChronoDurationPrinter(d
.type.name
, d
)
2102 suffix
= printer
._suffix
()
2104 if offset
is not None:
2105 num
, den
= printer
._ratio
()
2106 secs
= (r
* num
/ den
) + offset
2108 dt
= datetime
.datetime
.fromtimestamp(secs
, _utc_timezone
)
2109 time
= ' [{:%Y-%m-%d %H:%M:%S}]'.format(dt
)
2112 s
= '%d%s%s' % (r
, suffix
, time
)
2115 return '%s = { %s }' % (clock
, s
)
2118 class StdChronoZonedTimePrinter(printer_base
):
2119 """Print a std::chrono::zoned_time."""
2121 def __init__(self
, typename
, val
):
2122 self
._typename
= strip_versioned_namespace(typename
)
2125 def to_string(self
):
2126 zone
= self
._val
['_M_zone'].dereference()['_M_name']
2127 time
= self
._val
['_M_tp']
2128 printer
= StdChronoTimePointPrinter(time
.type.name
, time
)
2129 time
= printer
.to_string(True)
2130 return 'std::chrono::zoned_time = {{ {} {} }}'.format(zone
, time
)
2133 months
= [None, 'January', 'February', 'March', 'April', 'May', 'June',
2134 'July', 'August', 'September', 'October', 'November', 'December']
2136 weekdays
= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
2137 'Saturday', 'Sunday']
2140 class StdChronoCalendarPrinter(printer_base
):
2141 """Print a std::chrono::day, std::chrono::month, std::chrono::year etc."""
2143 def __init__(self
, typename
, val
):
2144 self
._typename
= strip_versioned_namespace(typename
)
2147 def to_string(self
):
2149 typ
= self
._typename
2150 if 'month' in typ
and typ
!= 'std::chrono::year_month_day_last':
2152 if typ
.startswith('std::chrono::year'):
2155 if typ
== 'std::chrono::day':
2156 return '{}'.format(int(val
['_M_d']))
2157 if typ
== 'std::chrono::month':
2158 if m
< 1 or m
>= len(months
):
2159 return "%d is not a valid month" % m
2161 if typ
== 'std::chrono::year':
2162 return '{}y'.format(y
)
2163 if typ
== 'std::chrono::weekday':
2165 if wd
< 0 or wd
>= len(weekdays
):
2166 return "%d is not a valid weekday" % wd
2167 return '{}'.format(weekdays
[wd
])
2168 if typ
== 'std::chrono::weekday_indexed':
2169 return '{}[{}]'.format(val
['_M_wd'], int(val
['_M_index']))
2170 if typ
== 'std::chrono::weekday_last':
2171 return '{}[last]'.format(val
['_M_wd'])
2172 if typ
== 'std::chrono::month_day':
2173 return '{}/{}'.format(m
, val
['_M_d'])
2174 if typ
== 'std::chrono::month_day_last':
2175 return '{}/last'.format(m
)
2176 if typ
== 'std::chrono::month_weekday':
2177 return '{}/{}'.format(m
, val
['_M_wdi'])
2178 if typ
== 'std::chrono::month_weekday_last':
2179 return '{}/{}'.format(m
, val
['_M_wdl'])
2180 if typ
== 'std::chrono::year_month':
2181 return '{}/{}'.format(y
, m
)
2182 if typ
== 'std::chrono::year_month_day':
2183 return '{}/{}/{}'.format(y
, m
, val
['_M_d'])
2184 if typ
== 'std::chrono::year_month_day_last':
2185 return '{}/{}'.format(y
, val
['_M_mdl'])
2186 if typ
== 'std::chrono::year_month_weekday':
2187 return '{}/{}/{}'.format(y
, m
, val
['_M_wdi'])
2188 if typ
== 'std::chrono::year_month_weekday_last':
2189 return '{}/{}/{}'.format(y
, m
, val
['_M_wdl'])
2190 if typ
.startswith('std::chrono::hh_mm_ss'):
2192 if val
['fractional_width'] != 0:
2193 fract
= '.{:0{}d}'.format(int(val
['_M_ss']['_M_r']),
2194 int(val
['fractional_width']))
2195 h
= int(val
['_M_h']['__r'])
2196 m
= int(val
['_M_m']['__r'])
2197 s
= int(val
['_M_s']['__r'])
2198 if val
['_M_is_neg']:
2200 return '{:02}:{:02}:{:02}{}'.format(h
, m
, s
, fract
)
2203 class StdChronoTimeZonePrinter(printer_base
):
2204 """Print a chrono::time_zone or chrono::time_zone_link."""
2206 def __init__(self
, typename
, val
):
2207 self
._typename
= strip_versioned_namespace(typename
)
2210 def to_string(self
):
2211 str = '%s = %s' % (self
._typename
, self
._val
['_M_name'])
2212 if self
._typename
.endswith("_link"):
2213 str += ' -> %s' % (self
._val
['_M_target'])
2217 class StdChronoLeapSecondPrinter(printer_base
):
2218 """Print a chrono::leap_second."""
2220 def __init__(self
, typename
, val
):
2221 self
._typename
= strip_versioned_namespace(typename
)
2224 def to_string(self
):
2225 date
= self
._val
['_M_s']['__r']
2226 neg
= '+-'[date
< 0]
2227 return '%s %d (%c)' % (self
._typename
, abs(date
), neg
)
2230 class StdChronoTzdbPrinter(printer_base
):
2231 """Print a chrono::tzdb."""
2233 def __init__(self
, typename
, val
):
2234 self
._typename
= strip_versioned_namespace(typename
)
2237 def to_string(self
):
2238 return '%s %s' % (self
._typename
, self
._val
['version'])
2241 class StdChronoTimeZoneRulePrinter(printer_base
):
2242 """Print a chrono::time_zone rule."""
2244 def __init__(self
, typename
, val
):
2245 self
._typename
= strip_versioned_namespace(typename
)
2248 def to_string(self
):
2249 on
= self
._val
['on']
2251 month
= months
[on
['month']]
2252 suffixes
= {1: 'st', 2: 'nd', 3: 'rd',
2253 21: 'st', 22: 'nd', 23: 'rd', 31: 'st'}
2254 day
= on
['day_of_month']
2255 ordinal_day
= '{}{}'.format(day
, suffixes
.get(day
, 'th'))
2256 if kind
== 0: # DayOfMonth
2257 start
= '{} {}'.format(month
, ordinal_day
)
2259 weekday
= weekdays
[on
['day_of_week']]
2260 if kind
== 1: # LastWeekDay
2261 start
= 'last {} in {}'.format(weekday
, month
)
2263 if kind
== 2: # LessEq
2264 direction
= ('last', '<=')
2266 direction
= ('first', '>=')
2267 day
= on
['day_of_month']
2268 start
= '{} {} {} {} {}'.format(direction
[0], weekday
,
2269 direction
[1], month
,
2271 return 'time_zone rule {} from {} to {} starting on {}'.format(
2272 self
._val
['name'], self
._val
['from'], self
._val
['to'], start
)
2275 class StdLocalePrinter(printer_base
):
2276 """Print a std::locale."""
2278 def __init__(self
, typename
, val
):
2280 self
._typename
= typename
2282 def to_string(self
):
2283 names
= self
._val
['_M_impl']['_M_names']
2288 cats
= gdb
.parse_and_eval(self
._typename
+ '::_S_categories')
2289 ncat
= gdb
.parse_and_eval(self
._typename
+ '::_S_categories_size')
2290 n
= names
[0].string()
2291 cat
= cats
[0].string()
2292 name
= '{}={}'.format(cat
, n
)
2293 cat_names
= {cat
: n
}
2295 while i
< ncat
and names
[i
] != 0:
2296 n
= names
[i
].string()
2297 cat
= cats
[i
].string()
2298 name
= '{};{}={}'.format(name
, cat
, n
)
2301 uniq_names
= set(cat_names
.values())
2302 if len(uniq_names
) == 1:
2304 elif len(uniq_names
) == 2:
2305 n1
, n2
= (uniq_names
)
2306 name_list
= list(cat_names
.values())
2308 if name_list
.count(n1
) == 1:
2311 elif name_list
.count(n2
) == 1:
2314 if other
is not None:
2315 cat
= next(c
for c
, n
in cat_names
.items() if n
== other
)
2316 mod
= ' with "{}={}"'.format(cat
, other
)
2317 return 'std::locale = "{}"{}'.format(name
, mod
)
2319 class StdIntegralConstantPrinter(printer_base
):
2320 """Print a std::true_type or std::false_type."""
2322 def __init__(self
, typename
, val
):
2324 self
._typename
= typename
2326 def to_string(self
):
2327 value_type
= self
._val
.type.template_argument(0)
2328 value
= self
._val
.type.template_argument(1)
2329 if value_type
.code
== gdb
.TYPE_CODE_BOOL
:
2331 return "std::true_type"
2333 return "std::false_type"
2334 typename
= strip_versioned_namespace(self
._typename
)
2335 return "{}<{}, {}>".format(typename
, value_type
, value
)
2337 class StdTextEncodingPrinter(printer_base
):
2338 """Print a std::text_encoding."""
2340 def __init__(self
, typename
, val
):
2342 self
._typename
= typename
2344 def to_string(self
):
2345 rep
= self
._val
['_M_rep'].dereference()
2346 if rep
['_M_id'] == 1:
2347 return self
._val
['_M_name']
2348 if rep
['_M_id'] == 2:
2350 return rep
['_M_name']
2352 # A "regular expression" printer which conforms to the
2353 # "SubPrettyPrinter" protocol from gdb.printing.
2354 class RxPrinter(object):
2355 def __init__(self
, name
, function
):
2356 super(RxPrinter
, self
).__init
__()
2358 self
._function
= function
2361 def invoke(self
, value
):
2362 if not self
.enabled
:
2365 if value
.type.code
== gdb
.TYPE_CODE_REF
:
2366 if hasattr(gdb
.Value
, "referenced_value"):
2367 value
= value
.referenced_value()
2369 return self
._function
(self
.name
, value
)
2371 # A pretty-printer that conforms to the "PrettyPrinter" protocol from
2372 # gdb.printing. It can also be used directly as an old-style printer.
2375 class Printer(object):
2376 def __init__(self
, name
):
2377 super(Printer
, self
).__init
__()
2379 self
._subprinters
= []
2382 self
._compiled
_rx
= re
.compile('^([a-zA-Z0-9_:]+)(<.*>)?$')
2384 def add(self
, name
, function
):
2385 # A small sanity check.
2387 if not self
._compiled
_rx
.match(name
):
2389 'libstdc++ programming error: "%s" does not match' % name
)
2390 printer
= RxPrinter(name
, function
)
2391 self
._subprinters
.append(printer
)
2392 self
._lookup
[name
] = printer
2394 # Add a name using _GLIBCXX_BEGIN_NAMESPACE_VERSION.
2395 def add_version(self
, base
, name
, function
):
2396 self
.add(base
+ name
, function
)
2397 if '__cxx11' not in base
:
2398 vbase
= re
.sub('^(std|__gnu_cxx)::', r
'\g<0>%s' %
2399 _versioned_namespace
, base
)
2400 self
.add(vbase
+ name
, function
)
2402 # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
2403 def add_container(self
, base
, name
, function
):
2404 self
.add_version(base
, name
, function
)
2405 self
.add_version(base
+ '__cxx1998::', name
, function
)
2408 def get_basic_type(type):
2409 # If it points to a reference, get the reference.
2410 if type.code
== gdb
.TYPE_CODE_REF
:
2411 type = type.target()
2413 # Get the unqualified type, stripped of typedefs.
2414 type = type.unqualified().strip_typedefs()
2418 def __call__(self
, val
):
2419 typename
= self
.get_basic_type(val
.type)
2423 # All the types we match are template types, so we can use a
2425 match
= self
._compiled
_rx
.match(typename
)
2429 basename
= match
.group(1)
2431 if val
.type.code
== gdb
.TYPE_CODE_REF
:
2432 if hasattr(gdb
.Value
, "referenced_value"):
2433 val
= val
.referenced_value()
2435 if basename
in self
._lookup
:
2436 return self
._lookup
[basename
].invoke(val
)
2438 # Cannot find a pretty printer. Return None.
2442 libstdcxx_printer
= None
2445 class TemplateTypePrinter(object):
2447 A type printer for class templates with default template arguments.
2449 Recognizes specializations of class templates and prints them without
2450 any template arguments that use a default template argument.
2451 Type printers are recursively applied to the template arguments.
2453 e.g. replace 'std::vector<T, std::allocator<T> >' with 'std::vector<T>'.
2456 def __init__(self
, name
, defargs
):
2458 self
._defargs
= defargs
2461 class _recognizer(object):
2462 """The recognizer class for TemplateTypePrinter."""
2464 def __init__(self
, name
, defargs
):
2466 self
._defargs
= defargs
2467 # self._type_obj = None
2469 def recognize(self
, type_obj
):
2471 If type_obj is a specialization of self.name that uses all the
2472 default template arguments for the class template, then return
2473 a string representation of the type without default arguments.
2474 Otherwise, return None.
2477 if type_obj
.tag
is None:
2480 if not type_obj
.tag
.startswith(self
.name
):
2483 template_args
= get_template_arg_list(type_obj
)
2485 require_defaulted
= False
2486 for n
in range(len(template_args
)):
2487 # The actual template argument in the type:
2488 targ
= template_args
[n
]
2489 # The default template argument for the class template:
2490 defarg
= self
._defargs
.get(n
)
2491 if defarg
is not None:
2492 # Substitute other template arguments into the default:
2493 defarg
= defarg
.format(*template_args
)
2494 # Fail to recognize the type (by returning None)
2495 # unless the actual argument is the same as the default.
2497 if targ
!= gdb
.lookup_type(defarg
):
2500 # Type lookup failed, just use string comparison:
2501 if targ
.tag
!= defarg
:
2503 # All subsequent args must have defaults:
2504 require_defaulted
= True
2505 elif require_defaulted
:
2508 # Recursively apply recognizers to the template argument
2509 # and add it to the arguments that will be displayed:
2510 displayed_args
.append(self
._recognize
_subtype
(targ
))
2512 # This assumes no class templates in the nested-name-specifier:
2513 template_name
= type_obj
.tag
[0:type_obj
.tag
.find('<')]
2514 template_name
= strip_inline_namespaces(template_name
)
2516 return template_name
+ '<' + ', '.join(displayed_args
) + '>'
2518 def _recognize_subtype(self
, type_obj
):
2519 """Convert a gdb.Type to a string by applying recognizers,
2520 or if that fails then simply converting to a string."""
2522 if type_obj
.code
== gdb
.TYPE_CODE_PTR
:
2523 return self
._recognize
_subtype
(type_obj
.target()) + '*'
2524 if type_obj
.code
== gdb
.TYPE_CODE_ARRAY
:
2525 type_str
= self
._recognize
_subtype
(type_obj
.target())
2526 if str(type_obj
.strip_typedefs()).endswith('[]'):
2527 return type_str
+ '[]' # array of unknown bound
2528 return "%s[%d]" % (type_str
, type_obj
.range()[1] + 1)
2529 if type_obj
.code
== gdb
.TYPE_CODE_REF
:
2530 return self
._recognize
_subtype
(type_obj
.target()) + '&'
2531 if hasattr(gdb
, 'TYPE_CODE_RVALUE_REF'):
2532 if type_obj
.code
== gdb
.TYPE_CODE_RVALUE_REF
:
2533 return self
._recognize
_subtype
(type_obj
.target()) + '&&'
2535 type_str
= gdb
.types
.apply_type_recognizers(
2536 gdb
.types
.get_type_recognizers(), type_obj
)
2539 return str(type_obj
)
2541 def instantiate(self
):
2542 """Return a recognizer object for this type printer."""
2543 return self
._recognizer
(self
.name
, self
._defargs
)
2546 def add_one_template_type_printer(obj
, name
, defargs
):
2548 Add a type printer for a class template with default template arguments.
2551 name (str): The template-name of the class template.
2552 defargs (dict int:string) The default template arguments.
2554 Types in defargs can refer to the Nth template-argument using {N}
2555 (with zero-based indices).
2557 e.g. 'unordered_map' has these defargs:
2558 { 2: 'std::hash<{0}>',
2559 3: 'std::equal_to<{0}>',
2560 4: 'std::allocator<std::pair<const {0}, {1}> >' }
2562 printer
= TemplateTypePrinter('std::' + name
, defargs
)
2563 gdb
.types
.register_type_printer(obj
, printer
)
2565 # Add type printer for same type in debug namespace:
2566 printer
= TemplateTypePrinter('std::__debug::' + name
, defargs
)
2567 gdb
.types
.register_type_printer(obj
, printer
)
2569 if '__cxx11' not in name
:
2570 # Add second type printer for same type in versioned namespace:
2571 ns
= 'std::' + _versioned_namespace
2572 # PR 86112 Cannot use dict comprehension here:
2573 defargs
= dict((n
, d
.replace('std::', ns
))
2574 for (n
, d
) in defargs
.items())
2575 printer
= TemplateTypePrinter(ns
+ name
, defargs
)
2576 gdb
.types
.register_type_printer(obj
, printer
)
2578 # Add type printer for same type in debug namespace:
2579 printer
= TemplateTypePrinter('std::__debug::' + name
, defargs
)
2580 gdb
.types
.register_type_printer(obj
, printer
)
2583 class FilteringTypePrinter(object):
2585 A type printer that uses typedef names for common template specializations.
2588 template (str): The class template to recognize.
2589 name (str): The typedef-name that will be used instead.
2590 targ1 (str, optional): The first template argument. Defaults to None.
2592 Checks if a specialization of the class template 'template' is the same type
2593 as the typedef 'name', and prints it as 'name' instead.
2595 e.g. if an instantiation of std::basic_istream<C, T> is the same type as
2596 std::istream then print it as std::istream.
2598 If targ1 is provided (not None), match only template specializations with
2599 this type as the first template argument, e.g. if template='basic_string'
2600 and targ1='char' then only match 'basic_string<char,...>' and not
2601 'basic_string<wchar_t,...>'. This rejects non-matching specializations
2602 more quickly, without needing to do GDB type lookups.
2605 def __init__(self
, template
, name
, targ1
=None):
2606 self
._template
= template
2611 class _recognizer(object):
2612 """The recognizer class for FilteringTypePrinter."""
2614 def __init__(self
, template
, name
, targ1
):
2615 self
._template
= template
2618 self
._type
_obj
= None
2620 def recognize(self
, type_obj
):
2622 If type_obj starts with self._template and is the same type as
2623 self.name then return self.name, otherwise None.
2625 if type_obj
.tag
is None:
2628 if self
._type
_obj
is None:
2629 if self
._targ
1 is not None:
2630 s
= '{}<{}'.format(self
._template
, self
._targ
1)
2631 if not type_obj
.tag
.startswith(s
):
2632 # Filter didn't match.
2634 elif not type_obj
.tag
.startswith(self
._template
):
2635 # Filter didn't match.
2639 self
._type
_obj
= gdb
.lookup_type(
2640 self
.name
).strip_typedefs()
2644 if self
._type
_obj
is None:
2647 t1
= gdb
.types
.get_basic_type(self
._type
_obj
)
2648 t2
= gdb
.types
.get_basic_type(type_obj
)
2650 return strip_inline_namespaces(self
.name
)
2652 # Workaround ambiguous typedefs matching both std:: and
2653 # std::__cxx11:: symbols.
2654 if self
._template
.split('::')[-1] == 'basic_string':
2655 s1
= self
._type
_obj
.tag
.replace('__cxx11::', '')
2656 s2
= type_obj
.tag
.replace('__cxx11::', '')
2658 return strip_inline_namespaces(self
.name
)
2662 def instantiate(self
):
2663 """Return a recognizer object for this type printer."""
2664 return self
._recognizer
(self
._template
, self
.name
, self
._targ
1)
2667 def add_one_type_printer(obj
, template
, name
, targ1
=None):
2668 printer
= FilteringTypePrinter('std::' + template
, 'std::' + name
, targ1
)
2669 gdb
.types
.register_type_printer(obj
, printer
)
2670 if '__cxx11' not in template
:
2671 ns
= 'std::' + _versioned_namespace
2672 printer
= FilteringTypePrinter(ns
+ template
, ns
+ name
, targ1
)
2673 gdb
.types
.register_type_printer(obj
, printer
)
2676 def register_type_printers(obj
):
2677 global _use_type_printing
2679 if not _use_type_printing
:
2682 # Add type printers for typedefs std::string, std::wstring etc.
2683 for ch
in (('', 'char'),
2686 ('u16', 'char16_t'),
2687 ('u32', 'char32_t')):
2688 add_one_type_printer(obj
, 'basic_string', ch
[0] + 'string', ch
[1])
2689 add_one_type_printer(obj
, '__cxx11::basic_string',
2690 ch
[0] + 'string', ch
[1])
2691 # Typedefs for __cxx11::basic_string used to be in namespace __cxx11:
2692 add_one_type_printer(obj
, '__cxx11::basic_string',
2693 '__cxx11::' + ch
[0] + 'string', ch
[1])
2694 add_one_type_printer(obj
, 'basic_string_view',
2695 ch
[0] + 'string_view', ch
[1])
2697 # Add type printers for typedefs std::istream, std::wistream etc.
2698 for ch
in (('', 'char'), ('w', 'wchar_t')):
2699 for x
in ('ios', 'streambuf', 'istream', 'ostream', 'iostream',
2700 'filebuf', 'ifstream', 'ofstream', 'fstream'):
2701 add_one_type_printer(obj
, 'basic_' + x
, ch
[0] + x
, ch
[1])
2702 for x
in ('stringbuf', 'istringstream', 'ostringstream',
2704 add_one_type_printer(obj
, 'basic_' + x
, ch
[0] + x
, ch
[1])
2705 # <sstream> types are in __cxx11 namespace, but typedefs aren't:
2706 add_one_type_printer(obj
, '__cxx11::basic_' + x
, ch
[0] + x
, ch
[1])
2708 # Add type printers for typedefs regex, wregex, cmatch, wcmatch etc.
2709 for abi
in ('', '__cxx11::'):
2710 for ch
in (('', 'char'), ('w', 'wchar_t')):
2711 add_one_type_printer(obj
, abi
+ 'basic_regex',
2712 abi
+ ch
[0] + 'regex', ch
[1])
2713 for ch
in ('c', 's', 'wc', 'ws'):
2714 add_one_type_printer(
2715 obj
, abi
+ 'match_results', abi
+ ch
+ 'match')
2716 for x
in ('sub_match', 'regex_iterator', 'regex_token_iterator'):
2717 add_one_type_printer(obj
, abi
+ x
, abi
+ ch
+ x
)
2719 # Note that we can't have a printer for std::wstreampos, because
2720 # it is the same type as std::streampos.
2721 add_one_type_printer(obj
, 'fpos', 'streampos')
2723 # Add type printers for <chrono> typedefs.
2724 for dur
in ('nanoseconds', 'microseconds', 'milliseconds', 'seconds',
2725 'minutes', 'hours', 'days', 'weeks', 'years', 'months'):
2726 add_one_type_printer(obj
, 'chrono::duration', 'chrono::' + dur
)
2728 # Add type printers for <random> typedefs.
2729 add_one_type_printer(obj
, 'linear_congruential_engine', 'minstd_rand0')
2730 add_one_type_printer(obj
, 'linear_congruential_engine', 'minstd_rand')
2731 add_one_type_printer(obj
, 'mersenne_twister_engine', 'mt19937')
2732 add_one_type_printer(obj
, 'mersenne_twister_engine', 'mt19937_64')
2733 add_one_type_printer(obj
, 'subtract_with_carry_engine', 'ranlux24_base')
2734 add_one_type_printer(obj
, 'subtract_with_carry_engine', 'ranlux48_base')
2735 add_one_type_printer(obj
, 'discard_block_engine', 'ranlux24')
2736 add_one_type_printer(obj
, 'discard_block_engine', 'ranlux48')
2737 add_one_type_printer(obj
, 'shuffle_order_engine', 'knuth_b')
2739 # Add type printers for experimental::basic_string_view typedefs.
2740 ns
= 'experimental::fundamentals_v1::'
2741 for ch
in (('', 'char'),
2744 ('u16', 'char16_t'),
2745 ('u32', 'char32_t')):
2746 add_one_type_printer(obj
, ns
+ 'basic_string_view',
2747 ns
+ ch
[0] + 'string_view', ch
[1])
2749 # Do not show defaulted template arguments in class templates.
2750 add_one_template_type_printer(obj
, 'unique_ptr',
2751 {1: 'std::default_delete<{0}>'})
2752 add_one_template_type_printer(obj
, 'deque', {1: 'std::allocator<{0}>'})
2753 add_one_template_type_printer(
2754 obj
, 'forward_list', {1: 'std::allocator<{0}>'})
2755 add_one_template_type_printer(obj
, 'list', {1: 'std::allocator<{0}>'})
2756 add_one_template_type_printer(
2757 obj
, '__cxx11::list', {1: 'std::allocator<{0}>'})
2758 add_one_template_type_printer(obj
, 'vector', {1: 'std::allocator<{0}>'})
2759 add_one_template_type_printer(obj
, 'map',
2760 {2: 'std::less<{0}>',
2761 3: 'std::allocator<std::pair<{0} const, {1}>>'})
2762 add_one_template_type_printer(obj
, 'multimap',
2763 {2: 'std::less<{0}>',
2764 3: 'std::allocator<std::pair<{0} const, {1}>>'})
2765 add_one_template_type_printer(obj
, 'set',
2766 {1: 'std::less<{0}>', 2: 'std::allocator<{0}>'})
2767 add_one_template_type_printer(obj
, 'multiset',
2768 {1: 'std::less<{0}>', 2: 'std::allocator<{0}>'})
2769 add_one_template_type_printer(obj
, 'unordered_map',
2770 {2: 'std::hash<{0}>',
2771 3: 'std::equal_to<{0}>',
2772 4: 'std::allocator<std::pair<{0} const, {1}>>'})
2773 add_one_template_type_printer(obj
, 'unordered_multimap',
2774 {2: 'std::hash<{0}>',
2775 3: 'std::equal_to<{0}>',
2776 4: 'std::allocator<std::pair<{0} const, {1}>>'})
2777 add_one_template_type_printer(obj
, 'unordered_set',
2778 {1: 'std::hash<{0}>',
2779 2: 'std::equal_to<{0}>',
2780 3: 'std::allocator<{0}>'})
2781 add_one_template_type_printer(obj
, 'unordered_multiset',
2782 {1: 'std::hash<{0}>',
2783 2: 'std::equal_to<{0}>',
2784 3: 'std::allocator<{0}>'})
2787 def register_libstdcxx_printers(obj
):
2788 """Register libstdc++ pretty-printers with objfile Obj."""
2791 global libstdcxx_printer
2794 gdb
.printing
.register_pretty_printer(obj
, libstdcxx_printer
)
2798 obj
.pretty_printers
.append(libstdcxx_printer
)
2800 register_type_printers(obj
)
2803 def build_libstdcxx_dictionary():
2804 global libstdcxx_printer
2806 libstdcxx_printer
= Printer("libstdc++-v6")
2808 # libstdc++ objects requiring pretty-printing.
2810 # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
2811 libstdcxx_printer
.add_version('std::', 'basic_string', StdStringPrinter
)
2812 libstdcxx_printer
.add_version(
2813 'std::__cxx11::', 'basic_string', StdStringPrinter
)
2814 libstdcxx_printer
.add_container('std::', 'bitset', StdBitsetPrinter
)
2815 libstdcxx_printer
.add_container('std::', 'deque', StdDequePrinter
)
2816 libstdcxx_printer
.add_container('std::', 'list', StdListPrinter
)
2817 libstdcxx_printer
.add_container('std::__cxx11::', 'list', StdListPrinter
)
2818 libstdcxx_printer
.add_container('std::', 'map', StdMapPrinter
)
2819 libstdcxx_printer
.add_container('std::', 'multimap', StdMapPrinter
)
2820 libstdcxx_printer
.add_container('std::', 'multiset', StdSetPrinter
)
2821 libstdcxx_printer
.add_version('std::', 'pair', StdPairPrinter
)
2822 libstdcxx_printer
.add_version('std::', 'priority_queue',
2823 StdStackOrQueuePrinter
)
2824 libstdcxx_printer
.add_version('std::', 'queue', StdStackOrQueuePrinter
)
2825 libstdcxx_printer
.add_version('std::', 'tuple', StdTuplePrinter
)
2826 libstdcxx_printer
.add_container('std::', 'set', StdSetPrinter
)
2827 libstdcxx_printer
.add_version('std::', 'stack', StdStackOrQueuePrinter
)
2828 libstdcxx_printer
.add_version('std::', 'unique_ptr', UniquePointerPrinter
)
2829 libstdcxx_printer
.add_container('std::', 'vector', StdVectorPrinter
)
2831 libstdcxx_printer
.add_version('std::', 'locale', StdLocalePrinter
)
2834 if hasattr(gdb
.Value
, 'dynamic_type'):
2835 libstdcxx_printer
.add_version('std::', 'error_code',
2836 StdErrorCodePrinter
)
2837 libstdcxx_printer
.add_version('std::', 'error_condition',
2838 StdErrorCodePrinter
)
2840 # Printer registrations for classes compiled with -D_GLIBCXX_DEBUG.
2841 libstdcxx_printer
.add('std::__debug::bitset', StdBitsetPrinter
)
2842 libstdcxx_printer
.add('std::__debug::deque', StdDequePrinter
)
2843 libstdcxx_printer
.add('std::__debug::list', StdListPrinter
)
2844 libstdcxx_printer
.add('std::__debug::map', StdMapPrinter
)
2845 libstdcxx_printer
.add('std::__debug::multimap', StdMapPrinter
)
2846 libstdcxx_printer
.add('std::__debug::multiset', StdSetPrinter
)
2847 libstdcxx_printer
.add('std::__debug::set', StdSetPrinter
)
2848 libstdcxx_printer
.add('std::__debug::vector', StdVectorPrinter
)
2850 # These are the TR1 and C++11 printers.
2851 # For array - the default GDB pretty-printer seems reasonable.
2852 libstdcxx_printer
.add_version('std::', 'shared_ptr', SharedPointerPrinter
)
2853 libstdcxx_printer
.add_version('std::', 'weak_ptr', SharedPointerPrinter
)
2854 libstdcxx_printer
.add_container('std::', 'unordered_map',
2855 Tr1UnorderedMapPrinter
)
2856 libstdcxx_printer
.add_container('std::', 'unordered_set',
2857 Tr1UnorderedSetPrinter
)
2858 libstdcxx_printer
.add_container('std::', 'unordered_multimap',
2859 Tr1UnorderedMapPrinter
)
2860 libstdcxx_printer
.add_container('std::', 'unordered_multiset',
2861 Tr1UnorderedSetPrinter
)
2862 libstdcxx_printer
.add_container('std::', 'forward_list',
2863 StdForwardListPrinter
)
2865 libstdcxx_printer
.add_version(
2866 'std::tr1::', 'shared_ptr', SharedPointerPrinter
)
2867 libstdcxx_printer
.add_version(
2868 'std::tr1::', 'weak_ptr', SharedPointerPrinter
)
2869 libstdcxx_printer
.add_version('std::tr1::', 'unordered_map',
2870 Tr1UnorderedMapPrinter
)
2871 libstdcxx_printer
.add_version('std::tr1::', 'unordered_set',
2872 Tr1UnorderedSetPrinter
)
2873 libstdcxx_printer
.add_version('std::tr1::', 'unordered_multimap',
2874 Tr1UnorderedMapPrinter
)
2875 libstdcxx_printer
.add_version('std::tr1::', 'unordered_multiset',
2876 Tr1UnorderedSetPrinter
)
2878 libstdcxx_printer
.add_version('std::', 'initializer_list',
2879 StdInitializerListPrinter
)
2880 libstdcxx_printer
.add_version('std::', 'atomic', StdAtomicPrinter
)
2881 libstdcxx_printer
.add_version(
2882 'std::', 'basic_stringbuf', StdStringBufPrinter
)
2883 libstdcxx_printer
.add_version(
2884 'std::__cxx11::', 'basic_stringbuf', StdStringBufPrinter
)
2885 for sstream
in ('istringstream', 'ostringstream', 'stringstream'):
2886 libstdcxx_printer
.add_version(
2887 'std::', 'basic_' + sstream
, StdStringStreamPrinter
)
2888 libstdcxx_printer
.add_version(
2889 'std::__cxx11::', 'basic_' + sstream
, StdStringStreamPrinter
)
2891 libstdcxx_printer
.add_version('std::chrono::', 'duration',
2892 StdChronoDurationPrinter
)
2893 libstdcxx_printer
.add_version('std::chrono::', 'time_point',
2894 StdChronoTimePointPrinter
)
2895 libstdcxx_printer
.add_version('std::', 'integral_constant',
2896 StdIntegralConstantPrinter
)
2898 # std::regex components
2899 libstdcxx_printer
.add_version('std::__detail::', '_State',
2900 StdRegexStatePrinter
)
2902 # These are the C++11 printer registrations for -D_GLIBCXX_DEBUG cases.
2903 # The tr1 namespace containers do not have any debug equivalents,
2904 # so do not register printers for them.
2905 libstdcxx_printer
.add('std::__debug::unordered_map',
2906 Tr1UnorderedMapPrinter
)
2907 libstdcxx_printer
.add('std::__debug::unordered_set',
2908 Tr1UnorderedSetPrinter
)
2909 libstdcxx_printer
.add('std::__debug::unordered_multimap',
2910 Tr1UnorderedMapPrinter
)
2911 libstdcxx_printer
.add('std::__debug::unordered_multiset',
2912 Tr1UnorderedSetPrinter
)
2913 libstdcxx_printer
.add('std::__debug::forward_list',
2914 StdForwardListPrinter
)
2916 # Library Fundamentals TS components
2917 libstdcxx_printer
.add_version('std::experimental::fundamentals_v1::',
2918 'any', StdExpAnyPrinter
)
2919 libstdcxx_printer
.add_version('std::experimental::fundamentals_v1::',
2920 'optional', StdExpOptionalPrinter
)
2921 libstdcxx_printer
.add_version('std::experimental::fundamentals_v1::',
2922 'basic_string_view', StdExpStringViewPrinter
)
2923 # Filesystem TS components
2924 libstdcxx_printer
.add_version('std::experimental::filesystem::v1::',
2925 'path', StdExpPathPrinter
)
2926 libstdcxx_printer
.add_version('std::experimental::filesystem::v1::__cxx11::',
2927 'path', StdExpPathPrinter
)
2928 libstdcxx_printer
.add_version('std::filesystem::',
2929 'path', StdPathPrinter
)
2930 libstdcxx_printer
.add_version('std::filesystem::__cxx11::',
2931 'path', StdPathPrinter
)
2934 libstdcxx_printer
.add_version('std::',
2935 'any', StdExpAnyPrinter
)
2936 libstdcxx_printer
.add_version('std::',
2937 'optional', StdExpOptionalPrinter
)
2938 libstdcxx_printer
.add_version('std::',
2939 'basic_string_view', StdExpStringViewPrinter
)
2940 libstdcxx_printer
.add_version('std::',
2941 'variant', StdVariantPrinter
)
2942 libstdcxx_printer
.add_version('std::',
2943 '_Node_handle', StdNodeHandlePrinter
)
2946 libstdcxx_printer
.add_version(
2947 'std::', 'partial_ordering', StdCmpCatPrinter
)
2948 libstdcxx_printer
.add_version('std::', 'weak_ordering', StdCmpCatPrinter
)
2949 libstdcxx_printer
.add_version('std::', 'strong_ordering', StdCmpCatPrinter
)
2950 libstdcxx_printer
.add_version('std::', 'span', StdSpanPrinter
)
2951 libstdcxx_printer
.add_version('std::', 'basic_format_args',
2952 StdFormatArgsPrinter
)
2953 for c
in ['day', 'month', 'year', 'weekday', 'weekday_indexed', 'weekday_last',
2954 'month_day', 'month_day_last', 'month_weekday', 'month_weekday_last',
2955 'year_month', 'year_month_day', 'year_month_day_last',
2956 'year_month_weekday', 'year_month_weekday_last', 'hh_mm_ss']:
2957 libstdcxx_printer
.add_version('std::chrono::', c
,
2958 StdChronoCalendarPrinter
)
2959 libstdcxx_printer
.add_version('std::chrono::', 'time_zone',
2960 StdChronoTimeZonePrinter
)
2961 libstdcxx_printer
.add_version('std::chrono::', 'time_zone_link',
2962 StdChronoTimeZonePrinter
)
2963 libstdcxx_printer
.add_version('std::chrono::', 'zoned_time',
2964 StdChronoZonedTimePrinter
)
2965 libstdcxx_printer
.add_version('std::chrono::', 'leap_second',
2966 StdChronoLeapSecondPrinter
)
2967 libstdcxx_printer
.add_version(
2968 'std::chrono::', 'tzdb', StdChronoTzdbPrinter
)
2969 # libstdcxx_printer.add_version('std::chrono::(anonymous namespace)', 'Rule',
2970 # StdChronoTimeZoneRulePrinter)
2973 libstdcxx_printer
.add_version('std::', 'text_encoding',
2974 StdTextEncodingPrinter
)
2976 libstdcxx_printer
.add_version('__gnu_cxx::', 'slist', StdSlistPrinter
)
2979 # These shouldn't be necessary, if GDB "print *i" worked.
2980 # But it often doesn't, so here they are.
2981 libstdcxx_printer
.add_container('std::', '_List_iterator',
2982 StdListIteratorPrinter
)
2983 libstdcxx_printer
.add_container('std::', '_List_const_iterator',
2984 StdListIteratorPrinter
)
2985 libstdcxx_printer
.add_version('std::', '_Rb_tree_iterator',
2986 StdRbtreeIteratorPrinter
)
2987 libstdcxx_printer
.add_version('std::', '_Rb_tree_const_iterator',
2988 StdRbtreeIteratorPrinter
)
2989 libstdcxx_printer
.add_container('std::', '_Deque_iterator',
2990 StdDequeIteratorPrinter
)
2991 libstdcxx_printer
.add_container('std::', '_Deque_const_iterator',
2992 StdDequeIteratorPrinter
)
2993 libstdcxx_printer
.add_version('__gnu_cxx::', '__normal_iterator',
2994 StdVectorIteratorPrinter
)
2995 libstdcxx_printer
.add_container('std::', '_Bit_iterator',
2996 StdBitIteratorPrinter
)
2997 libstdcxx_printer
.add_container('std::', '_Bit_const_iterator',
2998 StdBitIteratorPrinter
)
2999 libstdcxx_printer
.add_container('std::', '_Bit_reference',
3000 StdBitReferencePrinter
)
3001 libstdcxx_printer
.add_version('__gnu_cxx::', '_Slist_iterator',
3002 StdSlistIteratorPrinter
)
3003 libstdcxx_printer
.add_container('std::', '_Fwd_list_iterator',
3004 StdFwdListIteratorPrinter
)
3005 libstdcxx_printer
.add_container('std::', '_Fwd_list_const_iterator',
3006 StdFwdListIteratorPrinter
)
3008 # Debug (compiled with -D_GLIBCXX_DEBUG) printer
3010 libstdcxx_printer
.add('__gnu_debug::_Safe_iterator',
3011 StdDebugIteratorPrinter
)
3014 build_libstdcxx_dictionary()