[committed] libstdc++: Format Python code according to PEP8
Checks
Commit Message
Tested x86_64-linux. Pushed to trunk.
-- >8 --
These files were filtered through autopep8 to reformat them more
conventionally.
libstdc++-v3/ChangeLog:
* python/libstdcxx/v6/printers.py: Reformat.
* python/libstdcxx/v6/xmethods.py: Likewise.
---
libstdc++-v3/python/libstdcxx/v6/printers.py | 651 +++++++++++--------
libstdc++-v3/python/libstdcxx/v6/xmethods.py | 58 +-
2 files changed, 446 insertions(+), 263 deletions(-)
Comments
On Tue, Sep 12, 2023 at 7:46 AM Jonathan Wakely via Gcc-patches
<gcc-patches@gcc.gnu.org> wrote:
>
> Tested x86_64-linux. Pushed to trunk.
>
> -- >8 --
>
> These files were filtered through autopep8 to reformat them more
> conventionally.
>
Thanks for this; I'm wondering if it might be worthwhile to do
likewise for other python scripts elsewhere in the repository? e.g. in
contrib/
> libstdc++-v3/ChangeLog:
>
> * python/libstdcxx/v6/printers.py: Reformat.
> * python/libstdcxx/v6/xmethods.py: Likewise.
> ---
> libstdc++-v3/python/libstdcxx/v6/printers.py | 651 +++++++++++--------
> libstdc++-v3/python/libstdcxx/v6/xmethods.py | 58 +-
> 2 files changed, 446 insertions(+), 263 deletions(-)
>
> diff --git a/libstdc++-v3/python/libstdcxx/v6/printers.py b/libstdc++-v3/python/libstdcxx/v6/printers.py
> index 37a447b514b..c0056de2565 100644
> --- a/libstdc++-v3/python/libstdcxx/v6/printers.py
> +++ b/libstdc++-v3/python/libstdcxx/v6/printers.py
> @@ -18,10 +18,12 @@
> import gdb
> import itertools
> import re
> -import sys, os, errno
> +import sys
> +import os
> +import errno
> import datetime
>
> -### Python 2 + Python 3 compatibility code
> +# Python 2 + Python 3 compatibility code
>
> # Resources about compatibility:
> #
> @@ -38,7 +40,7 @@ import datetime
> # <https://sourceware.org/bugzilla/show_bug.cgi?id=17138>
>
> if sys.version_info[0] > 2:
> - ### Python 3 stuff
> + # Python 3 stuff
> Iterator = object
> # Python 3 folds these into the normal functions.
> imap = map
> @@ -47,7 +49,7 @@ if sys.version_info[0] > 2:
> long = int
> _utc_timezone = datetime.timezone.utc
> else:
> - ### Python 2 stuff
> + # Python 2 stuff
> class Iterator:
> """Compatibility mixin for iterators
>
> @@ -98,6 +100,8 @@ except ImportError:
> # Starting with the type ORIG, search for the member type NAME. This
> # handles searching upward through superclasses. This is needed to
> # work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
> +
> +
> def find_type(orig, name):
> typ = orig.strip_typedefs()
> while True:
> @@ -116,8 +120,10 @@ def find_type(orig, name):
> else:
> raise ValueError("Cannot find type %s::%s" % (str(orig), name))
>
> +
> _versioned_namespace = '__8::'
>
> +
> def lookup_templ_spec(templ, *args):
> """
> Lookup template specialization templ<args...>
> @@ -139,6 +145,8 @@ def lookup_templ_spec(templ, *args):
>
> # Use this to find container node types instead of find_type,
> # see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91997 for details.
> +
> +
> def lookup_node_type(nodename, containertype):
> """
> Lookup specialization of template NODENAME corresponding to CONTAINERTYPE.
> @@ -168,6 +176,7 @@ def lookup_node_type(nodename, containertype):
> pass
> return None
>
> +
> def is_member_of_namespace(typ, *namespaces):
> """
> Test whether a type is a member of one of the specified namespaces.
> @@ -181,6 +190,7 @@ def is_member_of_namespace(typ, *namespaces):
> return True
> return False
>
> +
> def is_specialization_of(x, template_name):
> """
> Test whether a type is a specialization of the named class template.
> @@ -195,12 +205,14 @@ def is_specialization_of(x, template_name):
> return re.match('^std::(%s)?%s<.*>$' % (_versioned_namespace, template_name), x) is not None
> return re.match('^std::%s<.*>$' % template_name, x) is not None
>
> +
> def strip_versioned_namespace(typename):
> global _versioned_namespace
> if _versioned_namespace:
> return typename.replace(_versioned_namespace, '')
> return typename
>
> +
> def strip_inline_namespaces(type_str):
> "Remove known inline namespaces from the canonical name of a type."
> type_str = strip_versioned_namespace(type_str)
> @@ -212,6 +224,7 @@ def strip_inline_namespaces(type_str):
> type_str = type_str.replace(fs_ns+'v1::', fs_ns)
> return type_str
>
> +
> def get_template_arg_list(type_obj):
> "Return a type's template arguments as a list"
> n = 0
> @@ -223,6 +236,7 @@ def get_template_arg_list(type_obj):
> return template_args
> n += 1
>
> +
> class SmartPtrIterator(Iterator):
> "An iterator for smart pointer types with a single 'child' value"
>
> @@ -238,28 +252,29 @@ class SmartPtrIterator(Iterator):
> self.val, val = None, self.val
> return ('get()', val)
>
> +
> class SharedPointerPrinter:
> "Print a shared_ptr, weak_ptr, atomic<shared_ptr>, or atomic<weak_ptr>"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.typename = strip_versioned_namespace(typename)
> self.val = val
> self.pointer = val['_M_ptr']
>
> - def children (self):
> + def children(self):
> return SmartPtrIterator(self.pointer)
>
> # Return the _Sp_counted_base<>* that holds the refcounts.
> - def _get_refcounts (self):
> + def _get_refcounts(self):
> if self.typename == 'std::atomic':
> # A tagged pointer is stored as uintptr_t.
> ptr_val = self.val['_M_refcount']['_M_val']['_M_i']
> - ptr_val = ptr_val - (ptr_val % 2) # clear lock bit
> + ptr_val = ptr_val - (ptr_val % 2) # clear lock bit
> ptr_type = find_type(self.val['_M_refcount'].type, 'pointer')
> return ptr_val.cast(ptr_type)
> return self.val['_M_refcount']['_M_pi']
>
> - def to_string (self):
> + def to_string(self):
> state = 'empty'
> refcounts = self._get_refcounts()
> targ = self.val.type.template_argument(0)
> @@ -271,19 +286,23 @@ class SharedPointerPrinter:
> if usecount == 0:
> state = 'expired, weak count %d' % weakcount
> else:
> - state = 'use count %d, weak count %d' % (usecount, weakcount - 1)
> + state = 'use count %d, weak count %d' % (
> + usecount, weakcount - 1)
> return '%s<%s> (%s)' % (self.typename, targ, state)
>
> +
> def _tuple_impl_get(val):
> "Return the tuple element stored in a _Tuple_impl<N, T> base class."
> bases = val.type.fields()
> if not bases[-1].is_base_class:
> - raise ValueError("Unsupported implementation for std::tuple: %s" % str(val.type))
> + raise ValueError(
> + "Unsupported implementation for std::tuple: %s" % str(val.type))
> # Get the _Head_base<N, T> base class:
> head_base = val.cast(bases[-1].type)
> fields = head_base.type.fields()
> if len(fields) == 0:
> - raise ValueError("Unsupported implementation for std::tuple: %s" % str(val.type))
> + raise ValueError(
> + "Unsupported implementation for std::tuple: %s" % str(val.type))
> if fields[0].name == '_M_head_impl':
> # The tuple element is the _Head_base::_M_head_impl data member.
> return head_base['_M_head_impl']
> @@ -292,7 +311,9 @@ def _tuple_impl_get(val):
> # Cast to that empty base class.
> return head_base.cast(fields[0].type)
> else:
> - raise ValueError("Unsupported implementation for std::tuple: %s" % str(val.type))
> + raise ValueError(
> + "Unsupported implementation for std::tuple: %s" % str(val.type))
> +
>
> def tuple_get(n, val):
> "Return the result of std::get<n>(val) on a std::tuple"
> @@ -307,6 +328,7 @@ def tuple_get(n, val):
> n -= 1
> return _tuple_impl_get(node)
>
> +
> def unique_ptr_get(val):
> "Return the result of val.get() on a std::unique_ptr"
> # std::unique_ptr<T, D> contains a std::tuple<D::pointer, D>,
> @@ -315,30 +337,34 @@ def unique_ptr_get(val):
> impl_type = val.type.fields()[0].type.strip_typedefs()
> # Check for new implementations first:
> if is_specialization_of(impl_type, '__uniq_ptr_data') \
> - or is_specialization_of(impl_type, '__uniq_ptr_impl'):
> + or is_specialization_of(impl_type, '__uniq_ptr_impl'):
> tuple_member = val['_M_t']['_M_t']
> elif is_specialization_of(impl_type, 'tuple'):
> tuple_member = val['_M_t']
> else:
> - raise ValueError("Unsupported implementation for unique_ptr: %s" % str(impl_type))
> + raise ValueError(
> + "Unsupported implementation for unique_ptr: %s" % str(impl_type))
> return tuple_get(0, tuple_member)
>
> +
> class UniquePointerPrinter:
> "Print a unique_ptr"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.val = val
>
> - def children (self):
> + def children(self):
> return SmartPtrIterator(unique_ptr_get(self.val))
>
> - def to_string (self):
> + def to_string(self):
> return ('std::unique_ptr<%s>' % (str(self.val.type.template_argument(0))))
>
> +
> def get_value_from_aligned_membuf(buf, valtype):
> """Returns the value held in a __gnu_cxx::__aligned_membuf."""
> return buf['_M_storage'].address.cast(valtype.pointer()).dereference()
>
> +
> def get_value_from_list_node(node):
> """Returns the value held in an _List_node<_Val>"""
> try:
> @@ -354,6 +380,7 @@ def get_value_from_list_node(node):
> pass
> raise ValueError("Unsupported implementation for %s" % str(node.type))
>
> +
> class StdListPrinter:
> "Print a std::list"
>
> @@ -391,6 +418,7 @@ class StdListPrinter:
> return 'empty %s' % (self.typename)
> return '%s' % (self.typename)
>
> +
> class NodeIteratorPrinter:
> def __init__(self, typename, val, contname, nodename):
> self.val = val
> @@ -404,12 +432,14 @@ class NodeIteratorPrinter:
> node = self.val['_M_node'].cast(self.nodetype.pointer()).dereference()
> return str(get_value_from_list_node(node))
>
> +
> class StdListIteratorPrinter(NodeIteratorPrinter):
> "Print std::list::iterator"
>
> def __init__(self, typename, val):
> NodeIteratorPrinter.__init__(self, typename, val, 'list', '_List_node')
>
> +
> class StdFwdListIteratorPrinter(NodeIteratorPrinter):
> "Print std::forward_list::iterator"
>
> @@ -417,6 +447,7 @@ class StdFwdListIteratorPrinter(NodeIteratorPrinter):
> NodeIteratorPrinter.__init__(self, typename, val, 'forward_list',
> '_Fwd_list_node')
>
> +
> class StdSlistPrinter:
> "Print a __gnu_cxx::slist"
>
> @@ -450,6 +481,7 @@ class StdSlistPrinter:
> return 'empty __gnu_cxx::slist'
> return '__gnu_cxx::slist'
>
> +
> class StdSlistIteratorPrinter:
> "Print __gnu_cxx::slist::iterator"
>
> @@ -459,20 +491,22 @@ class StdSlistIteratorPrinter:
> def to_string(self):
> if not self.val['_M_node']:
> return 'non-dereferenceable iterator for __gnu_cxx::slist'
> - nodetype = lookup_node_type('__gnu_cxx::_Slist_node', self.val.type).pointer()
> + nodetype = lookup_node_type(
> + '__gnu_cxx::_Slist_node', self.val.type).pointer()
> return str(self.val['_M_node'].cast(nodetype).dereference()['_M_data'])
>
> +
> class StdVectorPrinter:
> "Print a std::vector"
>
> class _iterator(Iterator):
> - def __init__ (self, start, finish, bitvec):
> + def __init__(self, start, finish, bitvec):
> self.bitvec = bitvec
> if bitvec:
> - self.item = start['_M_p']
> - self.so = 0
> + self.item = start['_M_p']
> + self.so = 0
> self.finish = finish['_M_p']
> - self.fo = finish['_M_offset']
> + self.fo = finish['_M_offset']
> itype = self.item.dereference().type
> self.isize = 8 * itype.sizeof
> else:
> @@ -519,20 +553,21 @@ class StdVectorPrinter:
> if self.is_bool:
> start = self.val['_M_impl']['_M_start']['_M_p']
> finish = self.val['_M_impl']['_M_finish']['_M_p']
> - fo = self.val['_M_impl']['_M_finish']['_M_offset']
> + fo = self.val['_M_impl']['_M_finish']['_M_offset']
> itype = start.dereference().type
> bl = 8 * itype.sizeof
> - length = bl * (finish - start) + fo
> + length = bl * (finish - start) + fo
> capacity = bl * (end - start)
> return ('%s<bool> of length %d, capacity %d'
> - % (self.typename, int (length), int (capacity)))
> + % (self.typename, int(length), int(capacity)))
> else:
> return ('%s of length %d, capacity %d'
> - % (self.typename, int (finish - start), int (end - start)))
> + % (self.typename, int(finish - start), int(end - start)))
>
> def display_hint(self):
> return 'array'
>
> +
> class StdVectorIteratorPrinter:
> "Print std::vector::iterator"
>
> @@ -544,6 +579,7 @@ class StdVectorIteratorPrinter:
> return 'non-dereferenceable iterator for std::vector'
> return str(self.val['_M_current'].dereference())
>
> +
> class StdBitIteratorPrinter:
> "Print std::vector<bool>'s _Bit_iterator and _Bit_const_iterator"
>
> @@ -555,6 +591,7 @@ class StdBitIteratorPrinter:
> return 'non-dereferenceable iterator for std::vector<bool>'
> return bool(self.val['_M_p'].dereference() & (1 << self.val['_M_offset']))
>
> +
> class StdBitReferencePrinter:
> "Print std::vector<bool>::reference"
>
> @@ -566,51 +603,54 @@ class StdBitReferencePrinter:
> return 'invalid std::vector<bool>::reference'
> return bool(self.val['_M_p'].dereference() & (self.val['_M_mask']))
>
> +
> class StdTuplePrinter:
> "Print a std::tuple"
>
> class _iterator(Iterator):
> @staticmethod
> - def _is_nonempty_tuple (nodes):
> - if len (nodes) == 2:
> - if is_specialization_of (nodes[1].type, '__tuple_base'):
> + def _is_nonempty_tuple(nodes):
> + if len(nodes) == 2:
> + if is_specialization_of(nodes[1].type, '__tuple_base'):
> return True
> - elif len (nodes) == 1:
> + elif len(nodes) == 1:
> return True
> - elif len (nodes) == 0:
> + elif len(nodes) == 0:
> return False
> - raise ValueError("Top of tuple tree does not consist of a single node.")
> + raise ValueError(
> + "Top of tuple tree does not consist of a single node.")
>
> - def __init__ (self, head):
> + def __init__(self, head):
> self.head = head
>
> # Set the base class as the initial head of the
> # tuple.
> - nodes = self.head.type.fields ()
> - if self._is_nonempty_tuple (nodes):
> + nodes = self.head.type.fields()
> + if self._is_nonempty_tuple(nodes):
> # Set the actual head to the first pair.
> - self.head = self.head.cast (nodes[0].type)
> + self.head = self.head.cast(nodes[0].type)
> self.count = 0
>
> - def __iter__ (self):
> + def __iter__(self):
> return self
>
> - def __next__ (self):
> + def __next__(self):
> # Check for further recursions in the inheritance tree.
> # For a GCC 5+ tuple self.head is None after visiting all nodes:
> if not self.head:
> raise StopIteration
> - nodes = self.head.type.fields ()
> + nodes = self.head.type.fields()
> # For a GCC 4.x tuple there is a final node with no fields:
> - if len (nodes) == 0:
> + if len(nodes) == 0:
> raise StopIteration
> # Check that this iteration has an expected structure.
> - if len (nodes) > 2:
> - raise ValueError("Cannot parse more than 2 nodes in a tuple tree.")
> + if len(nodes) > 2:
> + raise ValueError(
> + "Cannot parse more than 2 nodes in a tuple tree.")
>
> - if len (nodes) == 1:
> + if len(nodes) == 1:
> # This is the last node of a GCC 5+ std::tuple.
> - impl = self.head.cast (nodes[0].type)
> + impl = self.head.cast(nodes[0].type)
> self.head = None
> else:
> # Either a node before the last node, or the last node of
> @@ -620,53 +660,55 @@ class StdTuplePrinter:
> # - Right node is the actual class contained in the tuple.
>
> # Process right node.
> - impl = self.head.cast (nodes[1].type)
> + impl = self.head.cast(nodes[1].type)
>
> # Process left node and set it as head.
> - self.head = self.head.cast (nodes[0].type)
> + self.head = self.head.cast(nodes[0].type)
>
> self.count = self.count + 1
>
> # Finally, check the implementation. If it is
> # wrapped in _M_head_impl return that, otherwise return
> # the value "as is".
> - fields = impl.type.fields ()
> - if len (fields) < 1 or fields[0].name != "_M_head_impl":
> + fields = impl.type.fields()
> + if len(fields) < 1 or fields[0].name != "_M_head_impl":
> return ('[%d]' % (self.count - 1), impl)
> else:
> return ('[%d]' % (self.count - 1), impl['_M_head_impl'])
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.typename = strip_versioned_namespace(typename)
> - self.val = val;
> + self.val = val
>
> - def children (self):
> - return self._iterator (self.val)
> + def children(self):
> + return self._iterator(self.val)
>
> - def to_string (self):
> - if len (self.val.type.fields ()) == 0:
> + def to_string(self):
> + if len(self.val.type.fields()) == 0:
> return 'empty %s' % (self.typename)
> return '%s containing' % (self.typename)
>
> +
> class StdStackOrQueuePrinter:
> "Print a std::stack or std::queue"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.typename = strip_versioned_namespace(typename)
> self.visualizer = gdb.default_visualizer(val['c'])
>
> - def children (self):
> + def children(self):
> return self.visualizer.children()
>
> - def to_string (self):
> + def to_string(self):
> return '%s wrapping: %s' % (self.typename,
> self.visualizer.to_string())
>
> - def display_hint (self):
> - if hasattr (self.visualizer, 'display_hint'):
> - return self.visualizer.display_hint ()
> + def display_hint(self):
> + if hasattr(self.visualizer, 'display_hint'):
> + return self.visualizer.display_hint()
> return None
>
> +
> class RbtreeIterator(Iterator):
> """
> Turn an RB-tree-based container (std::map, std::set etc.) into
> @@ -682,7 +724,7 @@ class RbtreeIterator(Iterator):
> return self
>
> def __len__(self):
> - return int (self.size)
> + return int(self.size)
>
> def __next__(self):
> if self.count == self.size:
> @@ -706,6 +748,7 @@ class RbtreeIterator(Iterator):
> self.node = node
> return result
>
> +
> def get_value_from_Rb_tree_node(node):
> """Returns the value held in an _Rb_tree_node<_Val>"""
> try:
> @@ -724,29 +767,32 @@ def get_value_from_Rb_tree_node(node):
> # This is a pretty printer for std::_Rb_tree_iterator (which is
> # std::map::iterator), and has nothing to do with the RbtreeIterator
> # class above.
> +
> +
> class StdRbtreeIteratorPrinter:
> "Print std::map::iterator, std::set::iterator, etc."
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.val = val
> nodetype = lookup_node_type('_Rb_tree_node', self.val.type)
> self.link_type = nodetype.pointer()
>
> - def to_string (self):
> + def to_string(self):
> if not self.val['_M_node']:
> return 'non-dereferenceable iterator for associative container'
> node = self.val['_M_node'].cast(self.link_type).dereference()
> return str(get_value_from_Rb_tree_node(node))
>
> +
> class StdDebugIteratorPrinter:
> "Print a debug enabled version of an iterator"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.val = val
>
> # Just strip away the encapsulating __gnu_debug::_Safe_iterator
> # and return the wrapped iterator value.
> - def to_string (self):
> + def to_string(self):
> base_type = gdb.lookup_type('__gnu_debug::_Safe_iterator_base')
> itype = self.val.type.template_argument(0)
> safe_seq = self.val.cast(base_type)['_M_sequence']
> @@ -756,10 +802,12 @@ class StdDebugIteratorPrinter:
> return "invalid iterator"
> return str(self.val.cast(itype))
>
> +
> def num_elements(num):
> """Return either "1 element" or "N elements" depending on the argument."""
> return '1 element' if num == 1 else '%d elements' % num
>
> +
> class StdMapPrinter:
> "Print a std::map or std::multimap"
>
> @@ -786,21 +834,22 @@ class StdMapPrinter:
> self.count = self.count + 1
> return result
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.typename = strip_versioned_namespace(typename)
> self.val = val
>
> - def to_string (self):
> + def to_string(self):
> return '%s with %s' % (self.typename,
> - num_elements(len(RbtreeIterator (self.val))))
> + num_elements(len(RbtreeIterator(self.val))))
>
> - def children (self):
> + def children(self):
> node = lookup_node_type('_Rb_tree_node', self.val.type).pointer()
> - return self._iter (RbtreeIterator (self.val), node)
> + return self._iter(RbtreeIterator(self.val), node)
>
> - def display_hint (self):
> + def display_hint(self):
> return 'map'
>
> +
> class StdSetPrinter:
> "Print a std::set or std::multiset"
>
> @@ -824,17 +873,18 @@ class StdSetPrinter:
> self.count = self.count + 1
> return result
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.typename = strip_versioned_namespace(typename)
> self.val = val
>
> - def to_string (self):
> + def to_string(self):
> return '%s with %s' % (self.typename,
> - num_elements(len(RbtreeIterator (self.val))))
> + num_elements(len(RbtreeIterator(self.val))))
>
> - def children (self):
> + def children(self):
> node = lookup_node_type('_Rb_tree_node', self.val.type).pointer()
> - return self._iter (RbtreeIterator (self.val), node)
> + return self._iter(RbtreeIterator(self.val), node)
> +
>
> class StdBitsetPrinter:
> "Print a std::bitset"
> @@ -843,12 +893,12 @@ class StdBitsetPrinter:
> self.typename = strip_versioned_namespace(typename)
> self.val = val
>
> - def to_string (self):
> + def to_string(self):
> # If template_argument handled values, we could print the
> # size. Or we could use a regexp on the type.
> return '%s' % (self.typename)
>
> - def children (self):
> + def children(self):
> try:
> # An empty bitset may not have any members which will
> # result in an exception being thrown.
> @@ -862,7 +912,7 @@ class StdBitsetPrinter:
> # array. This depends on the template specialization used.
> # If it is a single long, convert to a single element list.
> if wtype.code == gdb.TYPE_CODE_ARRAY:
> - tsize = wtype.target ().sizeof
> + tsize = wtype.target().sizeof
> else:
> words = [words]
> tsize = wtype.sizeof
> @@ -882,6 +932,7 @@ class StdBitsetPrinter:
> byte = byte + 1
> return result
>
> +
> class StdDequePrinter:
> "Print a std::deque"
>
> @@ -921,7 +972,7 @@ class StdDequePrinter:
> self.elttype = val.type.template_argument(0)
> size = self.elttype.sizeof
> if size < 512:
> - self.buffer_size = int (512 / size)
> + self.buffer_size = int(512 / size)
> else:
> self.buffer_size = 1
>
> @@ -943,9 +994,10 @@ class StdDequePrinter:
> return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
> end['_M_cur'], self.buffer_size)
>
> - def display_hint (self):
> + def display_hint(self):
> return 'array'
>
> +
> class StdDequeIteratorPrinter:
> "Print std::deque::iterator"
>
> @@ -957,6 +1009,7 @@ class StdDequeIteratorPrinter:
> return 'non-dereferenceable iterator for std::deque'
> return str(self.val['_M_cur'].dereference())
>
> +
> class StdStringPrinter:
> "Print a std::basic_string of some kind"
>
> @@ -968,28 +1021,29 @@ class StdStringPrinter:
> # Make sure &string works, too.
> type = self.val.type
> if type.code == gdb.TYPE_CODE_REF:
> - type = type.target ()
> + type = type.target()
>
> # Calculate the length of the string so that to_string returns
> # the string according to length, not according to first null
> # encountered.
> - ptr = self.val ['_M_dataplus']['_M_p']
> + ptr = self.val['_M_dataplus']['_M_p']
> if self.new_string:
> length = self.val['_M_string_length']
> # https://sourceware.org/bugzilla/show_bug.cgi?id=17728
> ptr = ptr.cast(ptr.type.strip_typedefs())
> else:
> - realtype = type.unqualified ().strip_typedefs ()
> - reptype = gdb.lookup_type (str (realtype) + '::_Rep').pointer ()
> + realtype = type.unqualified().strip_typedefs()
> + reptype = gdb.lookup_type(str(realtype) + '::_Rep').pointer()
> header = ptr.cast(reptype) - 1
> - length = header.dereference ()['_M_length']
> + length = header.dereference()['_M_length']
> if hasattr(ptr, "lazy_string"):
> - return ptr.lazy_string (length = length)
> - return ptr.string (length = length)
> + return ptr.lazy_string(length=length)
> + return ptr.string(length=length)
>
> - def display_hint (self):
> + def display_hint(self):
> return 'string'
>
> +
> def access_streambuf_ptrs(streambuf):
> "Access the streambuf put area pointers"
> pbase = streambuf['_M_out_beg']
> @@ -997,6 +1051,7 @@ def access_streambuf_ptrs(streambuf):
> egptr = streambuf['_M_in_end']
> return pbase, pptr, egptr
>
> +
> class StdStringBufPrinter:
> "Print a std::basic_stringbuf"
>
> @@ -1008,14 +1063,15 @@ class StdStringBufPrinter:
> # Logic from basic_stringbuf::_M_high_mark()
> if pptr:
> if not egptr or pptr > egptr:
> - return pbase.string(length = pptr - pbase)
> + return pbase.string(length=pptr - pbase)
> else:
> - return pbase.string(length = egptr - pbase)
> + return pbase.string(length=egptr - pbase)
> return self.val['_M_string']
>
> def display_hint(self):
> return 'string'
>
> +
> class StdStringStreamPrinter:
> "Print a std::basic_stringstream"
>
> @@ -1041,8 +1097,9 @@ class StdStringStreamPrinter:
> return None
> return 'string'
>
> +
> class Tr1HashtableIterator(Iterator):
> - def __init__ (self, hashtable):
> + def __init__(self, hashtable):
> self.buckets = hashtable['_M_buckets']
> self.bucket = 0
> self.bucket_count = hashtable['_M_bucket_count']
> @@ -1054,15 +1111,15 @@ class Tr1HashtableIterator(Iterator):
> break
> self.bucket = self.bucket + 1
>
> - def __iter__ (self):
> + def __iter__(self):
> return self
>
> - def __next__ (self):
> + def __next__(self):
> if self.node == 0:
> raise StopIteration
> node = self.node.cast(self.node_type)
> result = node.dereference()['_M_v']
> - self.node = node.dereference()['_M_next'];
> + self.node = node.dereference()['_M_next']
> if self.node == 0:
> self.bucket = self.bucket + 1
> while self.bucket != self.bucket_count:
> @@ -1072,6 +1129,7 @@ class Tr1HashtableIterator(Iterator):
> self.bucket = self.bucket + 1
> return result
>
> +
> class StdHashtableIterator(Iterator):
> def __init__(self, hashtable):
> self.node = hashtable['_M_before_begin']['_M_nxt']
> @@ -1093,76 +1151,81 @@ class StdHashtableIterator(Iterator):
> valptr = valptr.cast(elt.type.template_argument(0).pointer())
> return valptr.dereference()
>
> +
> class Tr1UnorderedSetPrinter:
> "Print a std::unordered_set or tr1::unordered_set"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.typename = strip_versioned_namespace(typename)
> self.val = val
>
> - def hashtable (self):
> + def hashtable(self):
> if self.typename.startswith('std::tr1'):
> return self.val
> return self.val['_M_h']
>
> - def to_string (self):
> + def to_string(self):
> count = self.hashtable()['_M_element_count']
> return '%s with %s' % (self.typename, num_elements(count))
>
> @staticmethod
> - def format_count (i):
> + def format_count(i):
> return '[%d]' % i
>
> - def children (self):
> - counter = imap (self.format_count, itertools.count())
> + def children(self):
> + counter = imap(self.format_count, itertools.count())
> if self.typename.startswith('std::tr1'):
> - return izip (counter, Tr1HashtableIterator (self.hashtable()))
> - return izip (counter, StdHashtableIterator (self.hashtable()))
> + return izip(counter, Tr1HashtableIterator(self.hashtable()))
> + return izip(counter, StdHashtableIterator(self.hashtable()))
> +
>
> class Tr1UnorderedMapPrinter:
> "Print a std::unordered_map or tr1::unordered_map"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.typename = strip_versioned_namespace(typename)
> self.val = val
>
> - def hashtable (self):
> + def hashtable(self):
> if self.typename.startswith('std::tr1'):
> return self.val
> return self.val['_M_h']
>
> - def to_string (self):
> + def to_string(self):
> count = self.hashtable()['_M_element_count']
> return '%s with %s' % (self.typename, num_elements(count))
>
> @staticmethod
> - def flatten (list):
> + def flatten(list):
> for elt in list:
> for i in elt:
> yield i
>
> @staticmethod
> - def format_one (elt):
> + def format_one(elt):
> return (elt['first'], elt['second'])
>
> @staticmethod
> - def format_count (i):
> + def format_count(i):
> return '[%d]' % i
>
> - def children (self):
> - counter = imap (self.format_count, itertools.count())
> + def children(self):
> + counter = imap(self.format_count, itertools.count())
> # Map over the hash table and flatten the result.
> if self.typename.startswith('std::tr1'):
> - data = self.flatten (imap (self.format_one, Tr1HashtableIterator (self.hashtable())))
> + data = self.flatten(
> + imap(self.format_one, Tr1HashtableIterator(self.hashtable())))
> # Zip the two iterators together.
> - return izip (counter, data)
> - data = self.flatten (imap (self.format_one, StdHashtableIterator (self.hashtable())))
> + return izip(counter, data)
> + data = self.flatten(
> + imap(self.format_one, StdHashtableIterator(self.hashtable())))
> # Zip the two iterators together.
> - return izip (counter, data)
> + return izip(counter, data)
>
> - def display_hint (self):
> + def display_hint(self):
> return 'map'
>
> +
> class StdForwardListPrinter:
> "Print a std::forward_list"
>
> @@ -1199,10 +1262,11 @@ class StdForwardListPrinter:
> return 'empty %s' % self.typename
> return '%s' % self.typename
>
> +
> class SingleObjContainerPrinter(object):
> "Base class for printers of containers of single objects"
>
> - def __init__ (self, val, viz, hint = None):
> + def __init__(self, val, viz, hint=None):
> self.contained_value = val
> self.visualizer = viz
> self.hint = hint
> @@ -1216,10 +1280,10 @@ class SingleObjContainerPrinter(object):
> type) or str(type)
>
> class _contained(Iterator):
> - def __init__ (self, val):
> + def __init__(self, val):
> self.val = val
>
> - def __iter__ (self):
> + def __iter__(self):
> return self
>
> def __next__(self):
> @@ -1229,19 +1293,20 @@ class SingleObjContainerPrinter(object):
> self.val = None
> return ('[contained value]', retval)
>
> - def children (self):
> + def children(self):
> if self.contained_value is None:
> - return self._contained (None)
> - if hasattr (self.visualizer, 'children'):
> - return self.visualizer.children ()
> - return self._contained (self.contained_value)
> + return self._contained(None)
> + if hasattr(self.visualizer, 'children'):
> + return self.visualizer.children()
> + return self._contained(self.contained_value)
>
> - def display_hint (self):
> + def display_hint(self):
> # if contained value is a map we want to display in the same way
> - if hasattr (self.visualizer, 'children') and hasattr (self.visualizer, 'display_hint'):
> - return self.visualizer.display_hint ()
> + if hasattr(self.visualizer, 'children') and hasattr(self.visualizer, 'display_hint'):
> + return self.visualizer.display_hint()
> return self.hint
>
> +
> def function_pointer_to_name(f):
> "Find the name of the function referred to by the gdb.Value f, "
> " which should contain a function pointer from the program."
> @@ -1265,12 +1330,14 @@ def function_pointer_to_name(f):
> except:
> return None
>
> +
> class StdExpAnyPrinter(SingleObjContainerPrinter):
> "Print a std::any or std::experimental::any"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.typename = strip_versioned_namespace(typename)
> - self.typename = re.sub('^std::experimental::fundamentals_v\d::', 'std::experimental::', self.typename, 1)
> + self.typename = re.sub(
> + '^std::experimental::fundamentals_v\d::', 'std::experimental::', self.typename, 1)
> self.val = val
> self.contained_type = None
> contained_value = None
> @@ -1279,11 +1346,13 @@ class StdExpAnyPrinter(SingleObjContainerPrinter):
> if mgr != 0:
> func = function_pointer_to_name(mgr)
> if not func:
> - raise ValueError("Invalid function pointer in %s" % (self.typename))
> + raise ValueError(
> + "Invalid function pointer in %s" % (self.typename))
> rx = r"""({0}::_Manager_\w+<.*>)::_S_manage\((enum )?{0}::_Op, (const {0}|{0} const) ?\*, (union )?{0}::_Arg ?\*\)""".format(typename)
> m = re.match(rx, func)
> if not m:
> - raise ValueError("Unknown manager function in %s" % self.typename)
> + raise ValueError(
> + "Unknown manager function in %s" % self.typename)
>
> mgrname = m.group(1)
> # FIXME need to expand 'std::string' so that gdb.lookup_type works
> @@ -1291,11 +1360,13 @@ class StdExpAnyPrinter(SingleObjContainerPrinter):
> # This lookup for std::string might return the __cxx11 version,
> # but that's not necessarily the one used by the std::any
> # manager function we're trying to find.
> - strings = {str(gdb.lookup_type('std::string').strip_typedefs())}
> + strings = {
> + str(gdb.lookup_type('std::string').strip_typedefs())}
> # So also consider all the other possible std::string types!
> s = 'basic_string<char, std::char_traits<char>, std::allocator<char> >'
> - quals = ['std::', 'std::__cxx11::', 'std::' + _versioned_namespace]
> - strings |= {q+s for q in quals} # set of unique strings
> + quals = ['std::', 'std::__cxx11::',
> + 'std::' + _versioned_namespace]
> + strings |= {q+s for q in quals} # set of unique strings
> mgrtypes = []
> for s in strings:
> try:
> @@ -1312,7 +1383,8 @@ class StdExpAnyPrinter(SingleObjContainerPrinter):
> # std::any in a single program. Can we do better?
> # Maybe find the address of each type's _S_manage and
> # compare to the address stored in _M_manager?
> - raise ValueError('Cannot uniquely determine std::string type used in std::any')
> + raise ValueError(
> + 'Cannot uniquely determine std::string type used in std::any')
> mgrtype = mgrtypes[0]
> else:
> mgrtype = gdb.lookup_type(mgrname)
> @@ -1323,27 +1395,31 @@ class StdExpAnyPrinter(SingleObjContainerPrinter):
> elif '::_Manager_external' in mgrname:
> valptr = self.val['_M_storage']['_M_ptr']
> else:
> - raise ValueError("Unknown manager function in %s" % self.typename)
> - contained_value = valptr.cast(self.contained_type.pointer()).dereference()
> + raise ValueError(
> + "Unknown manager function in %s" % self.typename)
> + contained_value = valptr.cast(
> + self.contained_type.pointer()).dereference()
> visualizer = gdb.default_visualizer(contained_value)
> - super(StdExpAnyPrinter, self).__init__ (contained_value, visualizer)
> + super(StdExpAnyPrinter, self).__init__(contained_value, visualizer)
>
> - def to_string (self):
> + def to_string(self):
> if self.contained_type is None:
> return '%s [no contained value]' % self.typename
> desc = "%s containing " % self.typename
> - if hasattr (self.visualizer, 'children'):
> - return desc + self.visualizer.to_string ()
> - valtype = self._recognize (self.contained_type)
> + if hasattr(self.visualizer, 'children'):
> + return desc + self.visualizer.to_string()
> + valtype = self._recognize(self.contained_type)
> return desc + strip_versioned_namespace(str(valtype))
>
> +
> class StdExpOptionalPrinter(SingleObjContainerPrinter):
> "Print a std::optional or std::experimental::optional"
>
> - def __init__ (self, typename, val):
> - valtype = self._recognize (val.type.template_argument(0))
> + def __init__(self, typename, val):
> + valtype = self._recognize(val.type.template_argument(0))
> typename = strip_versioned_namespace(typename)
> - self.typename = re.sub('^std::(experimental::|)(fundamentals_v\d::|)(.*)', r'std::\1\3', typename, 1)
> + self.typename = re.sub(
> + '^std::(experimental::|)(fundamentals_v\d::|)(.*)', r'std::\1\3', typename, 1)
> payload = val['_M_payload']
> if self.typename.startswith('std::experimental'):
> engaged = val['_M_engaged']
> @@ -1356,19 +1432,21 @@ class StdExpOptionalPrinter(SingleObjContainerPrinter):
> contained_value = contained_value['_M_value']
> except:
> pass
> - visualizer = gdb.default_visualizer (contained_value)
> + visualizer = gdb.default_visualizer(contained_value)
> if not engaged:
> contained_value = None
> - super (StdExpOptionalPrinter, self).__init__ (contained_value, visualizer)
> + super(StdExpOptionalPrinter, self).__init__(
> + contained_value, visualizer)
>
> - def to_string (self):
> + def to_string(self):
> if self.contained_value is None:
> return "%s [no contained value]" % self.typename
> - if hasattr (self.visualizer, 'children'):
> + if hasattr(self.visualizer, 'children'):
> return "%s containing %s" % (self.typename,
> self.visualizer.to_string())
> return self.typename
>
> +
> class StdVariantPrinter(SingleObjContainerPrinter):
> "Print a std::variant"
>
> @@ -1383,9 +1461,11 @@ class StdVariantPrinter(SingleObjContainerPrinter):
> else:
> self.contained_type = alternatives[int(self.index)]
> addr = val['_M_u']['_M_first']['_M_storage'].address
> - contained_value = addr.cast(self.contained_type.pointer()).dereference()
> + contained_value = addr.cast(
> + self.contained_type.pointer()).dereference()
> visualizer = gdb.default_visualizer(contained_value)
> - super (StdVariantPrinter, self).__init__(contained_value, visualizer, 'array')
> + super(StdVariantPrinter, self).__init__(
> + contained_value, visualizer, 'array')
>
> def to_string(self):
> if self.contained_value is None:
> @@ -1395,18 +1475,21 @@ class StdVariantPrinter(SingleObjContainerPrinter):
> self.visualizer.to_string())
> return "%s [index %d]" % (self.typename, self.index)
>
> +
> class StdNodeHandlePrinter(SingleObjContainerPrinter):
> "Print a container node handle"
>
> def __init__(self, typename, val):
> self.value_type = val.type.template_argument(1)
> nodetype = val.type.template_argument(2).template_argument(0)
> - self.is_rb_tree_node = is_specialization_of(nodetype.name, '_Rb_tree_node')
> + self.is_rb_tree_node = is_specialization_of(
> + nodetype.name, '_Rb_tree_node')
> self.is_map_node = val.type.template_argument(0) != self.value_type
> nodeptr = val['_M_ptr']
> if nodeptr:
> if self.is_rb_tree_node:
> - contained_value = get_value_from_Rb_tree_node(nodeptr.dereference())
> + contained_value = get_value_from_Rb_tree_node(
> + nodeptr.dereference())
> else:
> contained_value = get_value_from_aligned_membuf(nodeptr['_M_storage'],
> self.value_type)
> @@ -1424,9 +1507,9 @@ class StdNodeHandlePrinter(SingleObjContainerPrinter):
> if not self.is_rb_tree_node:
> desc += 'unordered '
> if self.is_map_node:
> - desc += 'map';
> + desc += 'map'
> else:
> - desc += 'set';
> + desc += 'set'
>
> if self.contained_value:
> desc += ' with element'
> @@ -1436,31 +1519,33 @@ class StdNodeHandlePrinter(SingleObjContainerPrinter):
> else:
> return 'empty %s' % desc
>
> +
> class StdExpStringViewPrinter:
> "Print a std::basic_string_view or std::experimental::basic_string_view"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.val = val
>
> - def to_string (self):
> + def to_string(self):
> ptr = self.val['_M_str']
> len = self.val['_M_len']
> - if hasattr (ptr, "lazy_string"):
> - return ptr.lazy_string (length = len)
> - return ptr.string (length = len)
> + if hasattr(ptr, "lazy_string"):
> + return ptr.lazy_string(length=len)
> + return ptr.string(length=len)
>
> - def display_hint (self):
> + def display_hint(self):
> return 'string'
>
> +
> class StdExpPathPrinter:
> "Print a std::experimental::filesystem::path"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.val = val
> self.typename = typename
> start = self.val['_M_cmpts']['_M_impl']['_M_start']
> finish = self.val['_M_cmpts']['_M_impl']['_M_finish']
> - self.num_cmpts = int (finish - start)
> + self.num_cmpts = int(finish - start)
>
> def _path_type(self):
> t = str(self.val['_M_type'])
> @@ -1470,8 +1555,8 @@ class StdExpPathPrinter:
> return "root-name"
> return None
>
> - def to_string (self):
> - path = "%s" % self.val ['_M_pathname']
> + def to_string(self):
> + path = "%s" % self.val['_M_pathname']
> if self.num_cmpts == 0:
> t = self._path_type()
> if t:
> @@ -1504,10 +1589,11 @@ class StdExpPathPrinter:
> def children(self):
> return self._iterator(self.val['_M_cmpts'], self.typename)
>
> +
> class StdPathPrinter:
> "Print a std::filesystem::path"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.val = val
> self.typename = typename
> impl = unique_ptr_get(self.val['_M_cmpts']['_M_impl'])
> @@ -1525,8 +1611,8 @@ class StdPathPrinter:
> return "root-name"
> return None
>
> - def to_string (self):
> - path = "%s" % self.val ['_M_pathname']
> + def to_string(self):
> + path = "%s" % self.val['_M_pathname']
> if self.type != 0:
> t = self._path_type()
> if t:
> @@ -1609,27 +1695,29 @@ class StdPairPrinter:
> def to_string(self):
> return None
>
> +
> class StdCmpCatPrinter:
> "Print a comparison category object"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.typename = typename[typename.rfind(':')+1:]
> self.val = val['_M_value']
>
> - def to_string (self):
> + def to_string(self):
> if self.typename == 'strong_ordering' and self.val == 0:
> name = 'equal'
> else:
> - names = {2:'unordered', -1:'less', 0:'equivalent', 1:'greater'}
> + names = {2: 'unordered', -1: 'less', 0: 'equivalent', 1: 'greater'}
> name = names[int(self.val)]
> return 'std::{}::{}'.format(self.typename, name)
>
> +
> class StdErrorCodePrinter:
> "Print a std::error_code or std::error_condition"
>
> _system_is_posix = None # Whether std::system_category() use errno values.
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.val = val
> self.typename = strip_versioned_namespace(typename)
> # Do this only once ...
> @@ -1718,15 +1806,15 @@ class StdErrorCodePrinter:
> "Strip any nested-name-specifier from NAME to give an unqualified name"
> return name.split('::')[-1]
>
> - def to_string (self):
> + def to_string(self):
> value = self.val['_M_value']
> cat = self.val['_M_cat']
> name, alt_name, enum, is_errno = self._category_info(cat)
> if value == 0:
> - default_cats = { 'error_code' : 'system',
> - 'error_condition' : 'generic' }
> + default_cats = {'error_code': 'system',
> + 'error_condition': 'generic'}
> if name == default_cats[self._unqualified_name(self.typename)]:
> - return self.typename + ' = { }' # default-constructed value
> + return self.typename + ' = { }' # default-constructed value
>
> strval = str(value)
> if is_errno and value != 0:
> @@ -1747,24 +1835,24 @@ class StdErrorCodePrinter:
> class StdRegexStatePrinter:
> "Print a state node in the NFA for a std::regex"
>
> - def __init__ (self, typename, val):
> + def __init__(self, typename, val):
> self.val = val
> self.typename = typename
>
> - def to_string (self):
> + def to_string(self):
> opcode = str(self.val['_M_opcode'])
> if opcode:
> opcode = opcode[25:]
> next_id = self.val['_M_next']
>
> - variants = {'repeat':'alt', 'alternative':'alt',
> - 'subexpr_begin':'subexpr', 'subexpr_end':'subexpr',
> - 'line_begin_assertion':None, 'line_end_assertion':None,
> - 'word_boundary':'neg', 'subexpr_lookahead':'neg',
> - 'backref':'backref_index',
> - 'match':None, 'accept':None,
> - 'dummy':None, 'unknown':None
> - }
> + variants = {'repeat': 'alt', 'alternative': 'alt',
> + 'subexpr_begin': 'subexpr', 'subexpr_end': 'subexpr',
> + 'line_begin_assertion': None, 'line_end_assertion': None,
> + 'word_boundary': 'neg', 'subexpr_lookahead': 'neg',
> + 'backref': 'backref_index',
> + 'match': None, 'accept': None,
> + 'dummy': None, 'unknown': None
> + }
> v = variants[opcode]
>
> s = "opcode={}, next={}".format(opcode, next_id)
> @@ -1772,6 +1860,7 @@ class StdRegexStatePrinter:
> s = "{}, {}={}".format(s, v, self.val['_M_' + v])
> return "{%s}" % (s)
>
> +
> class StdSpanPrinter:
> "Print a std::span"
>
> @@ -1781,10 +1870,10 @@ class StdSpanPrinter:
> self.begin = begin
> self.size = size
>
> - def __iter__ (self):
> + def __iter__(self):
> return self
>
> - def __next__ (self):
> + def __next__(self):
> if self.count == self.size:
> raise StopIteration
>
> @@ -1809,6 +1898,7 @@ class StdSpanPrinter:
> def display_hint(self):
> return 'array'
>
> +
> class StdInitializerListPrinter:
> "Print a std::initializer_list"
>
> @@ -1826,6 +1916,7 @@ class StdInitializerListPrinter:
> def display_hint(self):
> return 'array'
>
> +
> class StdAtomicPrinter:
> "Print a std:atomic"
>
> @@ -1860,6 +1951,7 @@ class StdAtomicPrinter:
> val = self.val['_M_i']
> return '%s<%s> = { %s }' % (self.typename, str(self.value_type), val)
>
> +
> class StdFormatArgsPrinter:
> "Print a std::basic_format_args"
> # TODO: add printer for basic_format_arg<Context> and print out children.
> @@ -1886,6 +1978,7 @@ class StdFormatArgsPrinter:
> size = self.val['_M_unpacked_size']
> return "%s with %d arguments" % (typ, size)
>
> +
> def std_ratio_t_tuple(ratio_type):
> # TODO use reduced period i.e. duration::period
> period = self.val.type.template_argument(1)
> @@ -1893,6 +1986,7 @@ def std_ratio_t_tuple(ratio_type):
> den = period.template_argument(1)
> return (num, den)
>
> +
> class StdChronoDurationPrinter:
> "Print a std::chrono::duration"
>
> @@ -1950,18 +2044,18 @@ class StdChronoTimePointPrinter:
> return ('std::chrono::sys_time', 0)
> # XXX need to remove leap seconds from utc, gps, and tai
> if name == 'std::chrono::utc_clock':
> - return ('std::chrono::utc_time', None) # XXX
> + return ('std::chrono::utc_time', None) # XXX
> if name == 'std::chrono::gps_clock':
> - return ('std::chrono::gps_time', None) # XXX 315964809
> + return ('std::chrono::gps_time', None) # XXX 315964809
> if name == 'std::chrono::tai_clock':
> - return ('std::chrono::tai_time', None) # XXX -378691210
> + return ('std::chrono::tai_time', None) # XXX -378691210
> if name == 'std::filesystem::__file_clock':
> return ('std::chrono::file_time', 6437664000)
> if name == 'std::chrono::local_t':
> return ('std::chrono::local_time', 0)
> return ('{} time_point'.format(name), None)
>
> - def to_string(self, abbrev = False):
> + def to_string(self, abbrev=False):
> clock, offset = self._clock()
> d = self.val['__d']
> r = d['__r']
> @@ -1981,6 +2075,7 @@ class StdChronoTimePointPrinter:
> return s
> return '%s = { %s }' % (clock, s)
>
> +
> class StdChronoZonedTimePrinter:
> "Print a std::chrono::zoned_time"
>
> @@ -2002,6 +2097,7 @@ months = [None, 'January', 'February', 'March', 'April', 'May', 'June',
> weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
> 'Saturday', 'Sunday']
>
> +
> class StdChronoCalendarPrinter:
> "Print a std::chrono::day, std::chrono::month, std::chrono::year etc."
>
> @@ -2064,6 +2160,7 @@ class StdChronoCalendarPrinter:
> h = -h
> return '{:02}:{:02}:{:02}{}'.format(h, m, s, fract)
>
> +
> class StdChronoTimeZonePrinter:
> "Print a chrono::time_zone or chrono::time_zone_link"
>
> @@ -2077,6 +2174,7 @@ class StdChronoTimeZonePrinter:
> str += ' -> %s' % (self.val['_M_target'])
> return str
>
> +
> class StdChronoLeapSecondPrinter:
> "Print a chrono::leap_second"
>
> @@ -2089,6 +2187,7 @@ class StdChronoLeapSecondPrinter:
> neg = '+-'[date < 0]
> return '%s %d (%c)' % (self.typename, abs(date), neg)
>
> +
> class StdChronoTzdbPrinter:
> "Print a chrono::tzdb"
>
> @@ -2099,6 +2198,7 @@ class StdChronoTzdbPrinter:
> def to_string(self):
> return '%s %s' % (self.typename, self.val['version'])
>
> +
> class StdChronoTimeZoneRulePrinter:
> "Print a chrono::time_zone rule"
>
> @@ -2110,17 +2210,18 @@ class StdChronoTimeZoneRulePrinter:
> on = self.val['on']
> kind = on['kind']
> month = months[on['month']]
> - suffixes = {1:'st', 2:'nd', 3:'rd', 21:'st', 22:'nd', 23:'rd', 31:'st'}
> + suffixes = {1: 'st', 2: 'nd', 3: 'rd',
> + 21: 'st', 22: 'nd', 23: 'rd', 31: 'st'}
> day = on['day_of_month']
> ordinal_day = '{}{}'.format(day, suffixes.get(day, 'th'))
> - if kind == 0: # DayOfMonth
> - start = '{} {}{}'.format(month, ordinal_day)
> + if kind == 0: # DayOfMonth
> + start = '{} {}{}'.format(month, ordinal_day)
> else:
> weekday = weekdays[on['day_of_week']]
> - if kind == 1: # LastWeekDay
> + if kind == 1: # LastWeekDay
> start = 'last {} in {}'.format(weekday, month)
> else:
> - if kind == 2: # LessEq
> + if kind == 2: # LessEq
> direction = ('last', '<=')
> else:
> direction = ('first', '>=')
> @@ -2129,7 +2230,8 @@ class StdChronoTimeZoneRulePrinter:
> direction[1], month,
> ordinal_day)
> return 'time_zone rule {} from {} to {} starting on {}'.format(
> - self.val['name'], self.val['from'], self.val['to'], start)
> + self.val['name'], self.val['from'], self.val['to'], start)
> +
>
> class StdLocalePrinter:
> "Print a std::locale"
> @@ -2146,7 +2248,7 @@ class StdLocalePrinter:
> else:
> cats = gdb.parse_and_eval(self.typename + '::_S_categories')
> ncat = gdb.parse_and_eval(self.typename + '::_S_categories_size')
> - n = names[0].string();
> + n = names[0].string()
> cat = cats[0].string()
> name = '{}={}'.format(cat, n)
> cat_names = {cat: n}
> @@ -2171,7 +2273,7 @@ class StdLocalePrinter:
> name = n1
> other = n2
> if other is not None:
> - cat = next(c for c,n in cat_names.items() if n == other)
> + cat = next(c for c, n in cat_names.items() if n == other)
> mod = ' with "{}={}"'.format(cat, other)
> return 'std::locale = "{}"{}'.format(name, mod)
>
> @@ -2190,13 +2292,15 @@ class RxPrinter(object):
> return None
>
> if value.type.code == gdb.TYPE_CODE_REF:
> - if hasattr(gdb.Value,"referenced_value"):
> + if hasattr(gdb.Value, "referenced_value"):
> value = value.referenced_value()
>
> return self.function(self.name, value)
>
> # A pretty-printer that conforms to the "PrettyPrinter" protocol from
> # gdb.printing. It can also be used directly as an old-style printer.
> +
> +
> class Printer(object):
> def __init__(self, name):
> super(Printer, self).__init__()
> @@ -2210,7 +2314,8 @@ class Printer(object):
> # A small sanity check.
> # FIXME
> if not self.compiled_rx.match(name):
> - raise ValueError('libstdc++ programming error: "%s" does not match' % name)
> + raise ValueError(
> + 'libstdc++ programming error: "%s" does not match' % name)
> printer = RxPrinter(name, function)
> self.subprinters.append(printer)
> self.lookup[name] = printer
> @@ -2219,7 +2324,8 @@ class Printer(object):
> def add_version(self, base, name, function):
> self.add(base + name, function)
> if _versioned_namespace and not '__cxx11' in base:
> - vbase = re.sub('^(std|__gnu_cxx)::', r'\g<0>%s' % _versioned_namespace, base)
> + vbase = re.sub('^(std|__gnu_cxx)::', r'\g<0>%s' %
> + _versioned_namespace, base)
> self.add(vbase + name, function)
>
> # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
> @@ -2231,10 +2337,10 @@ class Printer(object):
> def get_basic_type(type):
> # If it points to a reference, get the reference.
> if type.code == gdb.TYPE_CODE_REF:
> - type = type.target ()
> + type = type.target()
>
> # Get the unqualified type, stripped of typedefs.
> - type = type.unqualified ().strip_typedefs ()
> + type = type.unqualified().strip_typedefs()
>
> return type.tag
>
> @@ -2252,7 +2358,7 @@ class Printer(object):
> basename = match.group(1)
>
> if val.type.code == gdb.TYPE_CODE_REF:
> - if hasattr(gdb.Value,"referenced_value"):
> + if hasattr(gdb.Value, "referenced_value"):
> val = val.referenced_value()
>
> if basename in self.lookup:
> @@ -2261,8 +2367,10 @@ class Printer(object):
> # Cannot find a pretty printer. Return None.
> return None
>
> +
> libstdcxx_printer = None
>
> +
> class TemplateTypePrinter(object):
> r"""
> A type printer for class templates with default template arguments.
> @@ -2345,7 +2453,7 @@ class TemplateTypePrinter(object):
> if type_obj.code == gdb.TYPE_CODE_ARRAY:
> type_str = self._recognize_subtype(type_obj.target())
> if str(type_obj.strip_typedefs()).endswith('[]'):
> - return type_str + '[]' # array of unknown bound
> + return type_str + '[]' # array of unknown bound
> return "%s[%d]" % (type_str, type_obj.range()[1] + 1)
> if type_obj.code == gdb.TYPE_CODE_REF:
> return self._recognize_subtype(type_obj.target()) + '&'
> @@ -2354,7 +2462,7 @@ class TemplateTypePrinter(object):
> return self._recognize_subtype(type_obj.target()) + '&&'
>
> type_str = gdb.types.apply_type_recognizers(
> - gdb.types.get_type_recognizers(), type_obj)
> + gdb.types.get_type_recognizers(), type_obj)
> if type_str:
> return type_str
> return str(type_obj)
> @@ -2363,6 +2471,7 @@ class TemplateTypePrinter(object):
> "Return a recognizer object for this type printer."
> return self._recognizer(self.name, self.defargs)
>
> +
> def add_one_template_type_printer(obj, name, defargs):
> r"""
> Add a type printer for a class template with default template arguments.
> @@ -2391,7 +2500,8 @@ def add_one_template_type_printer(obj, name, defargs):
> # Add second type printer for same type in versioned namespace:
> ns = 'std::' + _versioned_namespace
> # PR 86112 Cannot use dict comprehension here:
> - defargs = dict((n, d.replace('std::', ns)) for (n,d) in defargs.items())
> + defargs = dict((n, d.replace('std::', ns))
> + for (n, d) in defargs.items())
> printer = TemplateTypePrinter(ns+name, defargs)
> gdb.types.register_type_printer(obj, printer)
>
> @@ -2399,6 +2509,7 @@ def add_one_template_type_printer(obj, name, defargs):
> printer = TemplateTypePrinter('std::__debug::'+name, defargs)
> gdb.types.register_type_printer(obj, printer)
>
> +
> class FilteringTypePrinter(object):
> r"""
> A type printer that uses typedef names for common template specializations.
> @@ -2421,7 +2532,7 @@ class FilteringTypePrinter(object):
> more quickly, without needing to do GDB type lookups.
> """
>
> - def __init__(self, template, name, targ1 = None):
> + def __init__(self, template, name, targ1=None):
> self.template = template
> self.name = name
> self.targ1 = targ1
> @@ -2475,7 +2586,8 @@ class FilteringTypePrinter(object):
> "Return a recognizer object for this type printer."
> return self._recognizer(self.template, self.name, self.targ1)
>
> -def add_one_type_printer(obj, template, name, targ1 = None):
> +
> +def add_one_type_printer(obj, template, name, targ1=None):
> printer = FilteringTypePrinter('std::' + template, 'std::' + name, targ1)
> gdb.types.register_type_printer(obj, printer)
> if _versioned_namespace and not '__cxx11' in template:
> @@ -2483,6 +2595,7 @@ def add_one_type_printer(obj, template, name, targ1 = None):
> printer = FilteringTypePrinter(ns + template, ns + name, targ1)
> gdb.types.register_type_printer(obj, printer)
>
> +
> def register_type_printers(obj):
> global _use_type_printing
>
> @@ -2496,11 +2609,13 @@ def register_type_printers(obj):
> ('u16', 'char16_t'),
> ('u32', 'char32_t')):
> add_one_type_printer(obj, 'basic_string', ch[0] + 'string', ch[1])
> - add_one_type_printer(obj, '__cxx11::basic_string', ch[0] + 'string', ch[1])
> + add_one_type_printer(obj, '__cxx11::basic_string',
> + ch[0] + 'string', ch[1])
> # Typedefs for __cxx11::basic_string used to be in namespace __cxx11:
> add_one_type_printer(obj, '__cxx11::basic_string',
> '__cxx11::' + ch[0] + 'string', ch[1])
> - add_one_type_printer(obj, 'basic_string_view', ch[0] + 'string_view', ch[1])
> + add_one_type_printer(obj, 'basic_string_view',
> + ch[0] + 'string_view', ch[1])
>
> # Add type printers for typedefs std::istream, std::wistream etc.
> for ch in (('', 'char'), ('w', 'wchar_t')):
> @@ -2516,9 +2631,11 @@ def register_type_printers(obj):
> # Add type printers for typedefs regex, wregex, cmatch, wcmatch etc.
> for abi in ('', '__cxx11::'):
> for ch in (('', 'char'), ('w', 'wchar_t')):
> - add_one_type_printer(obj, abi + 'basic_regex', abi + ch[0] + 'regex', ch[1])
> + add_one_type_printer(obj, abi + 'basic_regex',
> + abi + ch[0] + 'regex', ch[1])
> for ch in ('c', 's', 'wc', 'ws'):
> - add_one_type_printer(obj, abi + 'match_results', abi + ch + 'match')
> + add_one_type_printer(
> + obj, abi + 'match_results', abi + ch + 'match')
> for x in ('sub_match', 'regex_iterator', 'regex_token_iterator'):
> add_one_type_printer(obj, abi + x, abi + ch + x)
>
> @@ -2554,40 +2671,43 @@ def register_type_printers(obj):
>
> # Do not show defaulted template arguments in class templates.
> add_one_template_type_printer(obj, 'unique_ptr',
> - { 1: 'std::default_delete<{0}>' })
> - add_one_template_type_printer(obj, 'deque', { 1: 'std::allocator<{0}>'})
> - add_one_template_type_printer(obj, 'forward_list', { 1: 'std::allocator<{0}>'})
> - add_one_template_type_printer(obj, 'list', { 1: 'std::allocator<{0}>'})
> - add_one_template_type_printer(obj, '__cxx11::list', { 1: 'std::allocator<{0}>'})
> - add_one_template_type_printer(obj, 'vector', { 1: 'std::allocator<{0}>'})
> + {1: 'std::default_delete<{0}>'})
> + add_one_template_type_printer(obj, 'deque', {1: 'std::allocator<{0}>'})
> + add_one_template_type_printer(
> + obj, 'forward_list', {1: 'std::allocator<{0}>'})
> + add_one_template_type_printer(obj, 'list', {1: 'std::allocator<{0}>'})
> + add_one_template_type_printer(
> + obj, '__cxx11::list', {1: 'std::allocator<{0}>'})
> + add_one_template_type_printer(obj, 'vector', {1: 'std::allocator<{0}>'})
> add_one_template_type_printer(obj, 'map',
> - { 2: 'std::less<{0}>',
> - 3: 'std::allocator<std::pair<{0} const, {1}>>' })
> + {2: 'std::less<{0}>',
> + 3: 'std::allocator<std::pair<{0} const, {1}>>'})
> add_one_template_type_printer(obj, 'multimap',
> - { 2: 'std::less<{0}>',
> - 3: 'std::allocator<std::pair<{0} const, {1}>>' })
> + {2: 'std::less<{0}>',
> + 3: 'std::allocator<std::pair<{0} const, {1}>>'})
> add_one_template_type_printer(obj, 'set',
> - { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
> + {1: 'std::less<{0}>', 2: 'std::allocator<{0}>'})
> add_one_template_type_printer(obj, 'multiset',
> - { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
> + {1: 'std::less<{0}>', 2: 'std::allocator<{0}>'})
> add_one_template_type_printer(obj, 'unordered_map',
> - { 2: 'std::hash<{0}>',
> - 3: 'std::equal_to<{0}>',
> - 4: 'std::allocator<std::pair<{0} const, {1}>>'})
> + {2: 'std::hash<{0}>',
> + 3: 'std::equal_to<{0}>',
> + 4: 'std::allocator<std::pair<{0} const, {1}>>'})
> add_one_template_type_printer(obj, 'unordered_multimap',
> - { 2: 'std::hash<{0}>',
> - 3: 'std::equal_to<{0}>',
> - 4: 'std::allocator<std::pair<{0} const, {1}>>'})
> + {2: 'std::hash<{0}>',
> + 3: 'std::equal_to<{0}>',
> + 4: 'std::allocator<std::pair<{0} const, {1}>>'})
> add_one_template_type_printer(obj, 'unordered_set',
> - { 1: 'std::hash<{0}>',
> - 2: 'std::equal_to<{0}>',
> - 3: 'std::allocator<{0}>'})
> + {1: 'std::hash<{0}>',
> + 2: 'std::equal_to<{0}>',
> + 3: 'std::allocator<{0}>'})
> add_one_template_type_printer(obj, 'unordered_multiset',
> - { 1: 'std::hash<{0}>',
> - 2: 'std::equal_to<{0}>',
> - 3: 'std::allocator<{0}>'})
> + {1: 'std::hash<{0}>',
> + 2: 'std::equal_to<{0}>',
> + 3: 'std::allocator<{0}>'})
>
> -def register_libstdcxx_printers (obj):
> +
> +def register_libstdcxx_printers(obj):
> "Register libstdc++ pretty-printers with objfile Obj."
>
> global _use_gdb_pp
> @@ -2602,7 +2722,8 @@ def register_libstdcxx_printers (obj):
>
> register_type_printers(obj)
>
> -def build_libstdcxx_dictionary ():
> +
> +def build_libstdcxx_dictionary():
> global libstdcxx_printer
>
> libstdcxx_printer = Printer("libstdc++-v6")
> @@ -2611,7 +2732,8 @@ def build_libstdcxx_dictionary ():
> # In order from:
> # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
> libstdcxx_printer.add_version('std::', 'basic_string', StdStringPrinter)
> - libstdcxx_printer.add_version('std::__cxx11::', 'basic_string', StdStringPrinter)
> + libstdcxx_printer.add_version(
> + 'std::__cxx11::', 'basic_string', StdStringPrinter)
> libstdcxx_printer.add_container('std::', 'bitset', StdBitsetPrinter)
> libstdcxx_printer.add_container('std::', 'deque', StdDequePrinter)
> libstdcxx_printer.add_container('std::', 'list', StdListPrinter)
> @@ -2662,8 +2784,10 @@ def build_libstdcxx_dictionary ():
> libstdcxx_printer.add_container('std::', 'forward_list',
> StdForwardListPrinter)
>
> - libstdcxx_printer.add_version('std::tr1::', 'shared_ptr', SharedPointerPrinter)
> - libstdcxx_printer.add_version('std::tr1::', 'weak_ptr', SharedPointerPrinter)
> + libstdcxx_printer.add_version(
> + 'std::tr1::', 'shared_ptr', SharedPointerPrinter)
> + libstdcxx_printer.add_version(
> + 'std::tr1::', 'weak_ptr', SharedPointerPrinter)
> libstdcxx_printer.add_version('std::tr1::', 'unordered_map',
> Tr1UnorderedMapPrinter)
> libstdcxx_printer.add_version('std::tr1::', 'unordered_set',
> @@ -2676,11 +2800,15 @@ def build_libstdcxx_dictionary ():
> libstdcxx_printer.add_version('std::', 'initializer_list',
> StdInitializerListPrinter)
> libstdcxx_printer.add_version('std::', 'atomic', StdAtomicPrinter)
> - libstdcxx_printer.add_version('std::', 'basic_stringbuf', StdStringBufPrinter)
> - libstdcxx_printer.add_version('std::__cxx11::', 'basic_stringbuf', StdStringBufPrinter)
> + libstdcxx_printer.add_version(
> + 'std::', 'basic_stringbuf', StdStringBufPrinter)
> + libstdcxx_printer.add_version(
> + 'std::__cxx11::', 'basic_stringbuf', StdStringBufPrinter)
> for sstream in ('istringstream', 'ostringstream', 'stringstream'):
> - libstdcxx_printer.add_version('std::', 'basic_' + sstream, StdStringStreamPrinter)
> - libstdcxx_printer.add_version('std::__cxx11::', 'basic_' + sstream, StdStringStreamPrinter)
> + libstdcxx_printer.add_version(
> + 'std::', 'basic_' + sstream, StdStringStreamPrinter)
> + libstdcxx_printer.add_version(
> + 'std::__cxx11::', 'basic_' + sstream, StdStringStreamPrinter)
>
> libstdcxx_printer.add_version('std::chrono::', 'duration',
> StdChronoDurationPrinter)
> @@ -2735,16 +2863,17 @@ def build_libstdcxx_dictionary ():
> '_Node_handle', StdNodeHandlePrinter)
>
> # C++20 components
> - libstdcxx_printer.add_version('std::', 'partial_ordering', StdCmpCatPrinter)
> + libstdcxx_printer.add_version(
> + 'std::', 'partial_ordering', StdCmpCatPrinter)
> libstdcxx_printer.add_version('std::', 'weak_ordering', StdCmpCatPrinter)
> libstdcxx_printer.add_version('std::', 'strong_ordering', StdCmpCatPrinter)
> libstdcxx_printer.add_version('std::', 'span', StdSpanPrinter)
> libstdcxx_printer.add_version('std::', 'basic_format_args',
> StdFormatArgsPrinter)
> - for c in ['day','month','year','weekday','weekday_indexed','weekday_last',
> - 'month_day','month_day_last','month_weekday','month_weekday_last',
> - 'year_month','year_month_day','year_month_day_last',
> - 'year_month_weekday','year_month_weekday_last', 'hh_mm_ss']:
> + for c in ['day', 'month', 'year', 'weekday', 'weekday_indexed', 'weekday_last',
> + 'month_day', 'month_day_last', 'month_weekday', 'month_weekday_last',
> + 'year_month', 'year_month_day', 'year_month_day_last',
> + 'year_month_weekday', 'year_month_weekday_last', 'hh_mm_ss']:
> libstdcxx_printer.add_version('std::chrono::', c,
> StdChronoCalendarPrinter)
> libstdcxx_printer.add_version('std::chrono::', 'time_zone',
> @@ -2755,8 +2884,9 @@ def build_libstdcxx_dictionary ():
> StdChronoZonedTimePrinter)
> libstdcxx_printer.add_version('std::chrono::', 'leap_second',
> StdChronoLeapSecondPrinter)
> - libstdcxx_printer.add_version('std::chrono::', 'tzdb', StdChronoTzdbPrinter)
> - #libstdcxx_printer.add_version('std::chrono::(anonymous namespace)', 'Rule',
> + libstdcxx_printer.add_version(
> + 'std::chrono::', 'tzdb', StdChronoTzdbPrinter)
> + # libstdcxx_printer.add_version('std::chrono::(anonymous namespace)', 'Rule',
> # StdChronoTimeZoneRulePrinter)
>
> # Extensions.
> @@ -2780,11 +2910,11 @@ def build_libstdcxx_dictionary ():
> libstdcxx_printer.add_version('__gnu_cxx::', '__normal_iterator',
> StdVectorIteratorPrinter)
> libstdcxx_printer.add_container('std::', '_Bit_iterator',
> - StdBitIteratorPrinter)
> + StdBitIteratorPrinter)
> libstdcxx_printer.add_container('std::', '_Bit_const_iterator',
> - StdBitIteratorPrinter)
> + StdBitIteratorPrinter)
> libstdcxx_printer.add_container('std::', '_Bit_reference',
> - StdBitReferencePrinter)
> + StdBitReferencePrinter)
> libstdcxx_printer.add_version('__gnu_cxx::', '_Slist_iterator',
> StdSlistIteratorPrinter)
> libstdcxx_printer.add_container('std::', '_Fwd_list_iterator',
> @@ -2797,4 +2927,5 @@ def build_libstdcxx_dictionary ():
> libstdcxx_printer.add('__gnu_debug::_Safe_iterator',
> StdDebugIteratorPrinter)
>
> -build_libstdcxx_dictionary ()
> +
> +build_libstdcxx_dictionary()
> diff --git a/libstdc++-v3/python/libstdcxx/v6/xmethods.py b/libstdc++-v3/python/libstdcxx/v6/xmethods.py
> index 18a165f425e..025b1b86ed0 100644
> --- a/libstdc++-v3/python/libstdcxx/v6/xmethods.py
> +++ b/libstdc++-v3/python/libstdcxx/v6/xmethods.py
> @@ -21,12 +21,15 @@ import re
>
> matcher_name_prefix = 'libstdc++::'
>
> +
> def get_bool_type():
> return gdb.lookup_type('bool')
>
> +
> def get_std_size_type():
> return gdb.lookup_type('std::size_t')
>
> +
> class LibStdCxxXMethod(gdb.xmethod.XMethod):
> def __init__(self, name, worker_class):
> gdb.xmethod.XMethod.__init__(self, name)
> @@ -34,6 +37,7 @@ class LibStdCxxXMethod(gdb.xmethod.XMethod):
>
> # Xmethods for std::array
>
> +
> class ArrayWorkerBase(gdb.xmethod.XMethodWorker):
> def __init__(self, val_type, size):
> self._val_type = val_type
> @@ -43,6 +47,7 @@ class ArrayWorkerBase(gdb.xmethod.XMethodWorker):
> nullptr = gdb.parse_and_eval('(void *) 0')
> return nullptr.cast(self._val_type.pointer()).dereference()
>
> +
> class ArraySizeWorker(ArrayWorkerBase):
> def __init__(self, val_type, size):
> ArrayWorkerBase.__init__(self, val_type, size)
> @@ -56,6 +61,7 @@ class ArraySizeWorker(ArrayWorkerBase):
> def __call__(self, obj):
> return self._size
>
> +
> class ArrayEmptyWorker(ArrayWorkerBase):
> def __init__(self, val_type, size):
> ArrayWorkerBase.__init__(self, val_type, size)
> @@ -69,6 +75,7 @@ class ArrayEmptyWorker(ArrayWorkerBase):
> def __call__(self, obj):
> return (int(self._size) == 0)
>
> +
> class ArrayFrontWorker(ArrayWorkerBase):
> def __init__(self, val_type, size):
> ArrayWorkerBase.__init__(self, val_type, size)
> @@ -85,6 +92,7 @@ class ArrayFrontWorker(ArrayWorkerBase):
> else:
> return self.null_value()
>
> +
> class ArrayBackWorker(ArrayWorkerBase):
> def __init__(self, val_type, size):
> ArrayWorkerBase.__init__(self, val_type, size)
> @@ -101,6 +109,7 @@ class ArrayBackWorker(ArrayWorkerBase):
> else:
> return self.null_value()
>
> +
> class ArrayAtWorker(ArrayWorkerBase):
> def __init__(self, val_type, size):
> ArrayWorkerBase.__init__(self, val_type, size)
> @@ -117,6 +126,7 @@ class ArrayAtWorker(ArrayWorkerBase):
> ((int(index), self._size)))
> return obj['_M_elems'][index]
>
> +
> class ArraySubscriptWorker(ArrayWorkerBase):
> def __init__(self, val_type, size):
> ArrayWorkerBase.__init__(self, val_type, size)
> @@ -133,6 +143,7 @@ class ArraySubscriptWorker(ArrayWorkerBase):
> else:
> return self.null_value()
>
> +
> class ArrayMethodsMatcher(gdb.xmethod.XMethodMatcher):
> def __init__(self):
> gdb.xmethod.XMethodMatcher.__init__(self,
> @@ -162,6 +173,7 @@ class ArrayMethodsMatcher(gdb.xmethod.XMethodMatcher):
>
> # Xmethods for std::deque
>
> +
> class DequeWorkerBase(gdb.xmethod.XMethodWorker):
> def __init__(self, val_type):
> self._val_type = val_type
> @@ -179,6 +191,7 @@ class DequeWorkerBase(gdb.xmethod.XMethodWorker):
> index_node = first_node + int(idx) // self._bufsize
> return index_node[0][idx % self._bufsize]
>
> +
> class DequeEmptyWorker(DequeWorkerBase):
> def get_arg_types(self):
> return None
> @@ -190,6 +203,7 @@ class DequeEmptyWorker(DequeWorkerBase):
> return (obj['_M_impl']['_M_start']['_M_cur'] ==
> obj['_M_impl']['_M_finish']['_M_cur'])
>
> +
> class DequeSizeWorker(DequeWorkerBase):
> def get_arg_types(self):
> return None
> @@ -200,6 +214,7 @@ class DequeSizeWorker(DequeWorkerBase):
> def __call__(self, obj):
> return self.size(obj)
>
> +
> class DequeFrontWorker(DequeWorkerBase):
> def get_arg_types(self):
> return None
> @@ -210,6 +225,7 @@ class DequeFrontWorker(DequeWorkerBase):
> def __call__(self, obj):
> return obj['_M_impl']['_M_start']['_M_cur'][0]
>
> +
> class DequeBackWorker(DequeWorkerBase):
> def get_arg_types(self):
> return None
> @@ -219,12 +235,13 @@ class DequeBackWorker(DequeWorkerBase):
>
> def __call__(self, obj):
> if (obj['_M_impl']['_M_finish']['_M_cur'] ==
> - obj['_M_impl']['_M_finish']['_M_first']):
> + obj['_M_impl']['_M_finish']['_M_first']):
> prev_node = obj['_M_impl']['_M_finish']['_M_node'] - 1
> return prev_node[0][self._bufsize - 1]
> else:
> return obj['_M_impl']['_M_finish']['_M_cur'][-1]
>
> +
> class DequeSubscriptWorker(DequeWorkerBase):
> def get_arg_types(self):
> return get_std_size_type()
> @@ -235,6 +252,7 @@ class DequeSubscriptWorker(DequeWorkerBase):
> def __call__(self, obj, subscript):
> return self.index(obj, subscript)
>
> +
> class DequeAtWorker(DequeWorkerBase):
> def get_arg_types(self):
> return get_std_size_type()
> @@ -248,7 +266,8 @@ class DequeAtWorker(DequeWorkerBase):
> raise IndexError('Deque index "%d" should not be >= %d.' %
> (int(index), deque_size))
> else:
> - return self.index(obj, index)
> + return self.index(obj, index)
> +
>
> class DequeMethodsMatcher(gdb.xmethod.XMethodMatcher):
> def __init__(self):
> @@ -274,6 +293,7 @@ class DequeMethodsMatcher(gdb.xmethod.XMethodMatcher):
>
> # Xmethods for std::forward_list
>
> +
> class ForwardListWorkerBase(gdb.xmethod.XMethodMatcher):
> def __init__(self, val_type, node_type):
> self._val_type = val_type
> @@ -282,6 +302,7 @@ class ForwardListWorkerBase(gdb.xmethod.XMethodMatcher):
> def get_arg_types(self):
> return None
>
> +
> class ForwardListEmptyWorker(ForwardListWorkerBase):
> def get_result_type(self, obj):
> return get_bool_type()
> @@ -289,6 +310,7 @@ class ForwardListEmptyWorker(ForwardListWorkerBase):
> def __call__(self, obj):
> return obj['_M_impl']['_M_head']['_M_next'] == 0
>
> +
> class ForwardListFrontWorker(ForwardListWorkerBase):
> def get_result_type(self, obj):
> return self._val_type
> @@ -298,6 +320,7 @@ class ForwardListFrontWorker(ForwardListWorkerBase):
> val_address = node['_M_storage']['_M_storage'].address
> return val_address.cast(self._val_type.pointer()).dereference()
>
> +
> class ForwardListMethodsMatcher(gdb.xmethod.XMethodMatcher):
> def __init__(self):
> matcher_name = matcher_name_prefix + 'forward_list'
> @@ -320,6 +343,7 @@ class ForwardListMethodsMatcher(gdb.xmethod.XMethodMatcher):
>
> # Xmethods for std::list
>
> +
> class ListWorkerBase(gdb.xmethod.XMethodWorker):
> def __init__(self, val_type, node_type):
> self._val_type = val_type
> @@ -337,6 +361,7 @@ class ListWorkerBase(gdb.xmethod.XMethodWorker):
> addr = node['_M_storage'].address
> return addr.cast(self._val_type.pointer()).dereference()
>
> +
> class ListEmptyWorker(ListWorkerBase):
> def get_result_type(self, obj):
> return get_bool_type()
> @@ -348,6 +373,7 @@ class ListEmptyWorker(ListWorkerBase):
> else:
> return False
>
> +
> class ListSizeWorker(ListWorkerBase):
> def get_result_type(self, obj):
> return get_std_size_type()
> @@ -361,6 +387,7 @@ class ListSizeWorker(ListWorkerBase):
> size += 1
> return size
>
> +
> class ListFrontWorker(ListWorkerBase):
> def get_result_type(self, obj):
> return self._val_type
> @@ -369,6 +396,7 @@ class ListFrontWorker(ListWorkerBase):
> node = obj['_M_impl']['_M_node']['_M_next'].cast(self._node_type)
> return self.get_value_from_node(node)
>
> +
> class ListBackWorker(ListWorkerBase):
> def get_result_type(self, obj):
> return self._val_type
> @@ -377,6 +405,7 @@ class ListBackWorker(ListWorkerBase):
> prev_node = obj['_M_impl']['_M_node']['_M_prev'].cast(self._node_type)
> return self.get_value_from_node(prev_node)
>
> +
> class ListMethodsMatcher(gdb.xmethod.XMethodMatcher):
> def __init__(self):
> gdb.xmethod.XMethodMatcher.__init__(self,
> @@ -401,6 +430,7 @@ class ListMethodsMatcher(gdb.xmethod.XMethodMatcher):
>
> # Xmethods for std::vector
>
> +
> class VectorWorkerBase(gdb.xmethod.XMethodWorker):
> def __init__(self, val_type):
> self._val_type = val_type
> @@ -425,6 +455,7 @@ class VectorWorkerBase(gdb.xmethod.XMethodWorker):
> else:
> return obj['_M_impl']['_M_start'][index]
>
> +
> class VectorEmptyWorker(VectorWorkerBase):
> def get_arg_types(self):
> return None
> @@ -435,6 +466,7 @@ class VectorEmptyWorker(VectorWorkerBase):
> def __call__(self, obj):
> return int(self.size(obj)) == 0
>
> +
> class VectorSizeWorker(VectorWorkerBase):
> def get_arg_types(self):
> return None
> @@ -445,6 +477,7 @@ class VectorSizeWorker(VectorWorkerBase):
> def __call__(self, obj):
> return self.size(obj)
>
> +
> class VectorFrontWorker(VectorWorkerBase):
> def get_arg_types(self):
> return None
> @@ -455,6 +488,7 @@ class VectorFrontWorker(VectorWorkerBase):
> def __call__(self, obj):
> return self.get(obj, 0)
>
> +
> class VectorBackWorker(VectorWorkerBase):
> def get_arg_types(self):
> return None
> @@ -465,6 +499,7 @@ class VectorBackWorker(VectorWorkerBase):
> def __call__(self, obj):
> return self.get(obj, int(self.size(obj)) - 1)
>
> +
> class VectorAtWorker(VectorWorkerBase):
> def get_arg_types(self):
> return get_std_size_type()
> @@ -479,6 +514,7 @@ class VectorAtWorker(VectorWorkerBase):
> ((int(index), size)))
> return self.get(obj, int(index))
>
> +
> class VectorSubscriptWorker(VectorWorkerBase):
> def get_arg_types(self):
> return get_std_size_type()
> @@ -489,6 +525,7 @@ class VectorSubscriptWorker(VectorWorkerBase):
> def __call__(self, obj, subscript):
> return self.get(obj, int(subscript))
>
> +
> class VectorMethodsMatcher(gdb.xmethod.XMethodMatcher):
> def __init__(self):
> gdb.xmethod.XMethodMatcher.__init__(self,
> @@ -514,6 +551,7 @@ class VectorMethodsMatcher(gdb.xmethod.XMethodMatcher):
>
> # Xmethods for associative containers
>
> +
> class AssociativeContainerWorkerBase(gdb.xmethod.XMethodWorker):
> def __init__(self, unordered):
> self._unordered = unordered
> @@ -527,6 +565,7 @@ class AssociativeContainerWorkerBase(gdb.xmethod.XMethodWorker):
> def get_arg_types(self):
> return None
>
> +
> class AssociativeContainerEmptyWorker(AssociativeContainerWorkerBase):
> def get_result_type(self, obj):
> return get_bool_type()
> @@ -534,6 +573,7 @@ class AssociativeContainerEmptyWorker(AssociativeContainerWorkerBase):
> def __call__(self, obj):
> return int(self.node_count(obj)) == 0
>
> +
> class AssociativeContainerSizeWorker(AssociativeContainerWorkerBase):
> def get_result_type(self, obj):
> return get_std_size_type()
> @@ -541,6 +581,7 @@ class AssociativeContainerSizeWorker(AssociativeContainerWorkerBase):
> def __call__(self, obj):
> return self.node_count(obj)
>
> +
> class AssociativeContainerMethodsMatcher(gdb.xmethod.XMethodMatcher):
> def __init__(self, name):
> gdb.xmethod.XMethodMatcher.__init__(self,
> @@ -564,6 +605,7 @@ class AssociativeContainerMethodsMatcher(gdb.xmethod.XMethodMatcher):
>
> # Xmethods for std::unique_ptr
>
> +
> class UniquePtrGetWorker(gdb.xmethod.XMethodWorker):
> "Implements std::unique_ptr<T>::get() and std::unique_ptr<T>::operator->()"
>
> @@ -593,7 +635,7 @@ class UniquePtrGetWorker(gdb.xmethod.XMethodWorker):
> tuple_member = obj['_M_t']
> else:
> return None
> - tuple_impl_type = tuple_member.type.fields()[0].type # _Tuple_impl
> + tuple_impl_type = tuple_member.type.fields()[0].type # _Tuple_impl
> tuple_head_type = tuple_impl_type.fields()[1].type # _Head_base
> head_field = tuple_head_type.fields()[0]
> if head_field.name == '_M_head_impl':
> @@ -603,6 +645,7 @@ class UniquePtrGetWorker(gdb.xmethod.XMethodWorker):
> else:
> return None
>
> +
> class UniquePtrDerefWorker(UniquePtrGetWorker):
> "Implements std::unique_ptr<T>::operator*()"
>
> @@ -619,6 +662,7 @@ class UniquePtrDerefWorker(UniquePtrGetWorker):
> def __call__(self, obj):
> return UniquePtrGetWorker.__call__(self, obj).dereference()
>
> +
> class UniquePtrSubscriptWorker(UniquePtrGetWorker):
> "Implements std::unique_ptr<T>::operator[](size_t)"
>
> @@ -638,6 +682,7 @@ class UniquePtrSubscriptWorker(UniquePtrGetWorker):
> def __call__(self, obj, index):
> return UniquePtrGetWorker.__call__(self, obj)[index]
>
> +
> class UniquePtrMethodsMatcher(gdb.xmethod.XMethodMatcher):
> def __init__(self):
> gdb.xmethod.XMethodMatcher.__init__(self,
> @@ -663,6 +708,7 @@ class UniquePtrMethodsMatcher(gdb.xmethod.XMethodMatcher):
>
> # Xmethods for std::shared_ptr
>
> +
> class SharedPtrGetWorker(gdb.xmethod.XMethodWorker):
> "Implements std::shared_ptr<T>::get() and std::shared_ptr<T>::operator->()"
>
> @@ -686,6 +732,7 @@ class SharedPtrGetWorker(gdb.xmethod.XMethodWorker):
> def __call__(self, obj):
> return obj['_M_ptr']
>
> +
> class SharedPtrDerefWorker(SharedPtrGetWorker):
> "Implements std::shared_ptr<T>::operator*()"
>
> @@ -702,6 +749,7 @@ class SharedPtrDerefWorker(SharedPtrGetWorker):
> def __call__(self, obj):
> return SharedPtrGetWorker.__call__(self, obj).dereference()
>
> +
> class SharedPtrSubscriptWorker(SharedPtrGetWorker):
> "Implements std::shared_ptr<T>::operator[](size_t)"
>
> @@ -726,6 +774,7 @@ class SharedPtrSubscriptWorker(SharedPtrGetWorker):
> (self._elem_type, int(index), int(m.group(1))))
> return SharedPtrGetWorker.__call__(self, obj)[index]
>
> +
> class SharedPtrUseCountWorker(gdb.xmethod.XMethodWorker):
> "Implements std::shared_ptr<T>::use_count()"
>
> @@ -745,6 +794,7 @@ class SharedPtrUseCountWorker(gdb.xmethod.XMethodWorker):
> refcounts = obj['_M_refcount']['_M_pi']
> return refcounts['_M_use_count'] if refcounts else 0
>
> +
> class SharedPtrUniqueWorker(SharedPtrUseCountWorker):
> "Implements std::shared_ptr<T>::unique()"
>
> @@ -757,6 +807,7 @@ class SharedPtrUniqueWorker(SharedPtrUseCountWorker):
> def __call__(self, obj):
> return SharedPtrUseCountWorker.__call__(self, obj) == 1
>
> +
> class SharedPtrMethodsMatcher(gdb.xmethod.XMethodMatcher):
> def __init__(self):
> gdb.xmethod.XMethodMatcher.__init__(self,
> @@ -782,6 +833,7 @@ class SharedPtrMethodsMatcher(gdb.xmethod.XMethodMatcher):
> return worker
> return None
>
> +
> def register_libstdcxx_xmethods(locus):
> gdb.xmethod.register_xmethod_matcher(locus, ArrayMethodsMatcher())
> gdb.xmethod.register_xmethod_matcher(locus, ForwardListMethodsMatcher())
> --
> 2.41.0
>
@@ -18,10 +18,12 @@
import gdb
import itertools
import re
-import sys, os, errno
+import sys
+import os
+import errno
import datetime
-### Python 2 + Python 3 compatibility code
+# Python 2 + Python 3 compatibility code
# Resources about compatibility:
#
@@ -38,7 +40,7 @@ import datetime
# <https://sourceware.org/bugzilla/show_bug.cgi?id=17138>
if sys.version_info[0] > 2:
- ### Python 3 stuff
+ # Python 3 stuff
Iterator = object
# Python 3 folds these into the normal functions.
imap = map
@@ -47,7 +49,7 @@ if sys.version_info[0] > 2:
long = int
_utc_timezone = datetime.timezone.utc
else:
- ### Python 2 stuff
+ # Python 2 stuff
class Iterator:
"""Compatibility mixin for iterators
@@ -98,6 +100,8 @@ except ImportError:
# Starting with the type ORIG, search for the member type NAME. This
# handles searching upward through superclasses. This is needed to
# work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
+
+
def find_type(orig, name):
typ = orig.strip_typedefs()
while True:
@@ -116,8 +120,10 @@ def find_type(orig, name):
else:
raise ValueError("Cannot find type %s::%s" % (str(orig), name))
+
_versioned_namespace = '__8::'
+
def lookup_templ_spec(templ, *args):
"""
Lookup template specialization templ<args...>
@@ -139,6 +145,8 @@ def lookup_templ_spec(templ, *args):
# Use this to find container node types instead of find_type,
# see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91997 for details.
+
+
def lookup_node_type(nodename, containertype):
"""
Lookup specialization of template NODENAME corresponding to CONTAINERTYPE.
@@ -168,6 +176,7 @@ def lookup_node_type(nodename, containertype):
pass
return None
+
def is_member_of_namespace(typ, *namespaces):
"""
Test whether a type is a member of one of the specified namespaces.
@@ -181,6 +190,7 @@ def is_member_of_namespace(typ, *namespaces):
return True
return False
+
def is_specialization_of(x, template_name):
"""
Test whether a type is a specialization of the named class template.
@@ -195,12 +205,14 @@ def is_specialization_of(x, template_name):
return re.match('^std::(%s)?%s<.*>$' % (_versioned_namespace, template_name), x) is not None
return re.match('^std::%s<.*>$' % template_name, x) is not None
+
def strip_versioned_namespace(typename):
global _versioned_namespace
if _versioned_namespace:
return typename.replace(_versioned_namespace, '')
return typename
+
def strip_inline_namespaces(type_str):
"Remove known inline namespaces from the canonical name of a type."
type_str = strip_versioned_namespace(type_str)
@@ -212,6 +224,7 @@ def strip_inline_namespaces(type_str):
type_str = type_str.replace(fs_ns+'v1::', fs_ns)
return type_str
+
def get_template_arg_list(type_obj):
"Return a type's template arguments as a list"
n = 0
@@ -223,6 +236,7 @@ def get_template_arg_list(type_obj):
return template_args
n += 1
+
class SmartPtrIterator(Iterator):
"An iterator for smart pointer types with a single 'child' value"
@@ -238,28 +252,29 @@ class SmartPtrIterator(Iterator):
self.val, val = None, self.val
return ('get()', val)
+
class SharedPointerPrinter:
"Print a shared_ptr, weak_ptr, atomic<shared_ptr>, or atomic<weak_ptr>"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.typename = strip_versioned_namespace(typename)
self.val = val
self.pointer = val['_M_ptr']
- def children (self):
+ def children(self):
return SmartPtrIterator(self.pointer)
# Return the _Sp_counted_base<>* that holds the refcounts.
- def _get_refcounts (self):
+ def _get_refcounts(self):
if self.typename == 'std::atomic':
# A tagged pointer is stored as uintptr_t.
ptr_val = self.val['_M_refcount']['_M_val']['_M_i']
- ptr_val = ptr_val - (ptr_val % 2) # clear lock bit
+ ptr_val = ptr_val - (ptr_val % 2) # clear lock bit
ptr_type = find_type(self.val['_M_refcount'].type, 'pointer')
return ptr_val.cast(ptr_type)
return self.val['_M_refcount']['_M_pi']
- def to_string (self):
+ def to_string(self):
state = 'empty'
refcounts = self._get_refcounts()
targ = self.val.type.template_argument(0)
@@ -271,19 +286,23 @@ class SharedPointerPrinter:
if usecount == 0:
state = 'expired, weak count %d' % weakcount
else:
- state = 'use count %d, weak count %d' % (usecount, weakcount - 1)
+ state = 'use count %d, weak count %d' % (
+ usecount, weakcount - 1)
return '%s<%s> (%s)' % (self.typename, targ, state)
+
def _tuple_impl_get(val):
"Return the tuple element stored in a _Tuple_impl<N, T> base class."
bases = val.type.fields()
if not bases[-1].is_base_class:
- raise ValueError("Unsupported implementation for std::tuple: %s" % str(val.type))
+ raise ValueError(
+ "Unsupported implementation for std::tuple: %s" % str(val.type))
# Get the _Head_base<N, T> base class:
head_base = val.cast(bases[-1].type)
fields = head_base.type.fields()
if len(fields) == 0:
- raise ValueError("Unsupported implementation for std::tuple: %s" % str(val.type))
+ raise ValueError(
+ "Unsupported implementation for std::tuple: %s" % str(val.type))
if fields[0].name == '_M_head_impl':
# The tuple element is the _Head_base::_M_head_impl data member.
return head_base['_M_head_impl']
@@ -292,7 +311,9 @@ def _tuple_impl_get(val):
# Cast to that empty base class.
return head_base.cast(fields[0].type)
else:
- raise ValueError("Unsupported implementation for std::tuple: %s" % str(val.type))
+ raise ValueError(
+ "Unsupported implementation for std::tuple: %s" % str(val.type))
+
def tuple_get(n, val):
"Return the result of std::get<n>(val) on a std::tuple"
@@ -307,6 +328,7 @@ def tuple_get(n, val):
n -= 1
return _tuple_impl_get(node)
+
def unique_ptr_get(val):
"Return the result of val.get() on a std::unique_ptr"
# std::unique_ptr<T, D> contains a std::tuple<D::pointer, D>,
@@ -315,30 +337,34 @@ def unique_ptr_get(val):
impl_type = val.type.fields()[0].type.strip_typedefs()
# Check for new implementations first:
if is_specialization_of(impl_type, '__uniq_ptr_data') \
- or is_specialization_of(impl_type, '__uniq_ptr_impl'):
+ or is_specialization_of(impl_type, '__uniq_ptr_impl'):
tuple_member = val['_M_t']['_M_t']
elif is_specialization_of(impl_type, 'tuple'):
tuple_member = val['_M_t']
else:
- raise ValueError("Unsupported implementation for unique_ptr: %s" % str(impl_type))
+ raise ValueError(
+ "Unsupported implementation for unique_ptr: %s" % str(impl_type))
return tuple_get(0, tuple_member)
+
class UniquePointerPrinter:
"Print a unique_ptr"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.val = val
- def children (self):
+ def children(self):
return SmartPtrIterator(unique_ptr_get(self.val))
- def to_string (self):
+ def to_string(self):
return ('std::unique_ptr<%s>' % (str(self.val.type.template_argument(0))))
+
def get_value_from_aligned_membuf(buf, valtype):
"""Returns the value held in a __gnu_cxx::__aligned_membuf."""
return buf['_M_storage'].address.cast(valtype.pointer()).dereference()
+
def get_value_from_list_node(node):
"""Returns the value held in an _List_node<_Val>"""
try:
@@ -354,6 +380,7 @@ def get_value_from_list_node(node):
pass
raise ValueError("Unsupported implementation for %s" % str(node.type))
+
class StdListPrinter:
"Print a std::list"
@@ -391,6 +418,7 @@ class StdListPrinter:
return 'empty %s' % (self.typename)
return '%s' % (self.typename)
+
class NodeIteratorPrinter:
def __init__(self, typename, val, contname, nodename):
self.val = val
@@ -404,12 +432,14 @@ class NodeIteratorPrinter:
node = self.val['_M_node'].cast(self.nodetype.pointer()).dereference()
return str(get_value_from_list_node(node))
+
class StdListIteratorPrinter(NodeIteratorPrinter):
"Print std::list::iterator"
def __init__(self, typename, val):
NodeIteratorPrinter.__init__(self, typename, val, 'list', '_List_node')
+
class StdFwdListIteratorPrinter(NodeIteratorPrinter):
"Print std::forward_list::iterator"
@@ -417,6 +447,7 @@ class StdFwdListIteratorPrinter(NodeIteratorPrinter):
NodeIteratorPrinter.__init__(self, typename, val, 'forward_list',
'_Fwd_list_node')
+
class StdSlistPrinter:
"Print a __gnu_cxx::slist"
@@ -450,6 +481,7 @@ class StdSlistPrinter:
return 'empty __gnu_cxx::slist'
return '__gnu_cxx::slist'
+
class StdSlistIteratorPrinter:
"Print __gnu_cxx::slist::iterator"
@@ -459,20 +491,22 @@ class StdSlistIteratorPrinter:
def to_string(self):
if not self.val['_M_node']:
return 'non-dereferenceable iterator for __gnu_cxx::slist'
- nodetype = lookup_node_type('__gnu_cxx::_Slist_node', self.val.type).pointer()
+ nodetype = lookup_node_type(
+ '__gnu_cxx::_Slist_node', self.val.type).pointer()
return str(self.val['_M_node'].cast(nodetype).dereference()['_M_data'])
+
class StdVectorPrinter:
"Print a std::vector"
class _iterator(Iterator):
- def __init__ (self, start, finish, bitvec):
+ def __init__(self, start, finish, bitvec):
self.bitvec = bitvec
if bitvec:
- self.item = start['_M_p']
- self.so = 0
+ self.item = start['_M_p']
+ self.so = 0
self.finish = finish['_M_p']
- self.fo = finish['_M_offset']
+ self.fo = finish['_M_offset']
itype = self.item.dereference().type
self.isize = 8 * itype.sizeof
else:
@@ -519,20 +553,21 @@ class StdVectorPrinter:
if self.is_bool:
start = self.val['_M_impl']['_M_start']['_M_p']
finish = self.val['_M_impl']['_M_finish']['_M_p']
- fo = self.val['_M_impl']['_M_finish']['_M_offset']
+ fo = self.val['_M_impl']['_M_finish']['_M_offset']
itype = start.dereference().type
bl = 8 * itype.sizeof
- length = bl * (finish - start) + fo
+ length = bl * (finish - start) + fo
capacity = bl * (end - start)
return ('%s<bool> of length %d, capacity %d'
- % (self.typename, int (length), int (capacity)))
+ % (self.typename, int(length), int(capacity)))
else:
return ('%s of length %d, capacity %d'
- % (self.typename, int (finish - start), int (end - start)))
+ % (self.typename, int(finish - start), int(end - start)))
def display_hint(self):
return 'array'
+
class StdVectorIteratorPrinter:
"Print std::vector::iterator"
@@ -544,6 +579,7 @@ class StdVectorIteratorPrinter:
return 'non-dereferenceable iterator for std::vector'
return str(self.val['_M_current'].dereference())
+
class StdBitIteratorPrinter:
"Print std::vector<bool>'s _Bit_iterator and _Bit_const_iterator"
@@ -555,6 +591,7 @@ class StdBitIteratorPrinter:
return 'non-dereferenceable iterator for std::vector<bool>'
return bool(self.val['_M_p'].dereference() & (1 << self.val['_M_offset']))
+
class StdBitReferencePrinter:
"Print std::vector<bool>::reference"
@@ -566,51 +603,54 @@ class StdBitReferencePrinter:
return 'invalid std::vector<bool>::reference'
return bool(self.val['_M_p'].dereference() & (self.val['_M_mask']))
+
class StdTuplePrinter:
"Print a std::tuple"
class _iterator(Iterator):
@staticmethod
- def _is_nonempty_tuple (nodes):
- if len (nodes) == 2:
- if is_specialization_of (nodes[1].type, '__tuple_base'):
+ def _is_nonempty_tuple(nodes):
+ if len(nodes) == 2:
+ if is_specialization_of(nodes[1].type, '__tuple_base'):
return True
- elif len (nodes) == 1:
+ elif len(nodes) == 1:
return True
- elif len (nodes) == 0:
+ elif len(nodes) == 0:
return False
- raise ValueError("Top of tuple tree does not consist of a single node.")
+ raise ValueError(
+ "Top of tuple tree does not consist of a single node.")
- def __init__ (self, head):
+ def __init__(self, head):
self.head = head
# Set the base class as the initial head of the
# tuple.
- nodes = self.head.type.fields ()
- if self._is_nonempty_tuple (nodes):
+ nodes = self.head.type.fields()
+ if self._is_nonempty_tuple(nodes):
# Set the actual head to the first pair.
- self.head = self.head.cast (nodes[0].type)
+ self.head = self.head.cast(nodes[0].type)
self.count = 0
- def __iter__ (self):
+ def __iter__(self):
return self
- def __next__ (self):
+ def __next__(self):
# Check for further recursions in the inheritance tree.
# For a GCC 5+ tuple self.head is None after visiting all nodes:
if not self.head:
raise StopIteration
- nodes = self.head.type.fields ()
+ nodes = self.head.type.fields()
# For a GCC 4.x tuple there is a final node with no fields:
- if len (nodes) == 0:
+ if len(nodes) == 0:
raise StopIteration
# Check that this iteration has an expected structure.
- if len (nodes) > 2:
- raise ValueError("Cannot parse more than 2 nodes in a tuple tree.")
+ if len(nodes) > 2:
+ raise ValueError(
+ "Cannot parse more than 2 nodes in a tuple tree.")
- if len (nodes) == 1:
+ if len(nodes) == 1:
# This is the last node of a GCC 5+ std::tuple.
- impl = self.head.cast (nodes[0].type)
+ impl = self.head.cast(nodes[0].type)
self.head = None
else:
# Either a node before the last node, or the last node of
@@ -620,53 +660,55 @@ class StdTuplePrinter:
# - Right node is the actual class contained in the tuple.
# Process right node.
- impl = self.head.cast (nodes[1].type)
+ impl = self.head.cast(nodes[1].type)
# Process left node and set it as head.
- self.head = self.head.cast (nodes[0].type)
+ self.head = self.head.cast(nodes[0].type)
self.count = self.count + 1
# Finally, check the implementation. If it is
# wrapped in _M_head_impl return that, otherwise return
# the value "as is".
- fields = impl.type.fields ()
- if len (fields) < 1 or fields[0].name != "_M_head_impl":
+ fields = impl.type.fields()
+ if len(fields) < 1 or fields[0].name != "_M_head_impl":
return ('[%d]' % (self.count - 1), impl)
else:
return ('[%d]' % (self.count - 1), impl['_M_head_impl'])
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.typename = strip_versioned_namespace(typename)
- self.val = val;
+ self.val = val
- def children (self):
- return self._iterator (self.val)
+ def children(self):
+ return self._iterator(self.val)
- def to_string (self):
- if len (self.val.type.fields ()) == 0:
+ def to_string(self):
+ if len(self.val.type.fields()) == 0:
return 'empty %s' % (self.typename)
return '%s containing' % (self.typename)
+
class StdStackOrQueuePrinter:
"Print a std::stack or std::queue"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.typename = strip_versioned_namespace(typename)
self.visualizer = gdb.default_visualizer(val['c'])
- def children (self):
+ def children(self):
return self.visualizer.children()
- def to_string (self):
+ def to_string(self):
return '%s wrapping: %s' % (self.typename,
self.visualizer.to_string())
- def display_hint (self):
- if hasattr (self.visualizer, 'display_hint'):
- return self.visualizer.display_hint ()
+ def display_hint(self):
+ if hasattr(self.visualizer, 'display_hint'):
+ return self.visualizer.display_hint()
return None
+
class RbtreeIterator(Iterator):
"""
Turn an RB-tree-based container (std::map, std::set etc.) into
@@ -682,7 +724,7 @@ class RbtreeIterator(Iterator):
return self
def __len__(self):
- return int (self.size)
+ return int(self.size)
def __next__(self):
if self.count == self.size:
@@ -706,6 +748,7 @@ class RbtreeIterator(Iterator):
self.node = node
return result
+
def get_value_from_Rb_tree_node(node):
"""Returns the value held in an _Rb_tree_node<_Val>"""
try:
@@ -724,29 +767,32 @@ def get_value_from_Rb_tree_node(node):
# This is a pretty printer for std::_Rb_tree_iterator (which is
# std::map::iterator), and has nothing to do with the RbtreeIterator
# class above.
+
+
class StdRbtreeIteratorPrinter:
"Print std::map::iterator, std::set::iterator, etc."
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.val = val
nodetype = lookup_node_type('_Rb_tree_node', self.val.type)
self.link_type = nodetype.pointer()
- def to_string (self):
+ def to_string(self):
if not self.val['_M_node']:
return 'non-dereferenceable iterator for associative container'
node = self.val['_M_node'].cast(self.link_type).dereference()
return str(get_value_from_Rb_tree_node(node))
+
class StdDebugIteratorPrinter:
"Print a debug enabled version of an iterator"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.val = val
# Just strip away the encapsulating __gnu_debug::_Safe_iterator
# and return the wrapped iterator value.
- def to_string (self):
+ def to_string(self):
base_type = gdb.lookup_type('__gnu_debug::_Safe_iterator_base')
itype = self.val.type.template_argument(0)
safe_seq = self.val.cast(base_type)['_M_sequence']
@@ -756,10 +802,12 @@ class StdDebugIteratorPrinter:
return "invalid iterator"
return str(self.val.cast(itype))
+
def num_elements(num):
"""Return either "1 element" or "N elements" depending on the argument."""
return '1 element' if num == 1 else '%d elements' % num
+
class StdMapPrinter:
"Print a std::map or std::multimap"
@@ -786,21 +834,22 @@ class StdMapPrinter:
self.count = self.count + 1
return result
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.typename = strip_versioned_namespace(typename)
self.val = val
- def to_string (self):
+ def to_string(self):
return '%s with %s' % (self.typename,
- num_elements(len(RbtreeIterator (self.val))))
+ num_elements(len(RbtreeIterator(self.val))))
- def children (self):
+ def children(self):
node = lookup_node_type('_Rb_tree_node', self.val.type).pointer()
- return self._iter (RbtreeIterator (self.val), node)
+ return self._iter(RbtreeIterator(self.val), node)
- def display_hint (self):
+ def display_hint(self):
return 'map'
+
class StdSetPrinter:
"Print a std::set or std::multiset"
@@ -824,17 +873,18 @@ class StdSetPrinter:
self.count = self.count + 1
return result
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.typename = strip_versioned_namespace(typename)
self.val = val
- def to_string (self):
+ def to_string(self):
return '%s with %s' % (self.typename,
- num_elements(len(RbtreeIterator (self.val))))
+ num_elements(len(RbtreeIterator(self.val))))
- def children (self):
+ def children(self):
node = lookup_node_type('_Rb_tree_node', self.val.type).pointer()
- return self._iter (RbtreeIterator (self.val), node)
+ return self._iter(RbtreeIterator(self.val), node)
+
class StdBitsetPrinter:
"Print a std::bitset"
@@ -843,12 +893,12 @@ class StdBitsetPrinter:
self.typename = strip_versioned_namespace(typename)
self.val = val
- def to_string (self):
+ def to_string(self):
# If template_argument handled values, we could print the
# size. Or we could use a regexp on the type.
return '%s' % (self.typename)
- def children (self):
+ def children(self):
try:
# An empty bitset may not have any members which will
# result in an exception being thrown.
@@ -862,7 +912,7 @@ class StdBitsetPrinter:
# array. This depends on the template specialization used.
# If it is a single long, convert to a single element list.
if wtype.code == gdb.TYPE_CODE_ARRAY:
- tsize = wtype.target ().sizeof
+ tsize = wtype.target().sizeof
else:
words = [words]
tsize = wtype.sizeof
@@ -882,6 +932,7 @@ class StdBitsetPrinter:
byte = byte + 1
return result
+
class StdDequePrinter:
"Print a std::deque"
@@ -921,7 +972,7 @@ class StdDequePrinter:
self.elttype = val.type.template_argument(0)
size = self.elttype.sizeof
if size < 512:
- self.buffer_size = int (512 / size)
+ self.buffer_size = int(512 / size)
else:
self.buffer_size = 1
@@ -943,9 +994,10 @@ class StdDequePrinter:
return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
end['_M_cur'], self.buffer_size)
- def display_hint (self):
+ def display_hint(self):
return 'array'
+
class StdDequeIteratorPrinter:
"Print std::deque::iterator"
@@ -957,6 +1009,7 @@ class StdDequeIteratorPrinter:
return 'non-dereferenceable iterator for std::deque'
return str(self.val['_M_cur'].dereference())
+
class StdStringPrinter:
"Print a std::basic_string of some kind"
@@ -968,28 +1021,29 @@ class StdStringPrinter:
# Make sure &string works, too.
type = self.val.type
if type.code == gdb.TYPE_CODE_REF:
- type = type.target ()
+ type = type.target()
# Calculate the length of the string so that to_string returns
# the string according to length, not according to first null
# encountered.
- ptr = self.val ['_M_dataplus']['_M_p']
+ ptr = self.val['_M_dataplus']['_M_p']
if self.new_string:
length = self.val['_M_string_length']
# https://sourceware.org/bugzilla/show_bug.cgi?id=17728
ptr = ptr.cast(ptr.type.strip_typedefs())
else:
- realtype = type.unqualified ().strip_typedefs ()
- reptype = gdb.lookup_type (str (realtype) + '::_Rep').pointer ()
+ realtype = type.unqualified().strip_typedefs()
+ reptype = gdb.lookup_type(str(realtype) + '::_Rep').pointer()
header = ptr.cast(reptype) - 1
- length = header.dereference ()['_M_length']
+ length = header.dereference()['_M_length']
if hasattr(ptr, "lazy_string"):
- return ptr.lazy_string (length = length)
- return ptr.string (length = length)
+ return ptr.lazy_string(length=length)
+ return ptr.string(length=length)
- def display_hint (self):
+ def display_hint(self):
return 'string'
+
def access_streambuf_ptrs(streambuf):
"Access the streambuf put area pointers"
pbase = streambuf['_M_out_beg']
@@ -997,6 +1051,7 @@ def access_streambuf_ptrs(streambuf):
egptr = streambuf['_M_in_end']
return pbase, pptr, egptr
+
class StdStringBufPrinter:
"Print a std::basic_stringbuf"
@@ -1008,14 +1063,15 @@ class StdStringBufPrinter:
# Logic from basic_stringbuf::_M_high_mark()
if pptr:
if not egptr or pptr > egptr:
- return pbase.string(length = pptr - pbase)
+ return pbase.string(length=pptr - pbase)
else:
- return pbase.string(length = egptr - pbase)
+ return pbase.string(length=egptr - pbase)
return self.val['_M_string']
def display_hint(self):
return 'string'
+
class StdStringStreamPrinter:
"Print a std::basic_stringstream"
@@ -1041,8 +1097,9 @@ class StdStringStreamPrinter:
return None
return 'string'
+
class Tr1HashtableIterator(Iterator):
- def __init__ (self, hashtable):
+ def __init__(self, hashtable):
self.buckets = hashtable['_M_buckets']
self.bucket = 0
self.bucket_count = hashtable['_M_bucket_count']
@@ -1054,15 +1111,15 @@ class Tr1HashtableIterator(Iterator):
break
self.bucket = self.bucket + 1
- def __iter__ (self):
+ def __iter__(self):
return self
- def __next__ (self):
+ def __next__(self):
if self.node == 0:
raise StopIteration
node = self.node.cast(self.node_type)
result = node.dereference()['_M_v']
- self.node = node.dereference()['_M_next'];
+ self.node = node.dereference()['_M_next']
if self.node == 0:
self.bucket = self.bucket + 1
while self.bucket != self.bucket_count:
@@ -1072,6 +1129,7 @@ class Tr1HashtableIterator(Iterator):
self.bucket = self.bucket + 1
return result
+
class StdHashtableIterator(Iterator):
def __init__(self, hashtable):
self.node = hashtable['_M_before_begin']['_M_nxt']
@@ -1093,76 +1151,81 @@ class StdHashtableIterator(Iterator):
valptr = valptr.cast(elt.type.template_argument(0).pointer())
return valptr.dereference()
+
class Tr1UnorderedSetPrinter:
"Print a std::unordered_set or tr1::unordered_set"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.typename = strip_versioned_namespace(typename)
self.val = val
- def hashtable (self):
+ def hashtable(self):
if self.typename.startswith('std::tr1'):
return self.val
return self.val['_M_h']
- def to_string (self):
+ def to_string(self):
count = self.hashtable()['_M_element_count']
return '%s with %s' % (self.typename, num_elements(count))
@staticmethod
- def format_count (i):
+ def format_count(i):
return '[%d]' % i
- def children (self):
- counter = imap (self.format_count, itertools.count())
+ def children(self):
+ counter = imap(self.format_count, itertools.count())
if self.typename.startswith('std::tr1'):
- return izip (counter, Tr1HashtableIterator (self.hashtable()))
- return izip (counter, StdHashtableIterator (self.hashtable()))
+ return izip(counter, Tr1HashtableIterator(self.hashtable()))
+ return izip(counter, StdHashtableIterator(self.hashtable()))
+
class Tr1UnorderedMapPrinter:
"Print a std::unordered_map or tr1::unordered_map"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.typename = strip_versioned_namespace(typename)
self.val = val
- def hashtable (self):
+ def hashtable(self):
if self.typename.startswith('std::tr1'):
return self.val
return self.val['_M_h']
- def to_string (self):
+ def to_string(self):
count = self.hashtable()['_M_element_count']
return '%s with %s' % (self.typename, num_elements(count))
@staticmethod
- def flatten (list):
+ def flatten(list):
for elt in list:
for i in elt:
yield i
@staticmethod
- def format_one (elt):
+ def format_one(elt):
return (elt['first'], elt['second'])
@staticmethod
- def format_count (i):
+ def format_count(i):
return '[%d]' % i
- def children (self):
- counter = imap (self.format_count, itertools.count())
+ def children(self):
+ counter = imap(self.format_count, itertools.count())
# Map over the hash table and flatten the result.
if self.typename.startswith('std::tr1'):
- data = self.flatten (imap (self.format_one, Tr1HashtableIterator (self.hashtable())))
+ data = self.flatten(
+ imap(self.format_one, Tr1HashtableIterator(self.hashtable())))
# Zip the two iterators together.
- return izip (counter, data)
- data = self.flatten (imap (self.format_one, StdHashtableIterator (self.hashtable())))
+ return izip(counter, data)
+ data = self.flatten(
+ imap(self.format_one, StdHashtableIterator(self.hashtable())))
# Zip the two iterators together.
- return izip (counter, data)
+ return izip(counter, data)
- def display_hint (self):
+ def display_hint(self):
return 'map'
+
class StdForwardListPrinter:
"Print a std::forward_list"
@@ -1199,10 +1262,11 @@ class StdForwardListPrinter:
return 'empty %s' % self.typename
return '%s' % self.typename
+
class SingleObjContainerPrinter(object):
"Base class for printers of containers of single objects"
- def __init__ (self, val, viz, hint = None):
+ def __init__(self, val, viz, hint=None):
self.contained_value = val
self.visualizer = viz
self.hint = hint
@@ -1216,10 +1280,10 @@ class SingleObjContainerPrinter(object):
type) or str(type)
class _contained(Iterator):
- def __init__ (self, val):
+ def __init__(self, val):
self.val = val
- def __iter__ (self):
+ def __iter__(self):
return self
def __next__(self):
@@ -1229,19 +1293,20 @@ class SingleObjContainerPrinter(object):
self.val = None
return ('[contained value]', retval)
- def children (self):
+ def children(self):
if self.contained_value is None:
- return self._contained (None)
- if hasattr (self.visualizer, 'children'):
- return self.visualizer.children ()
- return self._contained (self.contained_value)
+ return self._contained(None)
+ if hasattr(self.visualizer, 'children'):
+ return self.visualizer.children()
+ return self._contained(self.contained_value)
- def display_hint (self):
+ def display_hint(self):
# if contained value is a map we want to display in the same way
- if hasattr (self.visualizer, 'children') and hasattr (self.visualizer, 'display_hint'):
- return self.visualizer.display_hint ()
+ if hasattr(self.visualizer, 'children') and hasattr(self.visualizer, 'display_hint'):
+ return self.visualizer.display_hint()
return self.hint
+
def function_pointer_to_name(f):
"Find the name of the function referred to by the gdb.Value f, "
" which should contain a function pointer from the program."
@@ -1265,12 +1330,14 @@ def function_pointer_to_name(f):
except:
return None
+
class StdExpAnyPrinter(SingleObjContainerPrinter):
"Print a std::any or std::experimental::any"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.typename = strip_versioned_namespace(typename)
- self.typename = re.sub('^std::experimental::fundamentals_v\d::', 'std::experimental::', self.typename, 1)
+ self.typename = re.sub(
+ '^std::experimental::fundamentals_v\d::', 'std::experimental::', self.typename, 1)
self.val = val
self.contained_type = None
contained_value = None
@@ -1279,11 +1346,13 @@ class StdExpAnyPrinter(SingleObjContainerPrinter):
if mgr != 0:
func = function_pointer_to_name(mgr)
if not func:
- raise ValueError("Invalid function pointer in %s" % (self.typename))
+ raise ValueError(
+ "Invalid function pointer in %s" % (self.typename))
rx = r"""({0}::_Manager_\w+<.*>)::_S_manage\((enum )?{0}::_Op, (const {0}|{0} const) ?\*, (union )?{0}::_Arg ?\*\)""".format(typename)
m = re.match(rx, func)
if not m:
- raise ValueError("Unknown manager function in %s" % self.typename)
+ raise ValueError(
+ "Unknown manager function in %s" % self.typename)
mgrname = m.group(1)
# FIXME need to expand 'std::string' so that gdb.lookup_type works
@@ -1291,11 +1360,13 @@ class StdExpAnyPrinter(SingleObjContainerPrinter):
# This lookup for std::string might return the __cxx11 version,
# but that's not necessarily the one used by the std::any
# manager function we're trying to find.
- strings = {str(gdb.lookup_type('std::string').strip_typedefs())}
+ strings = {
+ str(gdb.lookup_type('std::string').strip_typedefs())}
# So also consider all the other possible std::string types!
s = 'basic_string<char, std::char_traits<char>, std::allocator<char> >'
- quals = ['std::', 'std::__cxx11::', 'std::' + _versioned_namespace]
- strings |= {q+s for q in quals} # set of unique strings
+ quals = ['std::', 'std::__cxx11::',
+ 'std::' + _versioned_namespace]
+ strings |= {q+s for q in quals} # set of unique strings
mgrtypes = []
for s in strings:
try:
@@ -1312,7 +1383,8 @@ class StdExpAnyPrinter(SingleObjContainerPrinter):
# std::any in a single program. Can we do better?
# Maybe find the address of each type's _S_manage and
# compare to the address stored in _M_manager?
- raise ValueError('Cannot uniquely determine std::string type used in std::any')
+ raise ValueError(
+ 'Cannot uniquely determine std::string type used in std::any')
mgrtype = mgrtypes[0]
else:
mgrtype = gdb.lookup_type(mgrname)
@@ -1323,27 +1395,31 @@ class StdExpAnyPrinter(SingleObjContainerPrinter):
elif '::_Manager_external' in mgrname:
valptr = self.val['_M_storage']['_M_ptr']
else:
- raise ValueError("Unknown manager function in %s" % self.typename)
- contained_value = valptr.cast(self.contained_type.pointer()).dereference()
+ raise ValueError(
+ "Unknown manager function in %s" % self.typename)
+ contained_value = valptr.cast(
+ self.contained_type.pointer()).dereference()
visualizer = gdb.default_visualizer(contained_value)
- super(StdExpAnyPrinter, self).__init__ (contained_value, visualizer)
+ super(StdExpAnyPrinter, self).__init__(contained_value, visualizer)
- def to_string (self):
+ def to_string(self):
if self.contained_type is None:
return '%s [no contained value]' % self.typename
desc = "%s containing " % self.typename
- if hasattr (self.visualizer, 'children'):
- return desc + self.visualizer.to_string ()
- valtype = self._recognize (self.contained_type)
+ if hasattr(self.visualizer, 'children'):
+ return desc + self.visualizer.to_string()
+ valtype = self._recognize(self.contained_type)
return desc + strip_versioned_namespace(str(valtype))
+
class StdExpOptionalPrinter(SingleObjContainerPrinter):
"Print a std::optional or std::experimental::optional"
- def __init__ (self, typename, val):
- valtype = self._recognize (val.type.template_argument(0))
+ def __init__(self, typename, val):
+ valtype = self._recognize(val.type.template_argument(0))
typename = strip_versioned_namespace(typename)
- self.typename = re.sub('^std::(experimental::|)(fundamentals_v\d::|)(.*)', r'std::\1\3', typename, 1)
+ self.typename = re.sub(
+ '^std::(experimental::|)(fundamentals_v\d::|)(.*)', r'std::\1\3', typename, 1)
payload = val['_M_payload']
if self.typename.startswith('std::experimental'):
engaged = val['_M_engaged']
@@ -1356,19 +1432,21 @@ class StdExpOptionalPrinter(SingleObjContainerPrinter):
contained_value = contained_value['_M_value']
except:
pass
- visualizer = gdb.default_visualizer (contained_value)
+ visualizer = gdb.default_visualizer(contained_value)
if not engaged:
contained_value = None
- super (StdExpOptionalPrinter, self).__init__ (contained_value, visualizer)
+ super(StdExpOptionalPrinter, self).__init__(
+ contained_value, visualizer)
- def to_string (self):
+ def to_string(self):
if self.contained_value is None:
return "%s [no contained value]" % self.typename
- if hasattr (self.visualizer, 'children'):
+ if hasattr(self.visualizer, 'children'):
return "%s containing %s" % (self.typename,
self.visualizer.to_string())
return self.typename
+
class StdVariantPrinter(SingleObjContainerPrinter):
"Print a std::variant"
@@ -1383,9 +1461,11 @@ class StdVariantPrinter(SingleObjContainerPrinter):
else:
self.contained_type = alternatives[int(self.index)]
addr = val['_M_u']['_M_first']['_M_storage'].address
- contained_value = addr.cast(self.contained_type.pointer()).dereference()
+ contained_value = addr.cast(
+ self.contained_type.pointer()).dereference()
visualizer = gdb.default_visualizer(contained_value)
- super (StdVariantPrinter, self).__init__(contained_value, visualizer, 'array')
+ super(StdVariantPrinter, self).__init__(
+ contained_value, visualizer, 'array')
def to_string(self):
if self.contained_value is None:
@@ -1395,18 +1475,21 @@ class StdVariantPrinter(SingleObjContainerPrinter):
self.visualizer.to_string())
return "%s [index %d]" % (self.typename, self.index)
+
class StdNodeHandlePrinter(SingleObjContainerPrinter):
"Print a container node handle"
def __init__(self, typename, val):
self.value_type = val.type.template_argument(1)
nodetype = val.type.template_argument(2).template_argument(0)
- self.is_rb_tree_node = is_specialization_of(nodetype.name, '_Rb_tree_node')
+ self.is_rb_tree_node = is_specialization_of(
+ nodetype.name, '_Rb_tree_node')
self.is_map_node = val.type.template_argument(0) != self.value_type
nodeptr = val['_M_ptr']
if nodeptr:
if self.is_rb_tree_node:
- contained_value = get_value_from_Rb_tree_node(nodeptr.dereference())
+ contained_value = get_value_from_Rb_tree_node(
+ nodeptr.dereference())
else:
contained_value = get_value_from_aligned_membuf(nodeptr['_M_storage'],
self.value_type)
@@ -1424,9 +1507,9 @@ class StdNodeHandlePrinter(SingleObjContainerPrinter):
if not self.is_rb_tree_node:
desc += 'unordered '
if self.is_map_node:
- desc += 'map';
+ desc += 'map'
else:
- desc += 'set';
+ desc += 'set'
if self.contained_value:
desc += ' with element'
@@ -1436,31 +1519,33 @@ class StdNodeHandlePrinter(SingleObjContainerPrinter):
else:
return 'empty %s' % desc
+
class StdExpStringViewPrinter:
"Print a std::basic_string_view or std::experimental::basic_string_view"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.val = val
- def to_string (self):
+ def to_string(self):
ptr = self.val['_M_str']
len = self.val['_M_len']
- if hasattr (ptr, "lazy_string"):
- return ptr.lazy_string (length = len)
- return ptr.string (length = len)
+ if hasattr(ptr, "lazy_string"):
+ return ptr.lazy_string(length=len)
+ return ptr.string(length=len)
- def display_hint (self):
+ def display_hint(self):
return 'string'
+
class StdExpPathPrinter:
"Print a std::experimental::filesystem::path"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.val = val
self.typename = typename
start = self.val['_M_cmpts']['_M_impl']['_M_start']
finish = self.val['_M_cmpts']['_M_impl']['_M_finish']
- self.num_cmpts = int (finish - start)
+ self.num_cmpts = int(finish - start)
def _path_type(self):
t = str(self.val['_M_type'])
@@ -1470,8 +1555,8 @@ class StdExpPathPrinter:
return "root-name"
return None
- def to_string (self):
- path = "%s" % self.val ['_M_pathname']
+ def to_string(self):
+ path = "%s" % self.val['_M_pathname']
if self.num_cmpts == 0:
t = self._path_type()
if t:
@@ -1504,10 +1589,11 @@ class StdExpPathPrinter:
def children(self):
return self._iterator(self.val['_M_cmpts'], self.typename)
+
class StdPathPrinter:
"Print a std::filesystem::path"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.val = val
self.typename = typename
impl = unique_ptr_get(self.val['_M_cmpts']['_M_impl'])
@@ -1525,8 +1611,8 @@ class StdPathPrinter:
return "root-name"
return None
- def to_string (self):
- path = "%s" % self.val ['_M_pathname']
+ def to_string(self):
+ path = "%s" % self.val['_M_pathname']
if self.type != 0:
t = self._path_type()
if t:
@@ -1609,27 +1695,29 @@ class StdPairPrinter:
def to_string(self):
return None
+
class StdCmpCatPrinter:
"Print a comparison category object"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.typename = typename[typename.rfind(':')+1:]
self.val = val['_M_value']
- def to_string (self):
+ def to_string(self):
if self.typename == 'strong_ordering' and self.val == 0:
name = 'equal'
else:
- names = {2:'unordered', -1:'less', 0:'equivalent', 1:'greater'}
+ names = {2: 'unordered', -1: 'less', 0: 'equivalent', 1: 'greater'}
name = names[int(self.val)]
return 'std::{}::{}'.format(self.typename, name)
+
class StdErrorCodePrinter:
"Print a std::error_code or std::error_condition"
_system_is_posix = None # Whether std::system_category() use errno values.
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.val = val
self.typename = strip_versioned_namespace(typename)
# Do this only once ...
@@ -1718,15 +1806,15 @@ class StdErrorCodePrinter:
"Strip any nested-name-specifier from NAME to give an unqualified name"
return name.split('::')[-1]
- def to_string (self):
+ def to_string(self):
value = self.val['_M_value']
cat = self.val['_M_cat']
name, alt_name, enum, is_errno = self._category_info(cat)
if value == 0:
- default_cats = { 'error_code' : 'system',
- 'error_condition' : 'generic' }
+ default_cats = {'error_code': 'system',
+ 'error_condition': 'generic'}
if name == default_cats[self._unqualified_name(self.typename)]:
- return self.typename + ' = { }' # default-constructed value
+ return self.typename + ' = { }' # default-constructed value
strval = str(value)
if is_errno and value != 0:
@@ -1747,24 +1835,24 @@ class StdErrorCodePrinter:
class StdRegexStatePrinter:
"Print a state node in the NFA for a std::regex"
- def __init__ (self, typename, val):
+ def __init__(self, typename, val):
self.val = val
self.typename = typename
- def to_string (self):
+ def to_string(self):
opcode = str(self.val['_M_opcode'])
if opcode:
opcode = opcode[25:]
next_id = self.val['_M_next']
- variants = {'repeat':'alt', 'alternative':'alt',
- 'subexpr_begin':'subexpr', 'subexpr_end':'subexpr',
- 'line_begin_assertion':None, 'line_end_assertion':None,
- 'word_boundary':'neg', 'subexpr_lookahead':'neg',
- 'backref':'backref_index',
- 'match':None, 'accept':None,
- 'dummy':None, 'unknown':None
- }
+ variants = {'repeat': 'alt', 'alternative': 'alt',
+ 'subexpr_begin': 'subexpr', 'subexpr_end': 'subexpr',
+ 'line_begin_assertion': None, 'line_end_assertion': None,
+ 'word_boundary': 'neg', 'subexpr_lookahead': 'neg',
+ 'backref': 'backref_index',
+ 'match': None, 'accept': None,
+ 'dummy': None, 'unknown': None
+ }
v = variants[opcode]
s = "opcode={}, next={}".format(opcode, next_id)
@@ -1772,6 +1860,7 @@ class StdRegexStatePrinter:
s = "{}, {}={}".format(s, v, self.val['_M_' + v])
return "{%s}" % (s)
+
class StdSpanPrinter:
"Print a std::span"
@@ -1781,10 +1870,10 @@ class StdSpanPrinter:
self.begin = begin
self.size = size
- def __iter__ (self):
+ def __iter__(self):
return self
- def __next__ (self):
+ def __next__(self):
if self.count == self.size:
raise StopIteration
@@ -1809,6 +1898,7 @@ class StdSpanPrinter:
def display_hint(self):
return 'array'
+
class StdInitializerListPrinter:
"Print a std::initializer_list"
@@ -1826,6 +1916,7 @@ class StdInitializerListPrinter:
def display_hint(self):
return 'array'
+
class StdAtomicPrinter:
"Print a std:atomic"
@@ -1860,6 +1951,7 @@ class StdAtomicPrinter:
val = self.val['_M_i']
return '%s<%s> = { %s }' % (self.typename, str(self.value_type), val)
+
class StdFormatArgsPrinter:
"Print a std::basic_format_args"
# TODO: add printer for basic_format_arg<Context> and print out children.
@@ -1886,6 +1978,7 @@ class StdFormatArgsPrinter:
size = self.val['_M_unpacked_size']
return "%s with %d arguments" % (typ, size)
+
def std_ratio_t_tuple(ratio_type):
# TODO use reduced period i.e. duration::period
period = self.val.type.template_argument(1)
@@ -1893,6 +1986,7 @@ def std_ratio_t_tuple(ratio_type):
den = period.template_argument(1)
return (num, den)
+
class StdChronoDurationPrinter:
"Print a std::chrono::duration"
@@ -1950,18 +2044,18 @@ class StdChronoTimePointPrinter:
return ('std::chrono::sys_time', 0)
# XXX need to remove leap seconds from utc, gps, and tai
if name == 'std::chrono::utc_clock':
- return ('std::chrono::utc_time', None) # XXX
+ return ('std::chrono::utc_time', None) # XXX
if name == 'std::chrono::gps_clock':
- return ('std::chrono::gps_time', None) # XXX 315964809
+ return ('std::chrono::gps_time', None) # XXX 315964809
if name == 'std::chrono::tai_clock':
- return ('std::chrono::tai_time', None) # XXX -378691210
+ return ('std::chrono::tai_time', None) # XXX -378691210
if name == 'std::filesystem::__file_clock':
return ('std::chrono::file_time', 6437664000)
if name == 'std::chrono::local_t':
return ('std::chrono::local_time', 0)
return ('{} time_point'.format(name), None)
- def to_string(self, abbrev = False):
+ def to_string(self, abbrev=False):
clock, offset = self._clock()
d = self.val['__d']
r = d['__r']
@@ -1981,6 +2075,7 @@ class StdChronoTimePointPrinter:
return s
return '%s = { %s }' % (clock, s)
+
class StdChronoZonedTimePrinter:
"Print a std::chrono::zoned_time"
@@ -2002,6 +2097,7 @@ months = [None, 'January', 'February', 'March', 'April', 'May', 'June',
weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday']
+
class StdChronoCalendarPrinter:
"Print a std::chrono::day, std::chrono::month, std::chrono::year etc."
@@ -2064,6 +2160,7 @@ class StdChronoCalendarPrinter:
h = -h
return '{:02}:{:02}:{:02}{}'.format(h, m, s, fract)
+
class StdChronoTimeZonePrinter:
"Print a chrono::time_zone or chrono::time_zone_link"
@@ -2077,6 +2174,7 @@ class StdChronoTimeZonePrinter:
str += ' -> %s' % (self.val['_M_target'])
return str
+
class StdChronoLeapSecondPrinter:
"Print a chrono::leap_second"
@@ -2089,6 +2187,7 @@ class StdChronoLeapSecondPrinter:
neg = '+-'[date < 0]
return '%s %d (%c)' % (self.typename, abs(date), neg)
+
class StdChronoTzdbPrinter:
"Print a chrono::tzdb"
@@ -2099,6 +2198,7 @@ class StdChronoTzdbPrinter:
def to_string(self):
return '%s %s' % (self.typename, self.val['version'])
+
class StdChronoTimeZoneRulePrinter:
"Print a chrono::time_zone rule"
@@ -2110,17 +2210,18 @@ class StdChronoTimeZoneRulePrinter:
on = self.val['on']
kind = on['kind']
month = months[on['month']]
- suffixes = {1:'st', 2:'nd', 3:'rd', 21:'st', 22:'nd', 23:'rd', 31:'st'}
+ suffixes = {1: 'st', 2: 'nd', 3: 'rd',
+ 21: 'st', 22: 'nd', 23: 'rd', 31: 'st'}
day = on['day_of_month']
ordinal_day = '{}{}'.format(day, suffixes.get(day, 'th'))
- if kind == 0: # DayOfMonth
- start = '{} {}{}'.format(month, ordinal_day)
+ if kind == 0: # DayOfMonth
+ start = '{} {}{}'.format(month, ordinal_day)
else:
weekday = weekdays[on['day_of_week']]
- if kind == 1: # LastWeekDay
+ if kind == 1: # LastWeekDay
start = 'last {} in {}'.format(weekday, month)
else:
- if kind == 2: # LessEq
+ if kind == 2: # LessEq
direction = ('last', '<=')
else:
direction = ('first', '>=')
@@ -2129,7 +2230,8 @@ class StdChronoTimeZoneRulePrinter:
direction[1], month,
ordinal_day)
return 'time_zone rule {} from {} to {} starting on {}'.format(
- self.val['name'], self.val['from'], self.val['to'], start)
+ self.val['name'], self.val['from'], self.val['to'], start)
+
class StdLocalePrinter:
"Print a std::locale"
@@ -2146,7 +2248,7 @@ class StdLocalePrinter:
else:
cats = gdb.parse_and_eval(self.typename + '::_S_categories')
ncat = gdb.parse_and_eval(self.typename + '::_S_categories_size')
- n = names[0].string();
+ n = names[0].string()
cat = cats[0].string()
name = '{}={}'.format(cat, n)
cat_names = {cat: n}
@@ -2171,7 +2273,7 @@ class StdLocalePrinter:
name = n1
other = n2
if other is not None:
- cat = next(c for c,n in cat_names.items() if n == other)
+ cat = next(c for c, n in cat_names.items() if n == other)
mod = ' with "{}={}"'.format(cat, other)
return 'std::locale = "{}"{}'.format(name, mod)
@@ -2190,13 +2292,15 @@ class RxPrinter(object):
return None
if value.type.code == gdb.TYPE_CODE_REF:
- if hasattr(gdb.Value,"referenced_value"):
+ if hasattr(gdb.Value, "referenced_value"):
value = value.referenced_value()
return self.function(self.name, value)
# A pretty-printer that conforms to the "PrettyPrinter" protocol from
# gdb.printing. It can also be used directly as an old-style printer.
+
+
class Printer(object):
def __init__(self, name):
super(Printer, self).__init__()
@@ -2210,7 +2314,8 @@ class Printer(object):
# A small sanity check.
# FIXME
if not self.compiled_rx.match(name):
- raise ValueError('libstdc++ programming error: "%s" does not match' % name)
+ raise ValueError(
+ 'libstdc++ programming error: "%s" does not match' % name)
printer = RxPrinter(name, function)
self.subprinters.append(printer)
self.lookup[name] = printer
@@ -2219,7 +2324,8 @@ class Printer(object):
def add_version(self, base, name, function):
self.add(base + name, function)
if _versioned_namespace and not '__cxx11' in base:
- vbase = re.sub('^(std|__gnu_cxx)::', r'\g<0>%s' % _versioned_namespace, base)
+ vbase = re.sub('^(std|__gnu_cxx)::', r'\g<0>%s' %
+ _versioned_namespace, base)
self.add(vbase + name, function)
# Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
@@ -2231,10 +2337,10 @@ class Printer(object):
def get_basic_type(type):
# If it points to a reference, get the reference.
if type.code == gdb.TYPE_CODE_REF:
- type = type.target ()
+ type = type.target()
# Get the unqualified type, stripped of typedefs.
- type = type.unqualified ().strip_typedefs ()
+ type = type.unqualified().strip_typedefs()
return type.tag
@@ -2252,7 +2358,7 @@ class Printer(object):
basename = match.group(1)
if val.type.code == gdb.TYPE_CODE_REF:
- if hasattr(gdb.Value,"referenced_value"):
+ if hasattr(gdb.Value, "referenced_value"):
val = val.referenced_value()
if basename in self.lookup:
@@ -2261,8 +2367,10 @@ class Printer(object):
# Cannot find a pretty printer. Return None.
return None
+
libstdcxx_printer = None
+
class TemplateTypePrinter(object):
r"""
A type printer for class templates with default template arguments.
@@ -2345,7 +2453,7 @@ class TemplateTypePrinter(object):
if type_obj.code == gdb.TYPE_CODE_ARRAY:
type_str = self._recognize_subtype(type_obj.target())
if str(type_obj.strip_typedefs()).endswith('[]'):
- return type_str + '[]' # array of unknown bound
+ return type_str + '[]' # array of unknown bound
return "%s[%d]" % (type_str, type_obj.range()[1] + 1)
if type_obj.code == gdb.TYPE_CODE_REF:
return self._recognize_subtype(type_obj.target()) + '&'
@@ -2354,7 +2462,7 @@ class TemplateTypePrinter(object):
return self._recognize_subtype(type_obj.target()) + '&&'
type_str = gdb.types.apply_type_recognizers(
- gdb.types.get_type_recognizers(), type_obj)
+ gdb.types.get_type_recognizers(), type_obj)
if type_str:
return type_str
return str(type_obj)
@@ -2363,6 +2471,7 @@ class TemplateTypePrinter(object):
"Return a recognizer object for this type printer."
return self._recognizer(self.name, self.defargs)
+
def add_one_template_type_printer(obj, name, defargs):
r"""
Add a type printer for a class template with default template arguments.
@@ -2391,7 +2500,8 @@ def add_one_template_type_printer(obj, name, defargs):
# Add second type printer for same type in versioned namespace:
ns = 'std::' + _versioned_namespace
# PR 86112 Cannot use dict comprehension here:
- defargs = dict((n, d.replace('std::', ns)) for (n,d) in defargs.items())
+ defargs = dict((n, d.replace('std::', ns))
+ for (n, d) in defargs.items())
printer = TemplateTypePrinter(ns+name, defargs)
gdb.types.register_type_printer(obj, printer)
@@ -2399,6 +2509,7 @@ def add_one_template_type_printer(obj, name, defargs):
printer = TemplateTypePrinter('std::__debug::'+name, defargs)
gdb.types.register_type_printer(obj, printer)
+
class FilteringTypePrinter(object):
r"""
A type printer that uses typedef names for common template specializations.
@@ -2421,7 +2532,7 @@ class FilteringTypePrinter(object):
more quickly, without needing to do GDB type lookups.
"""
- def __init__(self, template, name, targ1 = None):
+ def __init__(self, template, name, targ1=None):
self.template = template
self.name = name
self.targ1 = targ1
@@ -2475,7 +2586,8 @@ class FilteringTypePrinter(object):
"Return a recognizer object for this type printer."
return self._recognizer(self.template, self.name, self.targ1)
-def add_one_type_printer(obj, template, name, targ1 = None):
+
+def add_one_type_printer(obj, template, name, targ1=None):
printer = FilteringTypePrinter('std::' + template, 'std::' + name, targ1)
gdb.types.register_type_printer(obj, printer)
if _versioned_namespace and not '__cxx11' in template:
@@ -2483,6 +2595,7 @@ def add_one_type_printer(obj, template, name, targ1 = None):
printer = FilteringTypePrinter(ns + template, ns + name, targ1)
gdb.types.register_type_printer(obj, printer)
+
def register_type_printers(obj):
global _use_type_printing
@@ -2496,11 +2609,13 @@ def register_type_printers(obj):
('u16', 'char16_t'),
('u32', 'char32_t')):
add_one_type_printer(obj, 'basic_string', ch[0] + 'string', ch[1])
- add_one_type_printer(obj, '__cxx11::basic_string', ch[0] + 'string', ch[1])
+ add_one_type_printer(obj, '__cxx11::basic_string',
+ ch[0] + 'string', ch[1])
# Typedefs for __cxx11::basic_string used to be in namespace __cxx11:
add_one_type_printer(obj, '__cxx11::basic_string',
'__cxx11::' + ch[0] + 'string', ch[1])
- add_one_type_printer(obj, 'basic_string_view', ch[0] + 'string_view', ch[1])
+ add_one_type_printer(obj, 'basic_string_view',
+ ch[0] + 'string_view', ch[1])
# Add type printers for typedefs std::istream, std::wistream etc.
for ch in (('', 'char'), ('w', 'wchar_t')):
@@ -2516,9 +2631,11 @@ def register_type_printers(obj):
# Add type printers for typedefs regex, wregex, cmatch, wcmatch etc.
for abi in ('', '__cxx11::'):
for ch in (('', 'char'), ('w', 'wchar_t')):
- add_one_type_printer(obj, abi + 'basic_regex', abi + ch[0] + 'regex', ch[1])
+ add_one_type_printer(obj, abi + 'basic_regex',
+ abi + ch[0] + 'regex', ch[1])
for ch in ('c', 's', 'wc', 'ws'):
- add_one_type_printer(obj, abi + 'match_results', abi + ch + 'match')
+ add_one_type_printer(
+ obj, abi + 'match_results', abi + ch + 'match')
for x in ('sub_match', 'regex_iterator', 'regex_token_iterator'):
add_one_type_printer(obj, abi + x, abi + ch + x)
@@ -2554,40 +2671,43 @@ def register_type_printers(obj):
# Do not show defaulted template arguments in class templates.
add_one_template_type_printer(obj, 'unique_ptr',
- { 1: 'std::default_delete<{0}>' })
- add_one_template_type_printer(obj, 'deque', { 1: 'std::allocator<{0}>'})
- add_one_template_type_printer(obj, 'forward_list', { 1: 'std::allocator<{0}>'})
- add_one_template_type_printer(obj, 'list', { 1: 'std::allocator<{0}>'})
- add_one_template_type_printer(obj, '__cxx11::list', { 1: 'std::allocator<{0}>'})
- add_one_template_type_printer(obj, 'vector', { 1: 'std::allocator<{0}>'})
+ {1: 'std::default_delete<{0}>'})
+ add_one_template_type_printer(obj, 'deque', {1: 'std::allocator<{0}>'})
+ add_one_template_type_printer(
+ obj, 'forward_list', {1: 'std::allocator<{0}>'})
+ add_one_template_type_printer(obj, 'list', {1: 'std::allocator<{0}>'})
+ add_one_template_type_printer(
+ obj, '__cxx11::list', {1: 'std::allocator<{0}>'})
+ add_one_template_type_printer(obj, 'vector', {1: 'std::allocator<{0}>'})
add_one_template_type_printer(obj, 'map',
- { 2: 'std::less<{0}>',
- 3: 'std::allocator<std::pair<{0} const, {1}>>' })
+ {2: 'std::less<{0}>',
+ 3: 'std::allocator<std::pair<{0} const, {1}>>'})
add_one_template_type_printer(obj, 'multimap',
- { 2: 'std::less<{0}>',
- 3: 'std::allocator<std::pair<{0} const, {1}>>' })
+ {2: 'std::less<{0}>',
+ 3: 'std::allocator<std::pair<{0} const, {1}>>'})
add_one_template_type_printer(obj, 'set',
- { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
+ {1: 'std::less<{0}>', 2: 'std::allocator<{0}>'})
add_one_template_type_printer(obj, 'multiset',
- { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
+ {1: 'std::less<{0}>', 2: 'std::allocator<{0}>'})
add_one_template_type_printer(obj, 'unordered_map',
- { 2: 'std::hash<{0}>',
- 3: 'std::equal_to<{0}>',
- 4: 'std::allocator<std::pair<{0} const, {1}>>'})
+ {2: 'std::hash<{0}>',
+ 3: 'std::equal_to<{0}>',
+ 4: 'std::allocator<std::pair<{0} const, {1}>>'})
add_one_template_type_printer(obj, 'unordered_multimap',
- { 2: 'std::hash<{0}>',
- 3: 'std::equal_to<{0}>',
- 4: 'std::allocator<std::pair<{0} const, {1}>>'})
+ {2: 'std::hash<{0}>',
+ 3: 'std::equal_to<{0}>',
+ 4: 'std::allocator<std::pair<{0} const, {1}>>'})
add_one_template_type_printer(obj, 'unordered_set',
- { 1: 'std::hash<{0}>',
- 2: 'std::equal_to<{0}>',
- 3: 'std::allocator<{0}>'})
+ {1: 'std::hash<{0}>',
+ 2: 'std::equal_to<{0}>',
+ 3: 'std::allocator<{0}>'})
add_one_template_type_printer(obj, 'unordered_multiset',
- { 1: 'std::hash<{0}>',
- 2: 'std::equal_to<{0}>',
- 3: 'std::allocator<{0}>'})
+ {1: 'std::hash<{0}>',
+ 2: 'std::equal_to<{0}>',
+ 3: 'std::allocator<{0}>'})
-def register_libstdcxx_printers (obj):
+
+def register_libstdcxx_printers(obj):
"Register libstdc++ pretty-printers with objfile Obj."
global _use_gdb_pp
@@ -2602,7 +2722,8 @@ def register_libstdcxx_printers (obj):
register_type_printers(obj)
-def build_libstdcxx_dictionary ():
+
+def build_libstdcxx_dictionary():
global libstdcxx_printer
libstdcxx_printer = Printer("libstdc++-v6")
@@ -2611,7 +2732,8 @@ def build_libstdcxx_dictionary ():
# In order from:
# http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
libstdcxx_printer.add_version('std::', 'basic_string', StdStringPrinter)
- libstdcxx_printer.add_version('std::__cxx11::', 'basic_string', StdStringPrinter)
+ libstdcxx_printer.add_version(
+ 'std::__cxx11::', 'basic_string', StdStringPrinter)
libstdcxx_printer.add_container('std::', 'bitset', StdBitsetPrinter)
libstdcxx_printer.add_container('std::', 'deque', StdDequePrinter)
libstdcxx_printer.add_container('std::', 'list', StdListPrinter)
@@ -2662,8 +2784,10 @@ def build_libstdcxx_dictionary ():
libstdcxx_printer.add_container('std::', 'forward_list',
StdForwardListPrinter)
- libstdcxx_printer.add_version('std::tr1::', 'shared_ptr', SharedPointerPrinter)
- libstdcxx_printer.add_version('std::tr1::', 'weak_ptr', SharedPointerPrinter)
+ libstdcxx_printer.add_version(
+ 'std::tr1::', 'shared_ptr', SharedPointerPrinter)
+ libstdcxx_printer.add_version(
+ 'std::tr1::', 'weak_ptr', SharedPointerPrinter)
libstdcxx_printer.add_version('std::tr1::', 'unordered_map',
Tr1UnorderedMapPrinter)
libstdcxx_printer.add_version('std::tr1::', 'unordered_set',
@@ -2676,11 +2800,15 @@ def build_libstdcxx_dictionary ():
libstdcxx_printer.add_version('std::', 'initializer_list',
StdInitializerListPrinter)
libstdcxx_printer.add_version('std::', 'atomic', StdAtomicPrinter)
- libstdcxx_printer.add_version('std::', 'basic_stringbuf', StdStringBufPrinter)
- libstdcxx_printer.add_version('std::__cxx11::', 'basic_stringbuf', StdStringBufPrinter)
+ libstdcxx_printer.add_version(
+ 'std::', 'basic_stringbuf', StdStringBufPrinter)
+ libstdcxx_printer.add_version(
+ 'std::__cxx11::', 'basic_stringbuf', StdStringBufPrinter)
for sstream in ('istringstream', 'ostringstream', 'stringstream'):
- libstdcxx_printer.add_version('std::', 'basic_' + sstream, StdStringStreamPrinter)
- libstdcxx_printer.add_version('std::__cxx11::', 'basic_' + sstream, StdStringStreamPrinter)
+ libstdcxx_printer.add_version(
+ 'std::', 'basic_' + sstream, StdStringStreamPrinter)
+ libstdcxx_printer.add_version(
+ 'std::__cxx11::', 'basic_' + sstream, StdStringStreamPrinter)
libstdcxx_printer.add_version('std::chrono::', 'duration',
StdChronoDurationPrinter)
@@ -2735,16 +2863,17 @@ def build_libstdcxx_dictionary ():
'_Node_handle', StdNodeHandlePrinter)
# C++20 components
- libstdcxx_printer.add_version('std::', 'partial_ordering', StdCmpCatPrinter)
+ libstdcxx_printer.add_version(
+ 'std::', 'partial_ordering', StdCmpCatPrinter)
libstdcxx_printer.add_version('std::', 'weak_ordering', StdCmpCatPrinter)
libstdcxx_printer.add_version('std::', 'strong_ordering', StdCmpCatPrinter)
libstdcxx_printer.add_version('std::', 'span', StdSpanPrinter)
libstdcxx_printer.add_version('std::', 'basic_format_args',
StdFormatArgsPrinter)
- for c in ['day','month','year','weekday','weekday_indexed','weekday_last',
- 'month_day','month_day_last','month_weekday','month_weekday_last',
- 'year_month','year_month_day','year_month_day_last',
- 'year_month_weekday','year_month_weekday_last', 'hh_mm_ss']:
+ for c in ['day', 'month', 'year', 'weekday', 'weekday_indexed', 'weekday_last',
+ 'month_day', 'month_day_last', 'month_weekday', 'month_weekday_last',
+ 'year_month', 'year_month_day', 'year_month_day_last',
+ 'year_month_weekday', 'year_month_weekday_last', 'hh_mm_ss']:
libstdcxx_printer.add_version('std::chrono::', c,
StdChronoCalendarPrinter)
libstdcxx_printer.add_version('std::chrono::', 'time_zone',
@@ -2755,8 +2884,9 @@ def build_libstdcxx_dictionary ():
StdChronoZonedTimePrinter)
libstdcxx_printer.add_version('std::chrono::', 'leap_second',
StdChronoLeapSecondPrinter)
- libstdcxx_printer.add_version('std::chrono::', 'tzdb', StdChronoTzdbPrinter)
- #libstdcxx_printer.add_version('std::chrono::(anonymous namespace)', 'Rule',
+ libstdcxx_printer.add_version(
+ 'std::chrono::', 'tzdb', StdChronoTzdbPrinter)
+ # libstdcxx_printer.add_version('std::chrono::(anonymous namespace)', 'Rule',
# StdChronoTimeZoneRulePrinter)
# Extensions.
@@ -2780,11 +2910,11 @@ def build_libstdcxx_dictionary ():
libstdcxx_printer.add_version('__gnu_cxx::', '__normal_iterator',
StdVectorIteratorPrinter)
libstdcxx_printer.add_container('std::', '_Bit_iterator',
- StdBitIteratorPrinter)
+ StdBitIteratorPrinter)
libstdcxx_printer.add_container('std::', '_Bit_const_iterator',
- StdBitIteratorPrinter)
+ StdBitIteratorPrinter)
libstdcxx_printer.add_container('std::', '_Bit_reference',
- StdBitReferencePrinter)
+ StdBitReferencePrinter)
libstdcxx_printer.add_version('__gnu_cxx::', '_Slist_iterator',
StdSlistIteratorPrinter)
libstdcxx_printer.add_container('std::', '_Fwd_list_iterator',
@@ -2797,4 +2927,5 @@ def build_libstdcxx_dictionary ():
libstdcxx_printer.add('__gnu_debug::_Safe_iterator',
StdDebugIteratorPrinter)
-build_libstdcxx_dictionary ()
+
+build_libstdcxx_dictionary()
@@ -21,12 +21,15 @@ import re
matcher_name_prefix = 'libstdc++::'
+
def get_bool_type():
return gdb.lookup_type('bool')
+
def get_std_size_type():
return gdb.lookup_type('std::size_t')
+
class LibStdCxxXMethod(gdb.xmethod.XMethod):
def __init__(self, name, worker_class):
gdb.xmethod.XMethod.__init__(self, name)
@@ -34,6 +37,7 @@ class LibStdCxxXMethod(gdb.xmethod.XMethod):
# Xmethods for std::array
+
class ArrayWorkerBase(gdb.xmethod.XMethodWorker):
def __init__(self, val_type, size):
self._val_type = val_type
@@ -43,6 +47,7 @@ class ArrayWorkerBase(gdb.xmethod.XMethodWorker):
nullptr = gdb.parse_and_eval('(void *) 0')
return nullptr.cast(self._val_type.pointer()).dereference()
+
class ArraySizeWorker(ArrayWorkerBase):
def __init__(self, val_type, size):
ArrayWorkerBase.__init__(self, val_type, size)
@@ -56,6 +61,7 @@ class ArraySizeWorker(ArrayWorkerBase):
def __call__(self, obj):
return self._size
+
class ArrayEmptyWorker(ArrayWorkerBase):
def __init__(self, val_type, size):
ArrayWorkerBase.__init__(self, val_type, size)
@@ -69,6 +75,7 @@ class ArrayEmptyWorker(ArrayWorkerBase):
def __call__(self, obj):
return (int(self._size) == 0)
+
class ArrayFrontWorker(ArrayWorkerBase):
def __init__(self, val_type, size):
ArrayWorkerBase.__init__(self, val_type, size)
@@ -85,6 +92,7 @@ class ArrayFrontWorker(ArrayWorkerBase):
else:
return self.null_value()
+
class ArrayBackWorker(ArrayWorkerBase):
def __init__(self, val_type, size):
ArrayWorkerBase.__init__(self, val_type, size)
@@ -101,6 +109,7 @@ class ArrayBackWorker(ArrayWorkerBase):
else:
return self.null_value()
+
class ArrayAtWorker(ArrayWorkerBase):
def __init__(self, val_type, size):
ArrayWorkerBase.__init__(self, val_type, size)
@@ -117,6 +126,7 @@ class ArrayAtWorker(ArrayWorkerBase):
((int(index), self._size)))
return obj['_M_elems'][index]
+
class ArraySubscriptWorker(ArrayWorkerBase):
def __init__(self, val_type, size):
ArrayWorkerBase.__init__(self, val_type, size)
@@ -133,6 +143,7 @@ class ArraySubscriptWorker(ArrayWorkerBase):
else:
return self.null_value()
+
class ArrayMethodsMatcher(gdb.xmethod.XMethodMatcher):
def __init__(self):
gdb.xmethod.XMethodMatcher.__init__(self,
@@ -162,6 +173,7 @@ class ArrayMethodsMatcher(gdb.xmethod.XMethodMatcher):
# Xmethods for std::deque
+
class DequeWorkerBase(gdb.xmethod.XMethodWorker):
def __init__(self, val_type):
self._val_type = val_type
@@ -179,6 +191,7 @@ class DequeWorkerBase(gdb.xmethod.XMethodWorker):
index_node = first_node + int(idx) // self._bufsize
return index_node[0][idx % self._bufsize]
+
class DequeEmptyWorker(DequeWorkerBase):
def get_arg_types(self):
return None
@@ -190,6 +203,7 @@ class DequeEmptyWorker(DequeWorkerBase):
return (obj['_M_impl']['_M_start']['_M_cur'] ==
obj['_M_impl']['_M_finish']['_M_cur'])
+
class DequeSizeWorker(DequeWorkerBase):
def get_arg_types(self):
return None
@@ -200,6 +214,7 @@ class DequeSizeWorker(DequeWorkerBase):
def __call__(self, obj):
return self.size(obj)
+
class DequeFrontWorker(DequeWorkerBase):
def get_arg_types(self):
return None
@@ -210,6 +225,7 @@ class DequeFrontWorker(DequeWorkerBase):
def __call__(self, obj):
return obj['_M_impl']['_M_start']['_M_cur'][0]
+
class DequeBackWorker(DequeWorkerBase):
def get_arg_types(self):
return None
@@ -219,12 +235,13 @@ class DequeBackWorker(DequeWorkerBase):
def __call__(self, obj):
if (obj['_M_impl']['_M_finish']['_M_cur'] ==
- obj['_M_impl']['_M_finish']['_M_first']):
+ obj['_M_impl']['_M_finish']['_M_first']):
prev_node = obj['_M_impl']['_M_finish']['_M_node'] - 1
return prev_node[0][self._bufsize - 1]
else:
return obj['_M_impl']['_M_finish']['_M_cur'][-1]
+
class DequeSubscriptWorker(DequeWorkerBase):
def get_arg_types(self):
return get_std_size_type()
@@ -235,6 +252,7 @@ class DequeSubscriptWorker(DequeWorkerBase):
def __call__(self, obj, subscript):
return self.index(obj, subscript)
+
class DequeAtWorker(DequeWorkerBase):
def get_arg_types(self):
return get_std_size_type()
@@ -248,7 +266,8 @@ class DequeAtWorker(DequeWorkerBase):
raise IndexError('Deque index "%d" should not be >= %d.' %
(int(index), deque_size))
else:
- return self.index(obj, index)
+ return self.index(obj, index)
+
class DequeMethodsMatcher(gdb.xmethod.XMethodMatcher):
def __init__(self):
@@ -274,6 +293,7 @@ class DequeMethodsMatcher(gdb.xmethod.XMethodMatcher):
# Xmethods for std::forward_list
+
class ForwardListWorkerBase(gdb.xmethod.XMethodMatcher):
def __init__(self, val_type, node_type):
self._val_type = val_type
@@ -282,6 +302,7 @@ class ForwardListWorkerBase(gdb.xmethod.XMethodMatcher):
def get_arg_types(self):
return None
+
class ForwardListEmptyWorker(ForwardListWorkerBase):
def get_result_type(self, obj):
return get_bool_type()
@@ -289,6 +310,7 @@ class ForwardListEmptyWorker(ForwardListWorkerBase):
def __call__(self, obj):
return obj['_M_impl']['_M_head']['_M_next'] == 0
+
class ForwardListFrontWorker(ForwardListWorkerBase):
def get_result_type(self, obj):
return self._val_type
@@ -298,6 +320,7 @@ class ForwardListFrontWorker(ForwardListWorkerBase):
val_address = node['_M_storage']['_M_storage'].address
return val_address.cast(self._val_type.pointer()).dereference()
+
class ForwardListMethodsMatcher(gdb.xmethod.XMethodMatcher):
def __init__(self):
matcher_name = matcher_name_prefix + 'forward_list'
@@ -320,6 +343,7 @@ class ForwardListMethodsMatcher(gdb.xmethod.XMethodMatcher):
# Xmethods for std::list
+
class ListWorkerBase(gdb.xmethod.XMethodWorker):
def __init__(self, val_type, node_type):
self._val_type = val_type
@@ -337,6 +361,7 @@ class ListWorkerBase(gdb.xmethod.XMethodWorker):
addr = node['_M_storage'].address
return addr.cast(self._val_type.pointer()).dereference()
+
class ListEmptyWorker(ListWorkerBase):
def get_result_type(self, obj):
return get_bool_type()
@@ -348,6 +373,7 @@ class ListEmptyWorker(ListWorkerBase):
else:
return False
+
class ListSizeWorker(ListWorkerBase):
def get_result_type(self, obj):
return get_std_size_type()
@@ -361,6 +387,7 @@ class ListSizeWorker(ListWorkerBase):
size += 1
return size
+
class ListFrontWorker(ListWorkerBase):
def get_result_type(self, obj):
return self._val_type
@@ -369,6 +396,7 @@ class ListFrontWorker(ListWorkerBase):
node = obj['_M_impl']['_M_node']['_M_next'].cast(self._node_type)
return self.get_value_from_node(node)
+
class ListBackWorker(ListWorkerBase):
def get_result_type(self, obj):
return self._val_type
@@ -377,6 +405,7 @@ class ListBackWorker(ListWorkerBase):
prev_node = obj['_M_impl']['_M_node']['_M_prev'].cast(self._node_type)
return self.get_value_from_node(prev_node)
+
class ListMethodsMatcher(gdb.xmethod.XMethodMatcher):
def __init__(self):
gdb.xmethod.XMethodMatcher.__init__(self,
@@ -401,6 +430,7 @@ class ListMethodsMatcher(gdb.xmethod.XMethodMatcher):
# Xmethods for std::vector
+
class VectorWorkerBase(gdb.xmethod.XMethodWorker):
def __init__(self, val_type):
self._val_type = val_type
@@ -425,6 +455,7 @@ class VectorWorkerBase(gdb.xmethod.XMethodWorker):
else:
return obj['_M_impl']['_M_start'][index]
+
class VectorEmptyWorker(VectorWorkerBase):
def get_arg_types(self):
return None
@@ -435,6 +466,7 @@ class VectorEmptyWorker(VectorWorkerBase):
def __call__(self, obj):
return int(self.size(obj)) == 0
+
class VectorSizeWorker(VectorWorkerBase):
def get_arg_types(self):
return None
@@ -445,6 +477,7 @@ class VectorSizeWorker(VectorWorkerBase):
def __call__(self, obj):
return self.size(obj)
+
class VectorFrontWorker(VectorWorkerBase):
def get_arg_types(self):
return None
@@ -455,6 +488,7 @@ class VectorFrontWorker(VectorWorkerBase):
def __call__(self, obj):
return self.get(obj, 0)
+
class VectorBackWorker(VectorWorkerBase):
def get_arg_types(self):
return None
@@ -465,6 +499,7 @@ class VectorBackWorker(VectorWorkerBase):
def __call__(self, obj):
return self.get(obj, int(self.size(obj)) - 1)
+
class VectorAtWorker(VectorWorkerBase):
def get_arg_types(self):
return get_std_size_type()
@@ -479,6 +514,7 @@ class VectorAtWorker(VectorWorkerBase):
((int(index), size)))
return self.get(obj, int(index))
+
class VectorSubscriptWorker(VectorWorkerBase):
def get_arg_types(self):
return get_std_size_type()
@@ -489,6 +525,7 @@ class VectorSubscriptWorker(VectorWorkerBase):
def __call__(self, obj, subscript):
return self.get(obj, int(subscript))
+
class VectorMethodsMatcher(gdb.xmethod.XMethodMatcher):
def __init__(self):
gdb.xmethod.XMethodMatcher.__init__(self,
@@ -514,6 +551,7 @@ class VectorMethodsMatcher(gdb.xmethod.XMethodMatcher):
# Xmethods for associative containers
+
class AssociativeContainerWorkerBase(gdb.xmethod.XMethodWorker):
def __init__(self, unordered):
self._unordered = unordered
@@ -527,6 +565,7 @@ class AssociativeContainerWorkerBase(gdb.xmethod.XMethodWorker):
def get_arg_types(self):
return None
+
class AssociativeContainerEmptyWorker(AssociativeContainerWorkerBase):
def get_result_type(self, obj):
return get_bool_type()
@@ -534,6 +573,7 @@ class AssociativeContainerEmptyWorker(AssociativeContainerWorkerBase):
def __call__(self, obj):
return int(self.node_count(obj)) == 0
+
class AssociativeContainerSizeWorker(AssociativeContainerWorkerBase):
def get_result_type(self, obj):
return get_std_size_type()
@@ -541,6 +581,7 @@ class AssociativeContainerSizeWorker(AssociativeContainerWorkerBase):
def __call__(self, obj):
return self.node_count(obj)
+
class AssociativeContainerMethodsMatcher(gdb.xmethod.XMethodMatcher):
def __init__(self, name):
gdb.xmethod.XMethodMatcher.__init__(self,
@@ -564,6 +605,7 @@ class AssociativeContainerMethodsMatcher(gdb.xmethod.XMethodMatcher):
# Xmethods for std::unique_ptr
+
class UniquePtrGetWorker(gdb.xmethod.XMethodWorker):
"Implements std::unique_ptr<T>::get() and std::unique_ptr<T>::operator->()"
@@ -593,7 +635,7 @@ class UniquePtrGetWorker(gdb.xmethod.XMethodWorker):
tuple_member = obj['_M_t']
else:
return None
- tuple_impl_type = tuple_member.type.fields()[0].type # _Tuple_impl
+ tuple_impl_type = tuple_member.type.fields()[0].type # _Tuple_impl
tuple_head_type = tuple_impl_type.fields()[1].type # _Head_base
head_field = tuple_head_type.fields()[0]
if head_field.name == '_M_head_impl':
@@ -603,6 +645,7 @@ class UniquePtrGetWorker(gdb.xmethod.XMethodWorker):
else:
return None
+
class UniquePtrDerefWorker(UniquePtrGetWorker):
"Implements std::unique_ptr<T>::operator*()"
@@ -619,6 +662,7 @@ class UniquePtrDerefWorker(UniquePtrGetWorker):
def __call__(self, obj):
return UniquePtrGetWorker.__call__(self, obj).dereference()
+
class UniquePtrSubscriptWorker(UniquePtrGetWorker):
"Implements std::unique_ptr<T>::operator[](size_t)"
@@ -638,6 +682,7 @@ class UniquePtrSubscriptWorker(UniquePtrGetWorker):
def __call__(self, obj, index):
return UniquePtrGetWorker.__call__(self, obj)[index]
+
class UniquePtrMethodsMatcher(gdb.xmethod.XMethodMatcher):
def __init__(self):
gdb.xmethod.XMethodMatcher.__init__(self,
@@ -663,6 +708,7 @@ class UniquePtrMethodsMatcher(gdb.xmethod.XMethodMatcher):
# Xmethods for std::shared_ptr
+
class SharedPtrGetWorker(gdb.xmethod.XMethodWorker):
"Implements std::shared_ptr<T>::get() and std::shared_ptr<T>::operator->()"
@@ -686,6 +732,7 @@ class SharedPtrGetWorker(gdb.xmethod.XMethodWorker):
def __call__(self, obj):
return obj['_M_ptr']
+
class SharedPtrDerefWorker(SharedPtrGetWorker):
"Implements std::shared_ptr<T>::operator*()"
@@ -702,6 +749,7 @@ class SharedPtrDerefWorker(SharedPtrGetWorker):
def __call__(self, obj):
return SharedPtrGetWorker.__call__(self, obj).dereference()
+
class SharedPtrSubscriptWorker(SharedPtrGetWorker):
"Implements std::shared_ptr<T>::operator[](size_t)"
@@ -726,6 +774,7 @@ class SharedPtrSubscriptWorker(SharedPtrGetWorker):
(self._elem_type, int(index), int(m.group(1))))
return SharedPtrGetWorker.__call__(self, obj)[index]
+
class SharedPtrUseCountWorker(gdb.xmethod.XMethodWorker):
"Implements std::shared_ptr<T>::use_count()"
@@ -745,6 +794,7 @@ class SharedPtrUseCountWorker(gdb.xmethod.XMethodWorker):
refcounts = obj['_M_refcount']['_M_pi']
return refcounts['_M_use_count'] if refcounts else 0
+
class SharedPtrUniqueWorker(SharedPtrUseCountWorker):
"Implements std::shared_ptr<T>::unique()"
@@ -757,6 +807,7 @@ class SharedPtrUniqueWorker(SharedPtrUseCountWorker):
def __call__(self, obj):
return SharedPtrUseCountWorker.__call__(self, obj) == 1
+
class SharedPtrMethodsMatcher(gdb.xmethod.XMethodMatcher):
def __init__(self):
gdb.xmethod.XMethodMatcher.__init__(self,
@@ -782,6 +833,7 @@ class SharedPtrMethodsMatcher(gdb.xmethod.XMethodMatcher):
return worker
return None
+
def register_libstdcxx_xmethods(locus):
gdb.xmethod.register_xmethod_matcher(locus, ArrayMethodsMatcher())
gdb.xmethod.register_xmethod_matcher(locus, ForwardListMethodsMatcher())