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