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