PR libstdc++/86112 fix printers for Python 2.6
[official-gcc.git] / libstdc++-v3 / python / libstdcxx / v6 / printers.py
blob34d8b4e660653f1bf7533a49b96e84b8ec4b5238
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 NodeIteratorPrinter:
253 def __init__(self, typename, val, contname):
254 self.val = val
255 self.typename = typename
256 self.contname = contname
258 def to_string(self):
259 if not self.val['_M_node']:
260 return 'non-dereferenceable iterator for std::%s' % (self.contname)
261 nodetype = find_type(self.val.type, '_Node')
262 nodetype = nodetype.strip_typedefs().pointer()
263 node = self.val['_M_node'].cast(nodetype).dereference()
264 return str(get_value_from_list_node(node))
266 class StdListIteratorPrinter(NodeIteratorPrinter):
267 "Print std::list::iterator"
269 def __init__(self, typename, val):
270 NodeIteratorPrinter.__init__(self, typename, val, 'list')
272 class StdFwdListIteratorPrinter(NodeIteratorPrinter):
273 "Print std::forward_list::iterator"
275 def __init__(self, typename, val):
276 NodeIteratorPrinter.__init__(self, typename, val, 'forward_list')
278 class StdSlistPrinter:
279 "Print a __gnu_cxx::slist"
281 class _iterator(Iterator):
282 def __init__(self, nodetype, head):
283 self.nodetype = nodetype
284 self.base = head['_M_head']['_M_next']
285 self.count = 0
287 def __iter__(self):
288 return self
290 def __next__(self):
291 if self.base == 0:
292 raise StopIteration
293 elt = self.base.cast(self.nodetype).dereference()
294 self.base = elt['_M_next']
295 count = self.count
296 self.count = self.count + 1
297 return ('[%d]' % count, elt['_M_data'])
299 def __init__(self, typename, val):
300 self.val = val
302 def children(self):
303 nodetype = find_type(self.val.type, '_Node')
304 nodetype = nodetype.strip_typedefs().pointer()
305 return self._iterator(nodetype, self.val)
307 def to_string(self):
308 if self.val['_M_head']['_M_next'] == 0:
309 return 'empty __gnu_cxx::slist'
310 return '__gnu_cxx::slist'
312 class StdSlistIteratorPrinter:
313 "Print __gnu_cxx::slist::iterator"
315 def __init__(self, typename, val):
316 self.val = val
318 def to_string(self):
319 if not self.val['_M_node']:
320 return 'non-dereferenceable iterator for __gnu_cxx::slist'
321 nodetype = find_type(self.val.type, '_Node')
322 nodetype = nodetype.strip_typedefs().pointer()
323 return str(self.val['_M_node'].cast(nodetype).dereference()['_M_data'])
325 class StdVectorPrinter:
326 "Print a std::vector"
328 class _iterator(Iterator):
329 def __init__ (self, start, finish, bitvec):
330 self.bitvec = bitvec
331 if bitvec:
332 self.item = start['_M_p']
333 self.so = start['_M_offset']
334 self.finish = finish['_M_p']
335 self.fo = finish['_M_offset']
336 itype = self.item.dereference().type
337 self.isize = 8 * itype.sizeof
338 else:
339 self.item = start
340 self.finish = finish
341 self.count = 0
343 def __iter__(self):
344 return self
346 def __next__(self):
347 count = self.count
348 self.count = self.count + 1
349 if self.bitvec:
350 if self.item == self.finish and self.so >= self.fo:
351 raise StopIteration
352 elt = self.item.dereference()
353 if elt & (1 << self.so):
354 obit = 1
355 else:
356 obit = 0
357 self.so = self.so + 1
358 if self.so >= self.isize:
359 self.item = self.item + 1
360 self.so = 0
361 return ('[%d]' % count, obit)
362 else:
363 if self.item == self.finish:
364 raise StopIteration
365 elt = self.item.dereference()
366 self.item = self.item + 1
367 return ('[%d]' % count, elt)
369 def __init__(self, typename, val):
370 self.typename = strip_versioned_namespace(typename)
371 self.val = val
372 self.is_bool = val.type.template_argument(0).code == gdb.TYPE_CODE_BOOL
374 def children(self):
375 return self._iterator(self.val['_M_impl']['_M_start'],
376 self.val['_M_impl']['_M_finish'],
377 self.is_bool)
379 def to_string(self):
380 start = self.val['_M_impl']['_M_start']
381 finish = self.val['_M_impl']['_M_finish']
382 end = self.val['_M_impl']['_M_end_of_storage']
383 if self.is_bool:
384 start = self.val['_M_impl']['_M_start']['_M_p']
385 so = self.val['_M_impl']['_M_start']['_M_offset']
386 finish = self.val['_M_impl']['_M_finish']['_M_p']
387 fo = self.val['_M_impl']['_M_finish']['_M_offset']
388 itype = start.dereference().type
389 bl = 8 * itype.sizeof
390 length = (bl - so) + bl * ((finish - start) - 1) + fo
391 capacity = bl * (end - start)
392 return ('%s<bool> of length %d, capacity %d'
393 % (self.typename, int (length), int (capacity)))
394 else:
395 return ('%s of length %d, capacity %d'
396 % (self.typename, int (finish - start), int (end - start)))
398 def display_hint(self):
399 return 'array'
401 class StdVectorIteratorPrinter:
402 "Print std::vector::iterator"
404 def __init__(self, typename, val):
405 self.val = val
407 def to_string(self):
408 if not self.val['_M_current']:
409 return 'non-dereferenceable iterator for std::vector'
410 return str(self.val['_M_current'].dereference())
412 class StdTuplePrinter:
413 "Print a std::tuple"
415 class _iterator(Iterator):
416 def __init__ (self, head):
417 self.head = head
419 # Set the base class as the initial head of the
420 # tuple.
421 nodes = self.head.type.fields ()
422 if len (nodes) == 1:
423 # Set the actual head to the first pair.
424 self.head = self.head.cast (nodes[0].type)
425 elif len (nodes) != 0:
426 raise ValueError("Top of tuple tree does not consist of a single node.")
427 self.count = 0
429 def __iter__ (self):
430 return self
432 def __next__ (self):
433 # Check for further recursions in the inheritance tree.
434 # For a GCC 5+ tuple self.head is None after visiting all nodes:
435 if not self.head:
436 raise StopIteration
437 nodes = self.head.type.fields ()
438 # For a GCC 4.x tuple there is a final node with no fields:
439 if len (nodes) == 0:
440 raise StopIteration
441 # Check that this iteration has an expected structure.
442 if len (nodes) > 2:
443 raise ValueError("Cannot parse more than 2 nodes in a tuple tree.")
445 if len (nodes) == 1:
446 # This is the last node of a GCC 5+ std::tuple.
447 impl = self.head.cast (nodes[0].type)
448 self.head = None
449 else:
450 # Either a node before the last node, or the last node of
451 # a GCC 4.x tuple (which has an empty parent).
453 # - Left node is the next recursion parent.
454 # - Right node is the actual class contained in the tuple.
456 # Process right node.
457 impl = self.head.cast (nodes[1].type)
459 # Process left node and set it as head.
460 self.head = self.head.cast (nodes[0].type)
462 self.count = self.count + 1
464 # Finally, check the implementation. If it is
465 # wrapped in _M_head_impl return that, otherwise return
466 # the value "as is".
467 fields = impl.type.fields ()
468 if len (fields) < 1 or fields[0].name != "_M_head_impl":
469 return ('[%d]' % self.count, impl)
470 else:
471 return ('[%d]' % self.count, impl['_M_head_impl'])
473 def __init__ (self, typename, val):
474 self.typename = strip_versioned_namespace(typename)
475 self.val = val;
477 def children (self):
478 return self._iterator (self.val)
480 def to_string (self):
481 if len (self.val.type.fields ()) == 0:
482 return 'empty %s' % (self.typename)
483 return '%s containing' % (self.typename)
485 class StdStackOrQueuePrinter:
486 "Print a std::stack or std::queue"
488 def __init__ (self, typename, val):
489 self.typename = strip_versioned_namespace(typename)
490 self.visualizer = gdb.default_visualizer(val['c'])
492 def children (self):
493 return self.visualizer.children()
495 def to_string (self):
496 return '%s wrapping: %s' % (self.typename,
497 self.visualizer.to_string())
499 def display_hint (self):
500 if hasattr (self.visualizer, 'display_hint'):
501 return self.visualizer.display_hint ()
502 return None
504 class RbtreeIterator(Iterator):
506 Turn an RB-tree-based container (std::map, std::set etc.) into
507 a Python iterable object.
510 def __init__(self, rbtree):
511 self.size = rbtree['_M_t']['_M_impl']['_M_node_count']
512 self.node = rbtree['_M_t']['_M_impl']['_M_header']['_M_left']
513 self.count = 0
515 def __iter__(self):
516 return self
518 def __len__(self):
519 return int (self.size)
521 def __next__(self):
522 if self.count == self.size:
523 raise StopIteration
524 result = self.node
525 self.count = self.count + 1
526 if self.count < self.size:
527 # Compute the next node.
528 node = self.node
529 if node.dereference()['_M_right']:
530 node = node.dereference()['_M_right']
531 while node.dereference()['_M_left']:
532 node = node.dereference()['_M_left']
533 else:
534 parent = node.dereference()['_M_parent']
535 while node == parent.dereference()['_M_right']:
536 node = parent
537 parent = parent.dereference()['_M_parent']
538 if node.dereference()['_M_right'] != parent:
539 node = parent
540 self.node = node
541 return result
543 def get_value_from_Rb_tree_node(node):
544 """Returns the value held in an _Rb_tree_node<_Val>"""
545 try:
546 member = node.type.fields()[1].name
547 if member == '_M_value_field':
548 # C++03 implementation, node contains the value as a member
549 return node['_M_value_field']
550 elif member == '_M_storage':
551 # C++11 implementation, node stores value in __aligned_membuf
552 valtype = node.type.template_argument(0)
553 return get_value_from_aligned_membuf(node['_M_storage'], valtype)
554 except:
555 pass
556 raise ValueError("Unsupported implementation for %s" % str(node.type))
558 # This is a pretty printer for std::_Rb_tree_iterator (which is
559 # std::map::iterator), and has nothing to do with the RbtreeIterator
560 # class above.
561 class StdRbtreeIteratorPrinter:
562 "Print std::map::iterator, std::set::iterator, etc."
564 def __init__ (self, typename, val):
565 self.val = val
566 valtype = self.val.type.template_argument(0).strip_typedefs()
567 nodetype = '_Rb_tree_node<' + str(valtype) + '>'
568 if _versioned_namespace and typename.startswith('std::' + _versioned_namespace):
569 nodetype = _versioned_namespace + nodetype
570 nodetype = gdb.lookup_type('std::' + nodetype)
571 self.link_type = nodetype.strip_typedefs().pointer()
573 def to_string (self):
574 if not self.val['_M_node']:
575 return 'non-dereferenceable iterator for associative container'
576 node = self.val['_M_node'].cast(self.link_type).dereference()
577 return str(get_value_from_Rb_tree_node(node))
579 class StdDebugIteratorPrinter:
580 "Print a debug enabled version of an iterator"
582 def __init__ (self, typename, val):
583 self.val = val
585 # Just strip away the encapsulating __gnu_debug::_Safe_iterator
586 # and return the wrapped iterator value.
587 def to_string (self):
588 base_type = gdb.lookup_type('__gnu_debug::_Safe_iterator_base')
589 itype = self.val.type.template_argument(0)
590 safe_seq = self.val.cast(base_type)['_M_sequence']
591 if not safe_seq:
592 return str(self.val.cast(itype))
593 if self.val['_M_version'] != safe_seq['_M_version']:
594 return "invalid iterator"
595 return str(self.val.cast(itype))
597 def num_elements(num):
598 """Return either "1 element" or "N elements" depending on the argument."""
599 return '1 element' if num == 1 else '%d elements' % num
601 class StdMapPrinter:
602 "Print a std::map or std::multimap"
604 # Turn an RbtreeIterator into a pretty-print iterator.
605 class _iter(Iterator):
606 def __init__(self, rbiter, type):
607 self.rbiter = rbiter
608 self.count = 0
609 self.type = type
611 def __iter__(self):
612 return self
614 def __next__(self):
615 if self.count % 2 == 0:
616 n = next(self.rbiter)
617 n = n.cast(self.type).dereference()
618 n = get_value_from_Rb_tree_node(n)
619 self.pair = n
620 item = n['first']
621 else:
622 item = self.pair['second']
623 result = ('[%d]' % self.count, item)
624 self.count = self.count + 1
625 return result
627 def __init__ (self, typename, val):
628 self.typename = strip_versioned_namespace(typename)
629 self.val = val
631 def to_string (self):
632 return '%s with %s' % (self.typename,
633 num_elements(len(RbtreeIterator (self.val))))
635 def children (self):
636 rep_type = find_type(self.val.type, '_Rep_type')
637 node = find_type(rep_type, '_Link_type')
638 node = node.strip_typedefs()
639 return self._iter (RbtreeIterator (self.val), node)
641 def display_hint (self):
642 return 'map'
644 class StdSetPrinter:
645 "Print a std::set or std::multiset"
647 # Turn an RbtreeIterator into a pretty-print iterator.
648 class _iter(Iterator):
649 def __init__(self, rbiter, type):
650 self.rbiter = rbiter
651 self.count = 0
652 self.type = type
654 def __iter__(self):
655 return self
657 def __next__(self):
658 item = next(self.rbiter)
659 item = item.cast(self.type).dereference()
660 item = get_value_from_Rb_tree_node(item)
661 # FIXME: this is weird ... what to do?
662 # Maybe a 'set' display hint?
663 result = ('[%d]' % self.count, item)
664 self.count = self.count + 1
665 return result
667 def __init__ (self, typename, val):
668 self.typename = strip_versioned_namespace(typename)
669 self.val = val
671 def to_string (self):
672 return '%s with %s' % (self.typename,
673 num_elements(len(RbtreeIterator (self.val))))
675 def children (self):
676 rep_type = find_type(self.val.type, '_Rep_type')
677 node = find_type(rep_type, '_Link_type')
678 node = node.strip_typedefs()
679 return self._iter (RbtreeIterator (self.val), node)
681 class StdBitsetPrinter:
682 "Print a std::bitset"
684 def __init__(self, typename, val):
685 self.typename = strip_versioned_namespace(typename)
686 self.val = val
688 def to_string (self):
689 # If template_argument handled values, we could print the
690 # size. Or we could use a regexp on the type.
691 return '%s' % (self.typename)
693 def children (self):
694 words = self.val['_M_w']
695 wtype = words.type
697 # The _M_w member can be either an unsigned long, or an
698 # array. This depends on the template specialization used.
699 # If it is a single long, convert to a single element list.
700 if wtype.code == gdb.TYPE_CODE_ARRAY:
701 tsize = wtype.target ().sizeof
702 else:
703 words = [words]
704 tsize = wtype.sizeof
706 nwords = wtype.sizeof / tsize
707 result = []
708 byte = 0
709 while byte < nwords:
710 w = words[byte]
711 bit = 0
712 while w != 0:
713 if (w & 1) != 0:
714 # Another spot where we could use 'set'?
715 result.append(('[%d]' % (byte * tsize * 8 + bit), 1))
716 bit = bit + 1
717 w = w >> 1
718 byte = byte + 1
719 return result
721 class StdDequePrinter:
722 "Print a std::deque"
724 class _iter(Iterator):
725 def __init__(self, node, start, end, last, buffer_size):
726 self.node = node
727 self.p = start
728 self.end = end
729 self.last = last
730 self.buffer_size = buffer_size
731 self.count = 0
733 def __iter__(self):
734 return self
736 def __next__(self):
737 if self.p == self.last:
738 raise StopIteration
740 result = ('[%d]' % self.count, self.p.dereference())
741 self.count = self.count + 1
743 # Advance the 'cur' pointer.
744 self.p = self.p + 1
745 if self.p == self.end:
746 # If we got to the end of this bucket, move to the
747 # next bucket.
748 self.node = self.node + 1
749 self.p = self.node[0]
750 self.end = self.p + self.buffer_size
752 return result
754 def __init__(self, typename, val):
755 self.typename = strip_versioned_namespace(typename)
756 self.val = val
757 self.elttype = val.type.template_argument(0)
758 size = self.elttype.sizeof
759 if size < 512:
760 self.buffer_size = int (512 / size)
761 else:
762 self.buffer_size = 1
764 def to_string(self):
765 start = self.val['_M_impl']['_M_start']
766 end = self.val['_M_impl']['_M_finish']
768 delta_n = end['_M_node'] - start['_M_node'] - 1
769 delta_s = start['_M_last'] - start['_M_cur']
770 delta_e = end['_M_cur'] - end['_M_first']
772 size = self.buffer_size * delta_n + delta_s + delta_e
774 return '%s with %s' % (self.typename, num_elements(long(size)))
776 def children(self):
777 start = self.val['_M_impl']['_M_start']
778 end = self.val['_M_impl']['_M_finish']
779 return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
780 end['_M_cur'], self.buffer_size)
782 def display_hint (self):
783 return 'array'
785 class StdDequeIteratorPrinter:
786 "Print std::deque::iterator"
788 def __init__(self, typename, val):
789 self.val = val
791 def to_string(self):
792 if not self.val['_M_cur']:
793 return 'non-dereferenceable iterator for std::deque'
794 return str(self.val['_M_cur'].dereference())
796 class StdStringPrinter:
797 "Print a std::basic_string of some kind"
799 def __init__(self, typename, val):
800 self.val = val
801 self.new_string = typename.find("::__cxx11::basic_string") != -1
803 def to_string(self):
804 # Make sure &string works, too.
805 type = self.val.type
806 if type.code == gdb.TYPE_CODE_REF:
807 type = type.target ()
809 # Calculate the length of the string so that to_string returns
810 # the string according to length, not according to first null
811 # encountered.
812 ptr = self.val ['_M_dataplus']['_M_p']
813 if self.new_string:
814 length = self.val['_M_string_length']
815 # https://sourceware.org/bugzilla/show_bug.cgi?id=17728
816 ptr = ptr.cast(ptr.type.strip_typedefs())
817 else:
818 realtype = type.unqualified ().strip_typedefs ()
819 reptype = gdb.lookup_type (str (realtype) + '::_Rep').pointer ()
820 header = ptr.cast(reptype) - 1
821 length = header.dereference ()['_M_length']
822 if hasattr(ptr, "lazy_string"):
823 return ptr.lazy_string (length = length)
824 return ptr.string (length = length)
826 def display_hint (self):
827 return 'string'
829 class Tr1HashtableIterator(Iterator):
830 def __init__ (self, hash):
831 self.buckets = hash['_M_buckets']
832 self.bucket = 0
833 self.bucket_count = hash['_M_bucket_count']
834 self.node_type = find_type(hash.type, '_Node').pointer()
835 self.node = 0
836 while self.bucket != self.bucket_count:
837 self.node = self.buckets[self.bucket]
838 if self.node:
839 break
840 self.bucket = self.bucket + 1
842 def __iter__ (self):
843 return self
845 def __next__ (self):
846 if self.node == 0:
847 raise StopIteration
848 node = self.node.cast(self.node_type)
849 result = node.dereference()['_M_v']
850 self.node = node.dereference()['_M_next'];
851 if self.node == 0:
852 self.bucket = self.bucket + 1
853 while self.bucket != self.bucket_count:
854 self.node = self.buckets[self.bucket]
855 if self.node:
856 break
857 self.bucket = self.bucket + 1
858 return result
860 class StdHashtableIterator(Iterator):
861 def __init__(self, hash):
862 self.node = hash['_M_before_begin']['_M_nxt']
863 self.node_type = find_type(hash.type, '__node_type').pointer()
865 def __iter__(self):
866 return self
868 def __next__(self):
869 if self.node == 0:
870 raise StopIteration
871 elt = self.node.cast(self.node_type).dereference()
872 self.node = elt['_M_nxt']
873 valptr = elt['_M_storage'].address
874 valptr = valptr.cast(elt.type.template_argument(0).pointer())
875 return valptr.dereference()
877 class Tr1UnorderedSetPrinter:
878 "Print a tr1::unordered_set"
880 def __init__ (self, typename, val):
881 self.typename = strip_versioned_namespace(typename)
882 self.val = val
884 def hashtable (self):
885 if self.typename.startswith('std::tr1'):
886 return self.val
887 return self.val['_M_h']
889 def to_string (self):
890 count = self.hashtable()['_M_element_count']
891 return '%s with %s' % (self.typename, num_elements(count))
893 @staticmethod
894 def format_count (i):
895 return '[%d]' % i
897 def children (self):
898 counter = imap (self.format_count, itertools.count())
899 if self.typename.startswith('std::tr1'):
900 return izip (counter, Tr1HashtableIterator (self.hashtable()))
901 return izip (counter, StdHashtableIterator (self.hashtable()))
903 class Tr1UnorderedMapPrinter:
904 "Print a tr1::unordered_map"
906 def __init__ (self, typename, val):
907 self.typename = strip_versioned_namespace(typename)
908 self.val = val
910 def hashtable (self):
911 if self.typename.startswith('std::tr1'):
912 return self.val
913 return self.val['_M_h']
915 def to_string (self):
916 count = self.hashtable()['_M_element_count']
917 return '%s with %s' % (self.typename, num_elements(count))
919 @staticmethod
920 def flatten (list):
921 for elt in list:
922 for i in elt:
923 yield i
925 @staticmethod
926 def format_one (elt):
927 return (elt['first'], elt['second'])
929 @staticmethod
930 def format_count (i):
931 return '[%d]' % i
933 def children (self):
934 counter = imap (self.format_count, itertools.count())
935 # Map over the hash table and flatten the result.
936 if self.typename.startswith('std::tr1'):
937 data = self.flatten (imap (self.format_one, Tr1HashtableIterator (self.hashtable())))
938 # Zip the two iterators together.
939 return izip (counter, data)
940 data = self.flatten (imap (self.format_one, StdHashtableIterator (self.hashtable())))
941 # Zip the two iterators together.
942 return izip (counter, data)
945 def display_hint (self):
946 return 'map'
948 class StdForwardListPrinter:
949 "Print a std::forward_list"
951 class _iterator(Iterator):
952 def __init__(self, nodetype, head):
953 self.nodetype = nodetype
954 self.base = head['_M_next']
955 self.count = 0
957 def __iter__(self):
958 return self
960 def __next__(self):
961 if self.base == 0:
962 raise StopIteration
963 elt = self.base.cast(self.nodetype).dereference()
964 self.base = elt['_M_next']
965 count = self.count
966 self.count = self.count + 1
967 valptr = elt['_M_storage'].address
968 valptr = valptr.cast(elt.type.template_argument(0).pointer())
969 return ('[%d]' % count, valptr.dereference())
971 def __init__(self, typename, val):
972 self.val = val
973 self.typename = strip_versioned_namespace(typename)
975 def children(self):
976 nodetype = find_type(self.val.type, '_Node')
977 nodetype = nodetype.strip_typedefs().pointer()
978 return self._iterator(nodetype, self.val['_M_impl']['_M_head'])
980 def to_string(self):
981 if self.val['_M_impl']['_M_head']['_M_next'] == 0:
982 return 'empty %s' % self.typename
983 return '%s' % self.typename
985 class SingleObjContainerPrinter(object):
986 "Base class for printers of containers of single objects"
988 def __init__ (self, val, viz, hint = None):
989 self.contained_value = val
990 self.visualizer = viz
991 self.hint = hint
993 def _recognize(self, type):
994 """Return TYPE as a string after applying type printers"""
995 global _use_type_printing
996 if not _use_type_printing:
997 return str(type)
998 return gdb.types.apply_type_recognizers(gdb.types.get_type_recognizers(),
999 type) or str(type)
1001 class _contained(Iterator):
1002 def __init__ (self, val):
1003 self.val = val
1005 def __iter__ (self):
1006 return self
1008 def __next__(self):
1009 if self.val is None:
1010 raise StopIteration
1011 retval = self.val
1012 self.val = None
1013 return ('[contained value]', retval)
1015 def children (self):
1016 if self.contained_value is None:
1017 return self._contained (None)
1018 if hasattr (self.visualizer, 'children'):
1019 return self.visualizer.children ()
1020 return self._contained (self.contained_value)
1022 def display_hint (self):
1023 # if contained value is a map we want to display in the same way
1024 if hasattr (self.visualizer, 'children') and hasattr (self.visualizer, 'display_hint'):
1025 return self.visualizer.display_hint ()
1026 return self.hint
1028 class StdExpAnyPrinter(SingleObjContainerPrinter):
1029 "Print a std::any or std::experimental::any"
1031 def __init__ (self, typename, val):
1032 self.typename = strip_versioned_namespace(typename)
1033 self.typename = re.sub('^std::experimental::fundamentals_v\d::', 'std::experimental::', self.typename, 1)
1034 self.val = val
1035 self.contained_type = None
1036 contained_value = None
1037 visualizer = None
1038 mgr = self.val['_M_manager']
1039 if mgr != 0:
1040 func = gdb.block_for_pc(int(mgr.cast(gdb.lookup_type('intptr_t'))))
1041 if not func:
1042 raise ValueError("Invalid function pointer in %s" % self.typename)
1043 rx = r"""({0}::_Manager_\w+<.*>)::_S_manage\({0}::_Op, {0} const\*, {0}::_Arg\*\)""".format(typename)
1044 m = re.match(rx, func.function.name)
1045 if not m:
1046 raise ValueError("Unknown manager function in %s" % self.typename)
1048 mgrname = m.group(1)
1049 # FIXME need to expand 'std::string' so that gdb.lookup_type works
1050 if 'std::string' in mgrname:
1051 mgrname = re.sub("std::string(?!\w)", str(gdb.lookup_type('std::string').strip_typedefs()), m.group(1))
1053 mgrtype = gdb.lookup_type(mgrname)
1054 self.contained_type = mgrtype.template_argument(0)
1055 valptr = None
1056 if '::_Manager_internal' in mgrname:
1057 valptr = self.val['_M_storage']['_M_buffer'].address
1058 elif '::_Manager_external' in mgrname:
1059 valptr = self.val['_M_storage']['_M_ptr']
1060 else:
1061 raise ValueError("Unknown manager function in %s" % self.typename)
1062 contained_value = valptr.cast(self.contained_type.pointer()).dereference()
1063 visualizer = gdb.default_visualizer(contained_value)
1064 super(StdExpAnyPrinter, self).__init__ (contained_value, visualizer)
1066 def to_string (self):
1067 if self.contained_type is None:
1068 return '%s [no contained value]' % self.typename
1069 desc = "%s containing " % self.typename
1070 if hasattr (self.visualizer, 'children'):
1071 return desc + self.visualizer.to_string ()
1072 valtype = self._recognize (self.contained_type)
1073 return desc + strip_versioned_namespace(str(valtype))
1075 class StdExpOptionalPrinter(SingleObjContainerPrinter):
1076 "Print a std::optional or std::experimental::optional"
1078 def __init__ (self, typename, val):
1079 valtype = self._recognize (val.type.template_argument(0))
1080 self.typename = strip_versioned_namespace(typename)
1081 self.typename = re.sub('^std::(experimental::|)(fundamentals_v\d::|)(.*)', r'std::\1\3<%s>' % valtype, self.typename, 1)
1082 if not self.typename.startswith('std::experimental'):
1083 val = val['_M_payload']
1084 self.val = val
1085 contained_value = val['_M_payload'] if self.val['_M_engaged'] else None
1086 visualizer = gdb.default_visualizer (val['_M_payload'])
1087 super (StdExpOptionalPrinter, self).__init__ (contained_value, visualizer)
1089 def to_string (self):
1090 if self.contained_value is None:
1091 return "%s [no contained value]" % self.typename
1092 if hasattr (self.visualizer, 'children'):
1093 return "%s containing %s" % (self.typename,
1094 self.visualizer.to_string())
1095 return self.typename
1097 class StdVariantPrinter(SingleObjContainerPrinter):
1098 "Print a std::variant"
1100 def __init__(self, typename, val):
1101 alternatives = get_template_arg_list(val.type)
1102 self.typename = strip_versioned_namespace(typename)
1103 self.typename = "%s<%s>" % (self.typename, ', '.join([self._recognize(alt) for alt in alternatives]))
1104 self.index = val['_M_index']
1105 if self.index >= len(alternatives):
1106 self.contained_type = None
1107 contained_value = None
1108 visualizer = None
1109 else:
1110 self.contained_type = alternatives[int(self.index)]
1111 addr = val['_M_u']['_M_first']['_M_storage'].address
1112 contained_value = addr.cast(self.contained_type.pointer()).dereference()
1113 visualizer = gdb.default_visualizer(contained_value)
1114 super (StdVariantPrinter, self).__init__(contained_value, visualizer, 'array')
1116 def to_string(self):
1117 if self.contained_value is None:
1118 return "%s [no contained value]" % self.typename
1119 if hasattr(self.visualizer, 'children'):
1120 return "%s [index %d] containing %s" % (self.typename, self.index,
1121 self.visualizer.to_string())
1122 return "%s [index %d]" % (self.typename, self.index)
1124 class StdNodeHandlePrinter(SingleObjContainerPrinter):
1125 "Print a container node handle"
1127 def __init__(self, typename, val):
1128 self.value_type = val.type.template_argument(1)
1129 nodetype = val.type.template_argument(2).template_argument(0)
1130 self.is_rb_tree_node = is_specialization_of(nodetype.name, '_Rb_tree_node')
1131 self.is_map_node = val.type.template_argument(0) != self.value_type
1132 nodeptr = val['_M_ptr']
1133 if nodeptr:
1134 if self.is_rb_tree_node:
1135 contained_value = get_value_from_Rb_tree_node(nodeptr.dereference())
1136 else:
1137 contained_value = get_value_from_aligned_membuf(nodeptr['_M_storage'],
1138 self.value_type)
1139 visualizer = gdb.default_visualizer(contained_value)
1140 else:
1141 contained_value = None
1142 visualizer = None
1143 optalloc = val['_M_alloc']
1144 self.alloc = optalloc['_M_payload'] if optalloc['_M_engaged'] else None
1145 super(StdNodeHandlePrinter, self).__init__(contained_value, visualizer,
1146 'array')
1148 def to_string(self):
1149 desc = 'node handle for '
1150 if not self.is_rb_tree_node:
1151 desc += 'unordered '
1152 if self.is_map_node:
1153 desc += 'map';
1154 else:
1155 desc += 'set';
1157 if self.contained_value:
1158 desc += ' with element'
1159 if hasattr(self.visualizer, 'children'):
1160 return "%s = %s" % (desc, self.visualizer.to_string())
1161 return desc
1162 else:
1163 return 'empty %s' % desc
1165 class StdExpStringViewPrinter:
1166 "Print a std::basic_string_view or std::experimental::basic_string_view"
1168 def __init__ (self, typename, val):
1169 self.val = val
1171 def to_string (self):
1172 ptr = self.val['_M_str']
1173 len = self.val['_M_len']
1174 if hasattr (ptr, "lazy_string"):
1175 return ptr.lazy_string (length = len)
1176 return ptr.string (length = len)
1178 def display_hint (self):
1179 return 'string'
1181 class StdExpPathPrinter:
1182 "Print a std::experimental::filesystem::path"
1184 def __init__ (self, typename, val):
1185 self.val = val
1186 start = self.val['_M_cmpts']['_M_impl']['_M_start']
1187 finish = self.val['_M_cmpts']['_M_impl']['_M_finish']
1188 self.num_cmpts = int (finish - start)
1190 def _path_type(self):
1191 t = str(self.val['_M_type'])
1192 if t[-9:] == '_Root_dir':
1193 return "root-directory"
1194 if t[-10:] == '_Root_name':
1195 return "root-name"
1196 return None
1198 def to_string (self):
1199 path = "%s" % self.val ['_M_pathname']
1200 if self.num_cmpts == 0:
1201 t = self._path_type()
1202 if t:
1203 path = '%s [%s]' % (path, t)
1204 return "filesystem::path %s" % path
1206 class _iterator(Iterator):
1207 def __init__(self, cmpts):
1208 self.item = cmpts['_M_impl']['_M_start']
1209 self.finish = cmpts['_M_impl']['_M_finish']
1210 self.count = 0
1212 def __iter__(self):
1213 return self
1215 def __next__(self):
1216 if self.item == self.finish:
1217 raise StopIteration
1218 item = self.item.dereference()
1219 count = self.count
1220 self.count = self.count + 1
1221 self.item = self.item + 1
1222 path = item['_M_pathname']
1223 t = StdExpPathPrinter(item.type.name, item)._path_type()
1224 if not t:
1225 t = count
1226 return ('[%s]' % t, path)
1228 def children(self):
1229 return self._iterator(self.val['_M_cmpts'])
1232 # A "regular expression" printer which conforms to the
1233 # "SubPrettyPrinter" protocol from gdb.printing.
1234 class RxPrinter(object):
1235 def __init__(self, name, function):
1236 super(RxPrinter, self).__init__()
1237 self.name = name
1238 self.function = function
1239 self.enabled = True
1241 def invoke(self, value):
1242 if not self.enabled:
1243 return None
1245 if value.type.code == gdb.TYPE_CODE_REF:
1246 if hasattr(gdb.Value,"referenced_value"):
1247 value = value.referenced_value()
1249 return self.function(self.name, value)
1251 # A pretty-printer that conforms to the "PrettyPrinter" protocol from
1252 # gdb.printing. It can also be used directly as an old-style printer.
1253 class Printer(object):
1254 def __init__(self, name):
1255 super(Printer, self).__init__()
1256 self.name = name
1257 self.subprinters = []
1258 self.lookup = {}
1259 self.enabled = True
1260 self.compiled_rx = re.compile('^([a-zA-Z0-9_:]+)(<.*>)?$')
1262 def add(self, name, function):
1263 # A small sanity check.
1264 # FIXME
1265 if not self.compiled_rx.match(name):
1266 raise ValueError('libstdc++ programming error: "%s" does not match' % name)
1267 printer = RxPrinter(name, function)
1268 self.subprinters.append(printer)
1269 self.lookup[name] = printer
1271 # Add a name using _GLIBCXX_BEGIN_NAMESPACE_VERSION.
1272 def add_version(self, base, name, function):
1273 self.add(base + name, function)
1274 if _versioned_namespace:
1275 vbase = re.sub('^(std|__gnu_cxx)::', r'\g<0>%s' % _versioned_namespace, base)
1276 self.add(vbase + name, function)
1278 # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
1279 def add_container(self, base, name, function):
1280 self.add_version(base, name, function)
1281 self.add_version(base + '__cxx1998::', name, function)
1283 @staticmethod
1284 def get_basic_type(type):
1285 # If it points to a reference, get the reference.
1286 if type.code == gdb.TYPE_CODE_REF:
1287 type = type.target ()
1289 # Get the unqualified type, stripped of typedefs.
1290 type = type.unqualified ().strip_typedefs ()
1292 return type.tag
1294 def __call__(self, val):
1295 typename = self.get_basic_type(val.type)
1296 if not typename:
1297 return None
1299 # All the types we match are template types, so we can use a
1300 # dictionary.
1301 match = self.compiled_rx.match(typename)
1302 if not match:
1303 return None
1305 basename = match.group(1)
1307 if val.type.code == gdb.TYPE_CODE_REF:
1308 if hasattr(gdb.Value,"referenced_value"):
1309 val = val.referenced_value()
1311 if basename in self.lookup:
1312 return self.lookup[basename].invoke(val)
1314 # Cannot find a pretty printer. Return None.
1315 return None
1317 libstdcxx_printer = None
1319 class TemplateTypePrinter(object):
1320 r"""
1321 A type printer for class templates with default template arguments.
1323 Recognizes specializations of class templates and prints them without
1324 any template arguments that use a default template argument.
1325 Type printers are recursively applied to the template arguments.
1327 e.g. replace "std::vector<T, std::allocator<T> >" with "std::vector<T>".
1330 def __init__(self, name, defargs):
1331 self.name = name
1332 self.defargs = defargs
1333 self.enabled = True
1335 class _recognizer(object):
1336 "The recognizer class for TemplateTypePrinter."
1338 def __init__(self, name, defargs):
1339 self.name = name
1340 self.defargs = defargs
1341 # self.type_obj = None
1343 def recognize(self, type_obj):
1345 If type_obj is a specialization of self.name that uses all the
1346 default template arguments for the class template, then return
1347 a string representation of the type without default arguments.
1348 Otherwise, return None.
1351 if type_obj.tag is None:
1352 return None
1354 if not type_obj.tag.startswith(self.name):
1355 return None
1357 template_args = get_template_arg_list(type_obj)
1358 displayed_args = []
1359 require_defaulted = False
1360 for n in range(len(template_args)):
1361 # The actual template argument in the type:
1362 targ = template_args[n]
1363 # The default template argument for the class template:
1364 defarg = self.defargs.get(n)
1365 if defarg is not None:
1366 # Substitute other template arguments into the default:
1367 defarg = defarg.format(*template_args)
1368 # Fail to recognize the type (by returning None)
1369 # unless the actual argument is the same as the default.
1370 try:
1371 if targ != gdb.lookup_type(defarg):
1372 return None
1373 except gdb.error:
1374 # Type lookup failed, just use string comparison:
1375 if targ.tag != defarg:
1376 return None
1377 # All subsequent args must have defaults:
1378 require_defaulted = True
1379 elif require_defaulted:
1380 return None
1381 else:
1382 # Recursively apply recognizers to the template argument
1383 # and add it to the arguments that will be displayed:
1384 displayed_args.append(self._recognize_subtype(targ))
1386 # This assumes no class templates in the nested-name-specifier:
1387 template_name = type_obj.tag[0:type_obj.tag.find('<')]
1388 template_name = strip_inline_namespaces(template_name)
1390 return template_name + '<' + ', '.join(displayed_args) + '>'
1392 def _recognize_subtype(self, type_obj):
1393 """Convert a gdb.Type to a string by applying recognizers,
1394 or if that fails then simply converting to a string."""
1396 if type_obj.code == gdb.TYPE_CODE_PTR:
1397 return self._recognize_subtype(type_obj.target()) + '*'
1398 if type_obj.code == gdb.TYPE_CODE_ARRAY:
1399 type_str = self._recognize_subtype(type_obj.target())
1400 if str(type_obj.strip_typedefs()).endswith('[]'):
1401 return type_str + '[]' # array of unknown bound
1402 return "%s[%d]" % (type_str, type_obj.range()[1] + 1)
1403 if type_obj.code == gdb.TYPE_CODE_REF:
1404 return self._recognize_subtype(type_obj.target()) + '&'
1405 if hasattr(gdb, 'TYPE_CODE_RVALUE_REF'):
1406 if type_obj.code == gdb.TYPE_CODE_RVALUE_REF:
1407 return self._recognize_subtype(type_obj.target()) + '&&'
1409 type_str = gdb.types.apply_type_recognizers(
1410 gdb.types.get_type_recognizers(), type_obj)
1411 if type_str:
1412 return type_str
1413 return str(type_obj)
1415 def instantiate(self):
1416 "Return a recognizer object for this type printer."
1417 return self._recognizer(self.name, self.defargs)
1419 def add_one_template_type_printer(obj, name, defargs):
1420 r"""
1421 Add a type printer for a class template with default template arguments.
1423 Args:
1424 name (str): The template-name of the class template.
1425 defargs (dict int:string) The default template arguments.
1427 Types in defargs can refer to the Nth template-argument using {N}
1428 (with zero-based indices).
1430 e.g. 'unordered_map' has these defargs:
1431 { 2: 'std::hash<{0}>',
1432 3: 'std::equal_to<{0}>',
1433 4: 'std::allocator<std::pair<const {0}, {1}> >' }
1436 printer = TemplateTypePrinter('std::'+name, defargs)
1437 gdb.types.register_type_printer(obj, printer)
1438 if _versioned_namespace:
1439 # Add second type printer for same type in versioned namespace:
1440 ns = 'std::' + _versioned_namespace
1441 # PR 86112 Cannot use dict comprehension here:
1442 defargs = dict((n, d.replace('std::', ns)) for (n,d) in defargs.items())
1443 printer = TemplateTypePrinter(ns+name, defargs)
1444 gdb.types.register_type_printer(obj, printer)
1446 class FilteringTypePrinter(object):
1447 r"""
1448 A type printer that uses typedef names for common template specializations.
1450 Args:
1451 match (str): The class template to recognize.
1452 name (str): The typedef-name that will be used instead.
1454 Checks if a specialization of the class template 'match' is the same type
1455 as the typedef 'name', and prints it as 'name' instead.
1457 e.g. if an instantiation of std::basic_istream<C, T> is the same type as
1458 std::istream then print it as std::istream.
1461 def __init__(self, match, name):
1462 self.match = match
1463 self.name = name
1464 self.enabled = True
1466 class _recognizer(object):
1467 "The recognizer class for TemplateTypePrinter."
1469 def __init__(self, match, name):
1470 self.match = match
1471 self.name = name
1472 self.type_obj = None
1474 def recognize(self, type_obj):
1476 If type_obj starts with self.match and is the same type as
1477 self.name then return self.name, otherwise None.
1479 if type_obj.tag is None:
1480 return None
1482 if self.type_obj is None:
1483 if not type_obj.tag.startswith(self.match):
1484 # Filter didn't match.
1485 return None
1486 try:
1487 self.type_obj = gdb.lookup_type(self.name).strip_typedefs()
1488 except:
1489 pass
1490 if self.type_obj == type_obj:
1491 return strip_inline_namespaces(self.name)
1492 return None
1494 def instantiate(self):
1495 "Return a recognizer object for this type printer."
1496 return self._recognizer(self.match, self.name)
1498 def add_one_type_printer(obj, match, name):
1499 printer = FilteringTypePrinter('std::' + match, 'std::' + name)
1500 gdb.types.register_type_printer(obj, printer)
1501 if _versioned_namespace:
1502 ns = 'std::' + _versioned_namespace
1503 printer = FilteringTypePrinter(ns + match, ns + name)
1504 gdb.types.register_type_printer(obj, printer)
1506 def register_type_printers(obj):
1507 global _use_type_printing
1509 if not _use_type_printing:
1510 return
1512 # Add type printers for typedefs std::string, std::wstring etc.
1513 for ch in ('', 'w', 'u16', 'u32'):
1514 add_one_type_printer(obj, 'basic_string', ch + 'string')
1515 add_one_type_printer(obj, '__cxx11::basic_string',
1516 '__cxx11::' + ch + 'string')
1517 add_one_type_printer(obj, 'basic_string_view', ch + 'string_view')
1519 # Add type printers for typedefs std::istream, std::wistream etc.
1520 for ch in ('', 'w'):
1521 for x in ('ios', 'streambuf', 'istream', 'ostream', 'iostream',
1522 'filebuf', 'ifstream', 'ofstream', 'fstream'):
1523 add_one_type_printer(obj, 'basic_' + x, ch + x)
1524 for x in ('stringbuf', 'istringstream', 'ostringstream',
1525 'stringstream'):
1526 add_one_type_printer(obj, 'basic_' + x, ch + x)
1527 # <sstream> types are in __cxx11 namespace, but typedefs aren'x:
1528 add_one_type_printer(obj, '__cxx11::basic_' + x, ch + x)
1530 # Add type printers for typedefs regex, wregex, cmatch, wcmatch etc.
1531 for abi in ('', '__cxx11::'):
1532 for ch in ('', 'w'):
1533 add_one_type_printer(obj, abi + 'basic_regex', abi + ch + 'regex')
1534 for ch in ('c', 's', 'wc', 'ws'):
1535 add_one_type_printer(obj, abi + 'match_results', abi + ch + 'match')
1536 for x in ('sub_match', 'regex_iterator', 'regex_token_iterator'):
1537 add_one_type_printer(obj, abi + x, abi + ch + x)
1539 # Note that we can't have a printer for std::wstreampos, because
1540 # it is the same type as std::streampos.
1541 add_one_type_printer(obj, 'fpos', 'streampos')
1543 # Add type printers for <chrono> typedefs.
1544 for dur in ('nanoseconds', 'microseconds', 'milliseconds',
1545 'seconds', 'minutes', 'hours'):
1546 add_one_type_printer(obj, 'duration', dur)
1548 # Add type printers for <random> typedefs.
1549 add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand0')
1550 add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand')
1551 add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937')
1552 add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937_64')
1553 add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux24_base')
1554 add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux48_base')
1555 add_one_type_printer(obj, 'discard_block_engine', 'ranlux24')
1556 add_one_type_printer(obj, 'discard_block_engine', 'ranlux48')
1557 add_one_type_printer(obj, 'shuffle_order_engine', 'knuth_b')
1559 # Add type printers for experimental::basic_string_view typedefs.
1560 ns = 'experimental::fundamentals_v1::'
1561 for ch in ('', 'w', 'u16', 'u32'):
1562 add_one_type_printer(obj, ns + 'basic_string_view',
1563 ns + ch + 'string_view')
1565 # Do not show defaulted template arguments in class templates.
1566 add_one_template_type_printer(obj, 'unique_ptr',
1567 { 1: 'std::default_delete<{0}>' })
1568 add_one_template_type_printer(obj, 'deque', { 1: 'std::allocator<{0}>'})
1569 add_one_template_type_printer(obj, 'forward_list', { 1: 'std::allocator<{0}>'})
1570 add_one_template_type_printer(obj, 'list', { 1: 'std::allocator<{0}>'})
1571 add_one_template_type_printer(obj, '__cxx11::list', { 1: 'std::allocator<{0}>'})
1572 add_one_template_type_printer(obj, 'vector', { 1: 'std::allocator<{0}>'})
1573 add_one_template_type_printer(obj, 'map',
1574 { 2: 'std::less<{0}>',
1575 3: 'std::allocator<std::pair<{0} const, {1}>>' })
1576 add_one_template_type_printer(obj, 'multimap',
1577 { 2: 'std::less<{0}>',
1578 3: 'std::allocator<std::pair<{0} const, {1}>>' })
1579 add_one_template_type_printer(obj, 'set',
1580 { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
1581 add_one_template_type_printer(obj, 'multiset',
1582 { 1: 'std::less<{0}>', 2: 'std::allocator<{0}>' })
1583 add_one_template_type_printer(obj, 'unordered_map',
1584 { 2: 'std::hash<{0}>',
1585 3: 'std::equal_to<{0}>',
1586 4: 'std::allocator<std::pair<{0} const, {1}>>'})
1587 add_one_template_type_printer(obj, 'unordered_multimap',
1588 { 2: 'std::hash<{0}>',
1589 3: 'std::equal_to<{0}>',
1590 4: 'std::allocator<std::pair<{0} const, {1}>>'})
1591 add_one_template_type_printer(obj, 'unordered_set',
1592 { 1: 'std::hash<{0}>',
1593 2: 'std::equal_to<{0}>',
1594 3: 'std::allocator<{0}>'})
1595 add_one_template_type_printer(obj, 'unordered_multiset',
1596 { 1: 'std::hash<{0}>',
1597 2: 'std::equal_to<{0}>',
1598 3: 'std::allocator<{0}>'})
1600 def register_libstdcxx_printers (obj):
1601 "Register libstdc++ pretty-printers with objfile Obj."
1603 global _use_gdb_pp
1604 global libstdcxx_printer
1606 if _use_gdb_pp:
1607 gdb.printing.register_pretty_printer(obj, libstdcxx_printer)
1608 else:
1609 if obj is None:
1610 obj = gdb
1611 obj.pretty_printers.append(libstdcxx_printer)
1613 register_type_printers(obj)
1615 def build_libstdcxx_dictionary ():
1616 global libstdcxx_printer
1618 libstdcxx_printer = Printer("libstdc++-v6")
1620 # libstdc++ objects requiring pretty-printing.
1621 # In order from:
1622 # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
1623 libstdcxx_printer.add_version('std::', 'basic_string', StdStringPrinter)
1624 libstdcxx_printer.add_version('std::__cxx11::', 'basic_string', StdStringPrinter)
1625 libstdcxx_printer.add_container('std::', 'bitset', StdBitsetPrinter)
1626 libstdcxx_printer.add_container('std::', 'deque', StdDequePrinter)
1627 libstdcxx_printer.add_container('std::', 'list', StdListPrinter)
1628 libstdcxx_printer.add_container('std::__cxx11::', 'list', StdListPrinter)
1629 libstdcxx_printer.add_container('std::', 'map', StdMapPrinter)
1630 libstdcxx_printer.add_container('std::', 'multimap', StdMapPrinter)
1631 libstdcxx_printer.add_container('std::', 'multiset', StdSetPrinter)
1632 libstdcxx_printer.add_version('std::', 'priority_queue',
1633 StdStackOrQueuePrinter)
1634 libstdcxx_printer.add_version('std::', 'queue', StdStackOrQueuePrinter)
1635 libstdcxx_printer.add_version('std::', 'tuple', StdTuplePrinter)
1636 libstdcxx_printer.add_container('std::', 'set', StdSetPrinter)
1637 libstdcxx_printer.add_version('std::', 'stack', StdStackOrQueuePrinter)
1638 libstdcxx_printer.add_version('std::', 'unique_ptr', UniquePointerPrinter)
1639 libstdcxx_printer.add_container('std::', 'vector', StdVectorPrinter)
1640 # vector<bool>
1642 # Printer registrations for classes compiled with -D_GLIBCXX_DEBUG.
1643 libstdcxx_printer.add('std::__debug::bitset', StdBitsetPrinter)
1644 libstdcxx_printer.add('std::__debug::deque', StdDequePrinter)
1645 libstdcxx_printer.add('std::__debug::list', StdListPrinter)
1646 libstdcxx_printer.add('std::__debug::map', StdMapPrinter)
1647 libstdcxx_printer.add('std::__debug::multimap', StdMapPrinter)
1648 libstdcxx_printer.add('std::__debug::multiset', StdSetPrinter)
1649 libstdcxx_printer.add('std::__debug::priority_queue',
1650 StdStackOrQueuePrinter)
1651 libstdcxx_printer.add('std::__debug::queue', StdStackOrQueuePrinter)
1652 libstdcxx_printer.add('std::__debug::set', StdSetPrinter)
1653 libstdcxx_printer.add('std::__debug::stack', StdStackOrQueuePrinter)
1654 libstdcxx_printer.add('std::__debug::unique_ptr', UniquePointerPrinter)
1655 libstdcxx_printer.add('std::__debug::vector', StdVectorPrinter)
1657 # These are the TR1 and C++11 printers.
1658 # For array - the default GDB pretty-printer seems reasonable.
1659 libstdcxx_printer.add_version('std::', 'shared_ptr', SharedPointerPrinter)
1660 libstdcxx_printer.add_version('std::', 'weak_ptr', SharedPointerPrinter)
1661 libstdcxx_printer.add_container('std::', 'unordered_map',
1662 Tr1UnorderedMapPrinter)
1663 libstdcxx_printer.add_container('std::', 'unordered_set',
1664 Tr1UnorderedSetPrinter)
1665 libstdcxx_printer.add_container('std::', 'unordered_multimap',
1666 Tr1UnorderedMapPrinter)
1667 libstdcxx_printer.add_container('std::', 'unordered_multiset',
1668 Tr1UnorderedSetPrinter)
1669 libstdcxx_printer.add_container('std::', 'forward_list',
1670 StdForwardListPrinter)
1672 libstdcxx_printer.add_version('std::tr1::', 'shared_ptr', SharedPointerPrinter)
1673 libstdcxx_printer.add_version('std::tr1::', 'weak_ptr', SharedPointerPrinter)
1674 libstdcxx_printer.add_version('std::tr1::', 'unordered_map',
1675 Tr1UnorderedMapPrinter)
1676 libstdcxx_printer.add_version('std::tr1::', 'unordered_set',
1677 Tr1UnorderedSetPrinter)
1678 libstdcxx_printer.add_version('std::tr1::', 'unordered_multimap',
1679 Tr1UnorderedMapPrinter)
1680 libstdcxx_printer.add_version('std::tr1::', 'unordered_multiset',
1681 Tr1UnorderedSetPrinter)
1683 # These are the C++11 printer registrations for -D_GLIBCXX_DEBUG cases.
1684 # The tr1 namespace containers do not have any debug equivalents,
1685 # so do not register printers for them.
1686 libstdcxx_printer.add('std::__debug::unordered_map',
1687 Tr1UnorderedMapPrinter)
1688 libstdcxx_printer.add('std::__debug::unordered_set',
1689 Tr1UnorderedSetPrinter)
1690 libstdcxx_printer.add('std::__debug::unordered_multimap',
1691 Tr1UnorderedMapPrinter)
1692 libstdcxx_printer.add('std::__debug::unordered_multiset',
1693 Tr1UnorderedSetPrinter)
1694 libstdcxx_printer.add('std::__debug::forward_list',
1695 StdForwardListPrinter)
1697 # Library Fundamentals TS components
1698 libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
1699 'any', StdExpAnyPrinter)
1700 libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
1701 'optional', StdExpOptionalPrinter)
1702 libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
1703 'basic_string_view', StdExpStringViewPrinter)
1704 # Filesystem TS components
1705 libstdcxx_printer.add_version('std::experimental::filesystem::v1::',
1706 'path', StdExpPathPrinter)
1707 libstdcxx_printer.add_version('std::experimental::filesystem::v1::__cxx11::',
1708 'path', StdExpPathPrinter)
1709 libstdcxx_printer.add_version('std::filesystem::',
1710 'path', StdExpPathPrinter)
1711 libstdcxx_printer.add_version('std::filesystem::__cxx11::',
1712 'path', StdExpPathPrinter)
1714 # C++17 components
1715 libstdcxx_printer.add_version('std::',
1716 'any', StdExpAnyPrinter)
1717 libstdcxx_printer.add_version('std::',
1718 'optional', StdExpOptionalPrinter)
1719 libstdcxx_printer.add_version('std::',
1720 'basic_string_view', StdExpStringViewPrinter)
1721 libstdcxx_printer.add_version('std::',
1722 'variant', StdVariantPrinter)
1723 libstdcxx_printer.add_version('std::',
1724 '_Node_handle', StdNodeHandlePrinter)
1726 # Extensions.
1727 libstdcxx_printer.add_version('__gnu_cxx::', 'slist', StdSlistPrinter)
1729 if True:
1730 # These shouldn't be necessary, if GDB "print *i" worked.
1731 # But it often doesn't, so here they are.
1732 libstdcxx_printer.add_container('std::', '_List_iterator',
1733 StdListIteratorPrinter)
1734 libstdcxx_printer.add_container('std::', '_List_const_iterator',
1735 StdListIteratorPrinter)
1736 libstdcxx_printer.add_version('std::', '_Rb_tree_iterator',
1737 StdRbtreeIteratorPrinter)
1738 libstdcxx_printer.add_version('std::', '_Rb_tree_const_iterator',
1739 StdRbtreeIteratorPrinter)
1740 libstdcxx_printer.add_container('std::', '_Deque_iterator',
1741 StdDequeIteratorPrinter)
1742 libstdcxx_printer.add_container('std::', '_Deque_const_iterator',
1743 StdDequeIteratorPrinter)
1744 libstdcxx_printer.add_version('__gnu_cxx::', '__normal_iterator',
1745 StdVectorIteratorPrinter)
1746 libstdcxx_printer.add_version('__gnu_cxx::', '_Slist_iterator',
1747 StdSlistIteratorPrinter)
1748 libstdcxx_printer.add_container('std::', '_Fwd_list_iterator',
1749 StdFwdListIteratorPrinter)
1750 libstdcxx_printer.add_container('std::', '_Fwd_list_const_iterator',
1751 StdFwdListIteratorPrinter)
1753 # Debug (compiled with -D_GLIBCXX_DEBUG) printer
1754 # registrations.
1755 libstdcxx_printer.add('__gnu_debug::_Safe_iterator',
1756 StdDebugIteratorPrinter)
1758 build_libstdcxx_dictionary ()