]> git.ipfire.org Git - thirdparty/gcc.git/blob - libstdc++-v3/python/libstdcxx/v6/printers.py
Update copyright years.
[thirdparty/gcc.git] / libstdc++-v3 / python / libstdcxx / v6 / printers.py
1 # Pretty-printers for libstdc++.
2
3 # Copyright (C) 2008-2024 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 import errno
23 import datetime
24
25 # Python 2 + Python 3 compatibility code
26
27 # Resources about compatibility:
28 #
29 # * <http://pythonhosted.org/six/>: Documentation of the "six" module
30
31 # FIXME: The handling of e.g. std::basic_string (at least on char)
32 # probably needs updating to work with Python 3's new string rules.
33 #
34 # In particular, Python 3 has a separate type (called byte) for
35 # bytestrings, and a special b"" syntax for the byte literals; the old
36 # str() type has been redefined to always store Unicode text.
37 #
38 # We probably can't do much about this until this GDB PR is addressed:
39 # <https://sourceware.org/bugzilla/show_bug.cgi?id=17138>
40
41 if sys.version_info[0] > 2:
42 # Python 3 stuff
43 Iterator = object
44 # Python 3 folds these into the normal functions.
45 imap = map
46 izip = zip
47 # Also, int subsumes long
48 long = int
49 _utc_timezone = datetime.timezone.utc
50 else:
51 # Python 2 stuff
52 class Iterator:
53 """Compatibility mixin for iterators
54
55 Instead of writing next() methods for iterators, write
56 __next__() methods and use this mixin to make them work in
57 Python 2 as well as Python 3.
58
59 Idea stolen from the "six" documentation:
60 <http://pythonhosted.org/six/#six.Iterator>
61 """
62
63 def next(self):
64 return self.__next__()
65
66 # In Python 2, we still need these from itertools
67 from itertools import imap, izip
68
69 # Python 2 does not provide the datetime.UTC singleton.
70 class UTC(datetime.tzinfo):
71 """Concrete tzinfo class representing the UTC time zone."""
72
73 def utcoffset(self, dt):
74 return datetime.timedelta(0)
75
76 def tzname(self, dt):
77 return "UTC"
78
79 def dst(self, dt):
80 return datetime.timedelta(0)
81 _utc_timezone = UTC()
82
83 # Try to use the new-style pretty-printing if available.
84 _use_gdb_pp = True
85 try:
86 import gdb.printing
87 except ImportError:
88 _use_gdb_pp = False
89
90 # Try to install type-printers.
91 _use_type_printing = False
92 try:
93 import gdb.types
94 if hasattr(gdb.types, 'TypePrinter'):
95 _use_type_printing = True
96 except ImportError:
97 pass
98
99 # Use the base class if available.
100 if hasattr(gdb, 'ValuePrinter'):
101 printer_base = gdb.ValuePrinter
102 else:
103 printer_base = object
104
105 # Starting with the type ORIG, search for the member type NAME. This
106 # handles searching upward through superclasses. This is needed to
107 # work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
108
109
110 def find_type(orig, name):
111 typ = orig.strip_typedefs()
112 while True:
113 # Use Type.tag to ignore cv-qualifiers. PR 67440.
114 search = '%s::%s' % (typ.tag, name)
115 try:
116 return gdb.lookup_type(search)
117 except RuntimeError:
118 pass
119 # The type was not found, so try the superclass. We only need
120 # to check the first superclass, so we don't bother with
121 # anything fancier here.
122 fields = typ.fields()
123 if len(fields) and fields[0].is_base_class:
124 typ = fields[0].type
125 else:
126 raise ValueError("Cannot find type %s::%s" % (str(orig), name))
127
128
129 _versioned_namespace = '__8::'
130
131
132 def lookup_templ_spec(templ, *args):
133 """
134 Lookup template specialization templ<args...>.
135 """
136 t = '{}<{}>'.format(templ, ', '.join([str(a) for a in args]))
137 try:
138 return gdb.lookup_type(t)
139 except gdb.error as e:
140 # Type not found, try again in versioned namespace.
141 global _versioned_namespace
142 if _versioned_namespace not in templ:
143 t = t.replace('::', '::' + _versioned_namespace, 1)
144 try:
145 return gdb.lookup_type(t)
146 except gdb.error:
147 # If that also fails, rethrow the original exception
148 pass
149 raise e
150
151 # Use this to find container node types instead of find_type,
152 # see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91997 for details.
153 def lookup_node_type(nodename, containertype):
154 """
155 Lookup specialization of template nodename corresponding to containertype.
156
157 nodename - The name of a class template, as a String
158 containertype - The container, as a gdb.Type
159
160 Return a gdb.Type for the corresponding specialization of nodename,
161 or None if the type cannot be found.
162
163 e.g. lookup_node_type('_List_node', gdb.lookup_type('std::list<int>'))
164 will return a gdb.Type for the type std::_List_node<int>.
165 """
166 # If nodename is unqualified, assume it's in namespace std.
167 if '::' not in nodename:
168 nodename = 'std::' + nodename
169 # Use either containertype's value_type or its first template argument.
170 try:
171 valtype = find_type(containertype, 'value_type')
172 except:
173 valtype = containertype.template_argument(0)
174 valtype = valtype.strip_typedefs()
175 try:
176 return lookup_templ_spec(nodename, valtype)
177 except gdb.error:
178 # For debug mode containers the node is in std::__cxx1998.
179 if is_member_of_namespace(nodename, 'std'):
180 if is_member_of_namespace(containertype, 'std::__cxx1998',
181 'std::__debug', '__gnu_debug'):
182 nodename = nodename.replace('::', '::__cxx1998::', 1)
183 try:
184 return lookup_templ_spec(nodename, valtype)
185 except gdb.error:
186 pass
187 return None
188
189
190 def is_member_of_namespace(typ, *namespaces):
191 """
192 Test whether a type is a member of one of the specified namespaces.
193 The type can be specified as a string or a gdb.Type object.
194 """
195 if isinstance(typ, gdb.Type):
196 typ = str(typ)
197 typ = strip_versioned_namespace(typ)
198 for namespace in namespaces:
199 if typ.startswith(namespace + '::'):
200 return True
201 return False
202
203
204 def is_specialization_of(x, template_name):
205 """
206 Test whether a type is a specialization of the named class template.
207 The type can be specified as a string or a gdb.Type object.
208 The template should be the name of a class template as a string,
209 without any 'std' qualification.
210 """
211 global _versioned_namespace
212 if isinstance(x, gdb.Type):
213 x = x.tag
214 template_name = '(%s)?%s' % (_versioned_namespace, template_name)
215 return re.match('^std::%s<.*>$' % template_name, x) is not None
216
217
218 def strip_versioned_namespace(typename):
219 global _versioned_namespace
220 return typename.replace(_versioned_namespace, '')
221
222
223 def strip_inline_namespaces(type_str):
224 """Remove known inline namespaces from the canonical name of a type."""
225 type_str = strip_versioned_namespace(type_str)
226 type_str = type_str.replace('std::__cxx11::', 'std::')
227 expt_ns = 'std::experimental::'
228 for lfts_ns in ('fundamentals_v1', 'fundamentals_v2'):
229 type_str = type_str.replace(expt_ns + lfts_ns + '::', expt_ns)
230 fs_ns = expt_ns + 'filesystem::'
231 type_str = type_str.replace(fs_ns + 'v1::', fs_ns)
232 return type_str
233
234
235 def get_template_arg_list(type_obj):
236 """Return a type's template arguments as a list."""
237 n = 0
238 template_args = []
239 while True:
240 try:
241 template_args.append(type_obj.template_argument(n))
242 except:
243 return template_args
244 n += 1
245
246
247 class SmartPtrIterator(Iterator):
248 """An iterator for smart pointer types with a single 'child' value."""
249
250 def __init__(self, val):
251 self._val = val
252
253 def __iter__(self):
254 return self
255
256 def __next__(self):
257 if self._val is None:
258 raise StopIteration
259 self._val, val = None, self._val
260 return ('get()', val)
261
262
263 class SharedPointerPrinter(printer_base):
264 """
265 Print a shared_ptr, weak_ptr, atomic<shared_ptr>, or atomic<weak_ptr>.
266 """
267
268 def __init__(self, typename, val):
269 self._typename = strip_versioned_namespace(typename)
270 self._val = val
271 self._pointer = val['_M_ptr']
272
273 def children(self):
274 return SmartPtrIterator(self._pointer)
275
276 # Return the _Sp_counted_base<>* that holds the refcounts.
277 def _get_refcounts(self):
278 if self._typename == 'std::atomic':
279 # A tagged pointer is stored as uintptr_t.
280 ptr_val = self._val['_M_refcount']['_M_val']['_M_i']
281 ptr_val = ptr_val - (ptr_val % 2) # clear lock bit
282 ptr_type = find_type(self._val['_M_refcount'].type, 'pointer')
283 return ptr_val.cast(ptr_type)
284 return self._val['_M_refcount']['_M_pi']
285
286 def to_string(self):
287 state = 'empty'
288 refcounts = self._get_refcounts()
289 targ = self._val.type.template_argument(0)
290 targ = strip_versioned_namespace(str(targ))
291
292 if refcounts != 0:
293 usecount = refcounts['_M_use_count']
294 weakcount = refcounts['_M_weak_count']
295 if usecount == 0:
296 state = 'expired, weak count %d' % weakcount
297 else:
298 state = 'use count %d, weak count %d' % (
299 usecount, weakcount - 1)
300 return '%s<%s> (%s)' % (self._typename, targ, state)
301
302
303 def _tuple_impl_get(val):
304 """Return the tuple element stored in a _Tuple_impl<N, T> base class."""
305 bases = val.type.fields()
306 if not bases[-1].is_base_class:
307 raise ValueError(
308 "Unsupported implementation for std::tuple: %s" % str(val.type))
309 # Get the _Head_base<N, T> base class:
310 head_base = val.cast(bases[-1].type)
311 fields = head_base.type.fields()
312 if len(fields) == 0:
313 raise ValueError(
314 "Unsupported implementation for std::tuple: %s" % str(val.type))
315 if fields[0].name == '_M_head_impl':
316 # The tuple element is the _Head_base::_M_head_impl data member.
317 return head_base['_M_head_impl']
318 elif fields[0].is_base_class:
319 # The tuple element is an empty base class of _Head_base.
320 # Cast to that empty base class.
321 return head_base.cast(fields[0].type)
322 else:
323 raise ValueError(
324 "Unsupported implementation for std::tuple: %s" % str(val.type))
325
326
327 def tuple_get(n, val):
328 """Return the result of std::get<n>(val) on a std::tuple."""
329 tuple_size = len(get_template_arg_list(val.type))
330 if n > tuple_size:
331 raise ValueError("Out of range index for std::get<N> on std::tuple")
332 # Get the first _Tuple_impl<0, T...> base class:
333 node = val.cast(val.type.fields()[0].type)
334 while n > 0:
335 # Descend through the base classes until the Nth one.
336 node = node.cast(node.type.fields()[0].type)
337 n -= 1
338 return _tuple_impl_get(node)
339
340
341 def unique_ptr_get(val):
342 """Return the result of val.get() on a std::unique_ptr."""
343 # std::unique_ptr<T, D> contains a std::tuple<D::pointer, D>,
344 # either as a direct data member _M_t (the old implementation)
345 # or within a data member of type __uniq_ptr_data.
346 impl_type = val.type.fields()[0].type.strip_typedefs()
347 # Check for new implementations first:
348 if is_specialization_of(impl_type, '__uniq_ptr_data') \
349 or is_specialization_of(impl_type, '__uniq_ptr_impl'):
350 tuple_member = val['_M_t']['_M_t']
351 elif is_specialization_of(impl_type, 'tuple'):
352 tuple_member = val['_M_t']
353 else:
354 raise ValueError(
355 "Unsupported implementation for unique_ptr: %s" % str(impl_type))
356 return tuple_get(0, tuple_member)
357
358
359 class UniquePointerPrinter(printer_base):
360 """Print a unique_ptr."""
361
362 def __init__(self, typename, val):
363 self._val = val
364
365 def children(self):
366 return SmartPtrIterator(unique_ptr_get(self._val))
367
368 def to_string(self):
369 t = self._val.type.template_argument(0)
370 return 'std::unique_ptr<{}>'.format(str(t))
371
372
373 def get_value_from_aligned_membuf(buf, valtype):
374 """Return the value held in a __gnu_cxx::__aligned_membuf."""
375 return buf['_M_storage'].address.cast(valtype.pointer()).dereference()
376
377
378 def get_value_from_list_node(node):
379 """Return the value held in an _List_node<_Val>."""
380 try:
381 member = node.type.fields()[1].name
382 if member == '_M_data':
383 # C++03 implementation, node contains the value as a member
384 return node['_M_data']
385 elif member == '_M_storage':
386 # C++11 implementation, node stores value in __aligned_membuf
387 valtype = node.type.template_argument(0)
388 return get_value_from_aligned_membuf(node['_M_storage'], valtype)
389 except:
390 pass
391 raise ValueError("Unsupported implementation for %s" % str(node.type))
392
393
394 class StdListPrinter(printer_base):
395 """Print a std::list."""
396
397 class _iterator(Iterator):
398 def __init__(self, nodetype, head):
399 self._nodetype = nodetype
400 self._base = head['_M_next']
401 self._head = head.address
402 self._count = 0
403
404 def __iter__(self):
405 return self
406
407 def __next__(self):
408 if self._base == self._head:
409 raise StopIteration
410 elt = self._base.cast(self._nodetype).dereference()
411 self._base = elt['_M_next']
412 count = self._count
413 self._count = self._count + 1
414 val = get_value_from_list_node(elt)
415 return ('[%d]' % count, val)
416
417 def __init__(self, typename, val):
418 self._typename = strip_versioned_namespace(typename)
419 self._val = val
420
421 def children(self):
422 nodetype = lookup_node_type('_List_node', self._val.type).pointer()
423 return self._iterator(nodetype, self._val['_M_impl']['_M_node'])
424
425 def to_string(self):
426 headnode = self._val['_M_impl']['_M_node']
427 if headnode['_M_next'] == headnode.address:
428 return 'empty %s' % (self._typename)
429 return '%s' % (self._typename)
430
431
432 class NodeIteratorPrinter(printer_base):
433 def __init__(self, typename, val, contname, nodename):
434 self._val = val
435 self._typename = typename
436 self._contname = contname
437 self._nodetype = lookup_node_type(nodename, val.type)
438
439 def to_string(self):
440 if not self._val['_M_node']:
441 return 'non-dereferenceable iterator for std::%s' % (self._contname)
442 node = self._val['_M_node'].cast(
443 self._nodetype.pointer()).dereference()
444 return str(get_value_from_list_node(node))
445
446
447 class StdListIteratorPrinter(NodeIteratorPrinter):
448 """Print std::list::iterator."""
449
450 def __init__(self, typename, val):
451 NodeIteratorPrinter.__init__(self, typename, val, 'list', '_List_node')
452
453
454 class StdFwdListIteratorPrinter(NodeIteratorPrinter):
455 """Print std::forward_list::iterator."""
456
457 def __init__(self, typename, val):
458 NodeIteratorPrinter.__init__(self, typename, val, 'forward_list',
459 '_Fwd_list_node')
460
461
462 class StdSlistPrinter(printer_base):
463 """Print a __gnu_cxx::slist."""
464
465 class _iterator(Iterator):
466 def __init__(self, nodetype, head):
467 self._nodetype = nodetype
468 self._base = head['_M_head']['_M_next']
469 self._count = 0
470
471 def __iter__(self):
472 return self
473
474 def __next__(self):
475 if self._base == 0:
476 raise StopIteration
477 elt = self._base.cast(self._nodetype).dereference()
478 self._base = elt['_M_next']
479 count = self._count
480 self._count = self._count + 1
481 return ('[%d]' % count, elt['_M_data'])
482
483 def __init__(self, typename, val):
484 self._val = val
485
486 def children(self):
487 nodetype = lookup_node_type('__gnu_cxx::_Slist_node', self._val.type)
488 return self._iterator(nodetype.pointer(), self._val)
489
490 def to_string(self):
491 if self._val['_M_head']['_M_next'] == 0:
492 return 'empty __gnu_cxx::slist'
493 return '__gnu_cxx::slist'
494
495
496 class StdSlistIteratorPrinter(printer_base):
497 """Print __gnu_cxx::slist::iterator."""
498
499 def __init__(self, typename, val):
500 self._val = val
501
502 def to_string(self):
503 if not self._val['_M_node']:
504 return 'non-dereferenceable iterator for __gnu_cxx::slist'
505 nodetype = lookup_node_type(
506 '__gnu_cxx::_Slist_node', self._val.type).pointer()
507 return str(self._val['_M_node'].cast(nodetype).dereference()['_M_data'])
508
509
510 class StdVectorPrinter(printer_base):
511 """Print a std::vector."""
512
513 class _iterator(Iterator):
514 def __init__(self, start, finish, bitvec):
515 self._bitvec = bitvec
516 if bitvec:
517 self._item = start['_M_p']
518 self._so = 0
519 self._finish = finish['_M_p']
520 self._fo = finish['_M_offset']
521 itype = self._item.dereference().type
522 self._isize = 8 * itype.sizeof
523 else:
524 self._item = start
525 self._finish = finish
526 self._count = 0
527
528 def __iter__(self):
529 return self
530
531 def __next__(self):
532 count = self._count
533 self._count = self._count + 1
534 if self._bitvec:
535 if self._item == self._finish and self._so >= self._fo:
536 raise StopIteration
537 elt = bool(self._item.dereference() & (1 << self._so))
538 self._so = self._so + 1
539 if self._so >= self._isize:
540 self._item = self._item + 1
541 self._so = 0
542 return ('[%d]' % count, elt)
543 else:
544 if self._item == self._finish:
545 raise StopIteration
546 elt = self._item.dereference()
547 self._item = self._item + 1
548 return ('[%d]' % count, elt)
549
550 def __init__(self, typename, val):
551 self._typename = strip_versioned_namespace(typename)
552 self._val = val
553 self._is_bool = val.type.template_argument(
554 0).code == gdb.TYPE_CODE_BOOL
555
556 def children(self):
557 return self._iterator(self._val['_M_impl']['_M_start'],
558 self._val['_M_impl']['_M_finish'],
559 self._is_bool)
560
561 def to_string(self):
562 start = self._val['_M_impl']['_M_start']
563 finish = self._val['_M_impl']['_M_finish']
564 end = self._val['_M_impl']['_M_end_of_storage']
565 if self._is_bool:
566 start = self._val['_M_impl']['_M_start']['_M_p']
567 finish = self._val['_M_impl']['_M_finish']['_M_p']
568 fo = self._val['_M_impl']['_M_finish']['_M_offset']
569 itype = start.dereference().type
570 bl = 8 * itype.sizeof
571 length = bl * (finish - start) + fo
572 capacity = bl * (end - start)
573 return ('%s<bool> of length %d, capacity %d'
574 % (self._typename, int(length), int(capacity)))
575 else:
576 return ('%s of length %d, capacity %d'
577 % (self._typename, int(finish - start), int(end - start)))
578
579 def display_hint(self):
580 return 'array'
581
582
583 class StdVectorIteratorPrinter(printer_base):
584 """Print std::vector::iterator."""
585
586 def __init__(self, typename, val):
587 self._val = val
588
589 def to_string(self):
590 if not self._val['_M_current']:
591 return 'non-dereferenceable iterator for std::vector'
592 return str(self._val['_M_current'].dereference())
593
594
595 class StdBitIteratorPrinter(printer_base):
596 """Print std::vector<bool>'s _Bit_iterator and _Bit_const_iterator."""
597
598 def __init__(self, typename, val):
599 self._val = val
600
601 def to_string(self):
602 if not self._val['_M_p']:
603 return 'non-dereferenceable iterator for std::vector<bool>'
604 return bool(self._val['_M_p'].dereference()
605 & (1 << self._val['_M_offset']))
606
607
608 class StdBitReferencePrinter(printer_base):
609 """Print std::vector<bool>::reference."""
610
611 def __init__(self, typename, val):
612 self._val = val
613
614 def to_string(self):
615 if not self._val['_M_p']:
616 return 'invalid std::vector<bool>::reference'
617 return bool(self._val['_M_p'].dereference() & (self._val['_M_mask']))
618
619
620 class StdTuplePrinter(printer_base):
621 """Print a std::tuple."""
622
623 class _iterator(Iterator):
624 @staticmethod
625 def _is_nonempty_tuple(nodes):
626 if len(nodes) == 2:
627 if is_specialization_of(nodes[1].type, '__tuple_base'):
628 return True
629 elif len(nodes) == 1:
630 return True
631 elif len(nodes) == 0:
632 return False
633 raise ValueError(
634 "Top of tuple tree does not consist of a single node.")
635
636 def __init__(self, head):
637 self._head = head
638
639 # Set the base class as the initial head of the
640 # tuple.
641 nodes = self._head.type.fields()
642 if self._is_nonempty_tuple(nodes):
643 # Set the actual head to the first pair.
644 self._head = self._head.cast(nodes[0].type)
645 self._count = 0
646
647 def __iter__(self):
648 return self
649
650 def __next__(self):
651 # Check for further recursions in the inheritance tree.
652 # For a GCC 5+ tuple self._head is None after visiting all nodes:
653 if not self._head:
654 raise StopIteration
655 nodes = self._head.type.fields()
656 # For a GCC 4.x tuple there is a final node with no fields:
657 if len(nodes) == 0:
658 raise StopIteration
659 # Check that this iteration has an expected structure.
660 if len(nodes) > 2:
661 raise ValueError(
662 "Cannot parse more than 2 nodes in a tuple tree.")
663
664 if len(nodes) == 1:
665 # This is the last node of a GCC 5+ std::tuple.
666 impl = self._head.cast(nodes[0].type)
667 self._head = None
668 else:
669 # Either a node before the last node, or the last node of
670 # a GCC 4.x tuple (which has an empty parent).
671
672 # - Left node is the next recursion parent.
673 # - Right node is the actual class contained in the tuple.
674
675 # Process right node.
676 impl = self._head.cast(nodes[1].type)
677
678 # Process left node and set it as head.
679 self._head = self._head.cast(nodes[0].type)
680
681 self._count = self._count + 1
682
683 # Finally, check the implementation. If it is
684 # wrapped in _M_head_impl return that, otherwise return
685 # the value "as is".
686 fields = impl.type.fields()
687 if len(fields) < 1 or fields[0].name != "_M_head_impl":
688 return ('[%d]' % (self._count - 1), impl)
689 else:
690 return ('[%d]' % (self._count - 1), impl['_M_head_impl'])
691
692 def __init__(self, typename, val):
693 self._typename = strip_versioned_namespace(typename)
694 self._val = val
695
696 def children(self):
697 return self._iterator(self._val)
698
699 def to_string(self):
700 if len(self._val.type.fields()) == 0:
701 return 'empty %s' % (self._typename)
702 return '%s containing' % (self._typename)
703
704
705 class StdStackOrQueuePrinter(printer_base):
706 """Print a std::stack or std::queue."""
707
708 def __init__(self, typename, val):
709 self._typename = strip_versioned_namespace(typename)
710 self._visualizer = gdb.default_visualizer(val['c'])
711
712 def children(self):
713 return self._visualizer.children()
714
715 def to_string(self):
716 return '%s wrapping: %s' % (self._typename,
717 self._visualizer.to_string())
718
719 def display_hint(self):
720 if hasattr(self._visualizer, 'display_hint'):
721 return self._visualizer.display_hint()
722 return None
723
724
725 class RbtreeIterator(Iterator):
726 """
727 Turn an RB-tree-based container (std::map, std::set etc.) into
728 a Python iterable object.
729 """
730
731 def __init__(self, rbtree):
732 self._size = rbtree['_M_t']['_M_impl']['_M_node_count']
733 self._node = rbtree['_M_t']['_M_impl']['_M_header']['_M_left']
734 self._count = 0
735
736 def __iter__(self):
737 return self
738
739 def __len__(self):
740 return int(self._size)
741
742 def __next__(self):
743 if self._count == self._size:
744 raise StopIteration
745 result = self._node
746 self._count = self._count + 1
747 if self._count < self._size:
748 # Compute the next node.
749 node = self._node
750 if node.dereference()['_M_right']:
751 node = node.dereference()['_M_right']
752 while node.dereference()['_M_left']:
753 node = node.dereference()['_M_left']
754 else:
755 parent = node.dereference()['_M_parent']
756 while node == parent.dereference()['_M_right']:
757 node = parent
758 parent = parent.dereference()['_M_parent']
759 if node.dereference()['_M_right'] != parent:
760 node = parent
761 self._node = node
762 return result
763
764
765 def get_value_from_Rb_tree_node(node):
766 """Return the value held in an _Rb_tree_node<_Val>."""
767 try:
768 member = node.type.fields()[1].name
769 if member == '_M_value_field':
770 # C++03 implementation, node contains the value as a member
771 return node['_M_value_field']
772 elif member == '_M_storage':
773 # C++11 implementation, node stores value in __aligned_membuf
774 valtype = node.type.template_argument(0)
775 return get_value_from_aligned_membuf(node['_M_storage'], valtype)
776 except:
777 pass
778 raise ValueError("Unsupported implementation for %s" % str(node.type))
779
780 # This is a pretty printer for std::_Rb_tree_iterator (which is
781 # std::map::iterator), and has nothing to do with the RbtreeIterator
782 # class above.
783
784
785 class StdRbtreeIteratorPrinter(printer_base):
786 """Print std::map::iterator, std::set::iterator, etc."""
787
788 def __init__(self, typename, val):
789 self._val = val
790 nodetype = lookup_node_type('_Rb_tree_node', self._val.type)
791 self._link_type = nodetype.pointer()
792
793 def to_string(self):
794 if not self._val['_M_node']:
795 return 'non-dereferenceable iterator for associative container'
796 node = self._val['_M_node'].cast(self._link_type).dereference()
797 return str(get_value_from_Rb_tree_node(node))
798
799
800 class StdDebugIteratorPrinter(printer_base):
801 """Print a debug enabled version of an iterator."""
802
803 def __init__(self, typename, val):
804 self._val = val
805
806 # Just strip away the encapsulating __gnu_debug::_Safe_iterator
807 # and return the wrapped iterator value.
808 def to_string(self):
809 base_type = gdb.lookup_type('__gnu_debug::_Safe_iterator_base')
810 itype = self._val.type.template_argument(0)
811 safe_seq = self._val.cast(base_type)['_M_sequence']
812 if not safe_seq:
813 return str(self._val.cast(itype))
814 if self._val['_M_version'] != safe_seq['_M_version']:
815 return "invalid iterator"
816 return str(self._val.cast(itype))
817
818
819 def num_elements(num):
820 """Return either "1 element" or "N elements" depending on the argument."""
821 return '1 element' if num == 1 else '%d elements' % num
822
823
824 class StdMapPrinter(printer_base):
825 """Print a std::map or std::multimap."""
826
827 # Turn an RbtreeIterator into a pretty-print iterator.
828 class _iter(Iterator):
829 def __init__(self, rbiter, type):
830 self._rbiter = rbiter
831 self._count = 0
832 self._type = type
833
834 def __iter__(self):
835 return self
836
837 def __next__(self):
838 if self._count % 2 == 0:
839 n = next(self._rbiter)
840 n = n.cast(self._type).dereference()
841 n = get_value_from_Rb_tree_node(n)
842 self._pair = n
843 item = n['first']
844 else:
845 item = self._pair['second']
846 result = ('[%d]' % self._count, item)
847 self._count = self._count + 1
848 return result
849
850 def __init__(self, typename, val):
851 self._typename = strip_versioned_namespace(typename)
852 self._val = val
853
854 def to_string(self):
855 return '%s with %s' % (self._typename,
856 num_elements(len(RbtreeIterator(self._val))))
857
858 def children(self):
859 node = lookup_node_type('_Rb_tree_node', self._val.type).pointer()
860 return self._iter(RbtreeIterator(self._val), node)
861
862 def display_hint(self):
863 return 'map'
864
865
866 class StdSetPrinter(printer_base):
867 """Print a std::set or std::multiset."""
868
869 # Turn an RbtreeIterator into a pretty-print iterator.
870 class _iter(Iterator):
871 def __init__(self, rbiter, type):
872 self._rbiter = rbiter
873 self._count = 0
874 self._type = type
875
876 def __iter__(self):
877 return self
878
879 def __next__(self):
880 item = next(self._rbiter)
881 item = item.cast(self._type).dereference()
882 item = get_value_from_Rb_tree_node(item)
883 # FIXME: this is weird ... what to do?
884 # Maybe a 'set' display hint?
885 result = ('[%d]' % self._count, item)
886 self._count = self._count + 1
887 return result
888
889 def __init__(self, typename, val):
890 self._typename = strip_versioned_namespace(typename)
891 self._val = val
892
893 def to_string(self):
894 return '%s with %s' % (self._typename,
895 num_elements(len(RbtreeIterator(self._val))))
896
897 def children(self):
898 node = lookup_node_type('_Rb_tree_node', self._val.type).pointer()
899 return self._iter(RbtreeIterator(self._val), node)
900
901
902 class StdBitsetPrinter(printer_base):
903 """Print a std::bitset."""
904
905 def __init__(self, typename, val):
906 self._typename = strip_versioned_namespace(typename)
907 self._val = val
908
909 def to_string(self):
910 # If template_argument handled values, we could print the
911 # size. Or we could use a regexp on the type.
912 return '%s' % (self._typename)
913
914 def children(self):
915 try:
916 # An empty bitset may not have any members which will
917 # result in an exception being thrown.
918 words = self._val['_M_w']
919 except:
920 return []
921
922 wtype = words.type
923
924 # The _M_w member can be either an unsigned long, or an
925 # array. This depends on the template specialization used.
926 # If it is a single long, convert to a single element list.
927 if wtype.code == gdb.TYPE_CODE_ARRAY:
928 tsize = wtype.target().sizeof
929 else:
930 words = [words]
931 tsize = wtype.sizeof
932
933 nwords = wtype.sizeof / tsize
934 result = []
935 byte = 0
936 while byte < nwords:
937 w = words[byte]
938 bit = 0
939 while w != 0:
940 if (w & 1) != 0:
941 # Another spot where we could use 'set'?
942 result.append(('[%d]' % (byte * tsize * 8 + bit), 1))
943 bit = bit + 1
944 w = w >> 1
945 byte = byte + 1
946 return result
947
948
949 class StdDequePrinter(printer_base):
950 """Print a std::deque."""
951
952 class _iter(Iterator):
953 def __init__(self, node, start, end, last, buffer_size):
954 self._node = node
955 self._p = start
956 self._end = end
957 self._last = last
958 self._buffer_size = buffer_size
959 self._count = 0
960
961 def __iter__(self):
962 return self
963
964 def __next__(self):
965 if self._p == self._last:
966 raise StopIteration
967
968 result = ('[%d]' % self._count, self._p.dereference())
969 self._count = self._count + 1
970
971 # Advance the 'cur' pointer.
972 self._p = self._p + 1
973 if self._p == self._end:
974 # If we got to the end of this bucket, move to the
975 # next bucket.
976 self._node = self._node + 1
977 self._p = self._node[0]
978 self._end = self._p + self._buffer_size
979
980 return result
981
982 def __init__(self, typename, val):
983 self._typename = strip_versioned_namespace(typename)
984 self._val = val
985 self._elttype = val.type.template_argument(0)
986 size = self._elttype.sizeof
987 if size < 512:
988 self._buffer_size = int(512 / size)
989 else:
990 self._buffer_size = 1
991
992 def to_string(self):
993 start = self._val['_M_impl']['_M_start']
994 end = self._val['_M_impl']['_M_finish']
995
996 delta_n = end['_M_node'] - start['_M_node'] - 1
997 delta_s = start['_M_last'] - start['_M_cur']
998 delta_e = end['_M_cur'] - end['_M_first']
999
1000 size = self._buffer_size * delta_n + delta_s + delta_e
1001
1002 return '%s with %s' % (self._typename, num_elements(long(size)))
1003
1004 def children(self):
1005 start = self._val['_M_impl']['_M_start']
1006 end = self._val['_M_impl']['_M_finish']
1007 return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
1008 end['_M_cur'], self._buffer_size)
1009
1010 def display_hint(self):
1011 return 'array'
1012
1013
1014 class StdDequeIteratorPrinter(printer_base):
1015 """Print std::deque::iterator."""
1016
1017 def __init__(self, typename, val):
1018 self._val = val
1019
1020 def to_string(self):
1021 if not self._val['_M_cur']:
1022 return 'non-dereferenceable iterator for std::deque'
1023 return str(self._val['_M_cur'].dereference())
1024
1025
1026 class StdStringPrinter(printer_base):
1027 """Print a std::basic_string of some kind."""
1028
1029 def __init__(self, typename, val):
1030 self._val = val
1031 self._new_string = typename.find("::__cxx11::basic_string") != -1
1032
1033 def to_string(self):
1034 # Make sure &string works, too.
1035 type = self._val.type
1036 if type.code == gdb.TYPE_CODE_REF:
1037 type = type.target()
1038
1039 # Calculate the length of the string so that to_string returns
1040 # the string according to length, not according to first null
1041 # encountered.
1042 ptr = self._val['_M_dataplus']['_M_p']
1043 if self._new_string:
1044 length = self._val['_M_string_length']
1045 # https://sourceware.org/bugzilla/show_bug.cgi?id=17728
1046 ptr = ptr.cast(ptr.type.strip_typedefs())
1047 else:
1048 realtype = type.unqualified().strip_typedefs()
1049 reptype = gdb.lookup_type(str(realtype) + '::_Rep').pointer()
1050 header = ptr.cast(reptype) - 1
1051 length = header.dereference()['_M_length']
1052 if hasattr(ptr, "lazy_string"):
1053 return ptr.lazy_string(length=length)
1054 return ptr.string(length=length)
1055
1056 def display_hint(self):
1057 return 'string'
1058
1059
1060 def access_streambuf_ptrs(streambuf):
1061 """Access the streambuf put area pointers."""
1062 pbase = streambuf['_M_out_beg']
1063 pptr = streambuf['_M_out_cur']
1064 egptr = streambuf['_M_in_end']
1065 return pbase, pptr, egptr
1066
1067
1068 class StdStringBufPrinter(printer_base):
1069 """Print a std::basic_stringbuf."""
1070
1071 def __init__(self, _, val):
1072 self._val = val
1073
1074 def to_string(self):
1075 (pbase, pptr, egptr) = access_streambuf_ptrs(self._val)
1076 # Logic from basic_stringbuf::_M_high_mark()
1077 if pptr:
1078 if not egptr or pptr > egptr:
1079 return pbase.string(length=pptr - pbase)
1080 else:
1081 return pbase.string(length=egptr - pbase)
1082 return self._val['_M_string']
1083
1084 def display_hint(self):
1085 return 'string'
1086
1087
1088 class StdStringStreamPrinter(printer_base):
1089 """Print a std::basic_stringstream."""
1090
1091 def __init__(self, typename, val):
1092 self._val = val
1093 self._typename = typename
1094
1095 # Check if the stream was redirected. This is essentially:
1096 # val['_M_streambuf'] != val['_M_stringbuf'].address
1097 # However, GDB can't resolve the virtual inheritance, so we do that
1098 # manually.
1099 basetype = [f.type for f in val.type.fields() if f.is_base_class][0]
1100 gdb.set_convenience_variable('__stream', val.cast(basetype).address)
1101 self._streambuf = gdb.parse_and_eval('$__stream->rdbuf()')
1102 self._was_redirected = self._streambuf != val['_M_stringbuf'].address
1103
1104 def to_string(self):
1105 if self._was_redirected:
1106 return "%s redirected to %s" % (
1107 self._typename, self._streambuf.dereference())
1108 return self._val['_M_stringbuf']
1109
1110 def display_hint(self):
1111 if self._was_redirected:
1112 return None
1113 return 'string'
1114
1115
1116 class Tr1HashtableIterator(Iterator):
1117 def __init__(self, hashtable):
1118 self._buckets = hashtable['_M_buckets']
1119 self._bucket = 0
1120 self._bucket_count = hashtable['_M_bucket_count']
1121 self._node_type = find_type(hashtable.type, '_Node').pointer()
1122 self._node = 0
1123 while self._bucket != self._bucket_count:
1124 self._node = self._buckets[self._bucket]
1125 if self._node:
1126 break
1127 self._bucket = self._bucket + 1
1128
1129 def __iter__(self):
1130 return self
1131
1132 def __next__(self):
1133 if self._node == 0:
1134 raise StopIteration
1135 node = self._node.cast(self._node_type)
1136 result = node.dereference()['_M_v']
1137 self._node = node.dereference()['_M_next']
1138 if self._node == 0:
1139 self._bucket = self._bucket + 1
1140 while self._bucket != self._bucket_count:
1141 self._node = self._buckets[self._bucket]
1142 if self._node:
1143 break
1144 self._bucket = self._bucket + 1
1145 return result
1146
1147
1148 class StdHashtableIterator(Iterator):
1149 def __init__(self, hashtable):
1150 self._node = hashtable['_M_before_begin']['_M_nxt']
1151 valtype = hashtable.type.template_argument(1)
1152 cached = hashtable.type.template_argument(9).template_argument(0)
1153 node_type = lookup_templ_spec('std::__detail::_Hash_node', str(valtype),
1154 'true' if cached else 'false')
1155 self._node_type = node_type.pointer()
1156
1157 def __iter__(self):
1158 return self
1159
1160 def __next__(self):
1161 if self._node == 0:
1162 raise StopIteration
1163 elt = self._node.cast(self._node_type).dereference()
1164 self._node = elt['_M_nxt']
1165 valptr = elt['_M_storage'].address
1166 valptr = valptr.cast(elt.type.template_argument(0).pointer())
1167 return valptr.dereference()
1168
1169
1170 class Tr1UnorderedSetPrinter(printer_base):
1171 """Print a std::unordered_set or tr1::unordered_set."""
1172
1173 def __init__(self, typename, val):
1174 self._typename = strip_versioned_namespace(typename)
1175 self._val = val
1176
1177 def _hashtable(self):
1178 if self._typename.startswith('std::tr1'):
1179 return self._val
1180 return self._val['_M_h']
1181
1182 def to_string(self):
1183 count = self._hashtable()['_M_element_count']
1184 return '%s with %s' % (self._typename, num_elements(count))
1185
1186 @staticmethod
1187 def _format_count(i):
1188 return '[%d]' % i
1189
1190 def children(self):
1191 counter = imap(self._format_count, itertools.count())
1192 if self._typename.startswith('std::tr1'):
1193 return izip(counter, Tr1HashtableIterator(self._hashtable()))
1194 return izip(counter, StdHashtableIterator(self._hashtable()))
1195
1196
1197 class Tr1UnorderedMapPrinter(printer_base):
1198 """Print a std::unordered_map or tr1::unordered_map."""
1199
1200 def __init__(self, typename, val):
1201 self._typename = strip_versioned_namespace(typename)
1202 self._val = val
1203
1204 def _hashtable(self):
1205 if self._typename.startswith('std::tr1'):
1206 return self._val
1207 return self._val['_M_h']
1208
1209 def to_string(self):
1210 count = self._hashtable()['_M_element_count']
1211 return '%s with %s' % (self._typename, num_elements(count))
1212
1213 @staticmethod
1214 def _flatten(list):
1215 for elt in list:
1216 for i in elt:
1217 yield i
1218
1219 @staticmethod
1220 def _format_one(elt):
1221 return (elt['first'], elt['second'])
1222
1223 @staticmethod
1224 def _format_count(i):
1225 return '[%d]' % i
1226
1227 def children(self):
1228 counter = imap(self._format_count, itertools.count())
1229 # Map over the hash table and flatten the result.
1230 if self._typename.startswith('std::tr1'):
1231 data = self._flatten(
1232 imap(self._format_one, Tr1HashtableIterator(self._hashtable())))
1233 # Zip the two iterators together.
1234 return izip(counter, data)
1235 data = self._flatten(
1236 imap(self._format_one, StdHashtableIterator(self._hashtable())))
1237 # Zip the two iterators together.
1238 return izip(counter, data)
1239
1240 def display_hint(self):
1241 return 'map'
1242
1243
1244 class StdForwardListPrinter(printer_base):
1245 """Print a std::forward_list."""
1246
1247 class _iterator(Iterator):
1248 def __init__(self, nodetype, head):
1249 self._nodetype = nodetype
1250 self._base = head['_M_next']
1251 self._count = 0
1252
1253 def __iter__(self):
1254 return self
1255
1256 def __next__(self):
1257 if self._base == 0:
1258 raise StopIteration
1259 elt = self._base.cast(self._nodetype).dereference()
1260 self._base = elt['_M_next']
1261 count = self._count
1262 self._count = self._count + 1
1263 valptr = elt['_M_storage'].address
1264 valptr = valptr.cast(elt.type.template_argument(0).pointer())
1265 return ('[%d]' % count, valptr.dereference())
1266
1267 def __init__(self, typename, val):
1268 self._val = val
1269 self._typename = strip_versioned_namespace(typename)
1270
1271 def children(self):
1272 nodetype = lookup_node_type('_Fwd_list_node', self._val.type).pointer()
1273 return self._iterator(nodetype, self._val['_M_impl']['_M_head'])
1274
1275 def to_string(self):
1276 if self._val['_M_impl']['_M_head']['_M_next'] == 0:
1277 return 'empty %s' % self._typename
1278 return '%s' % self._typename
1279
1280
1281 class SingleObjContainerPrinter(printer_base):
1282 """Base class for printers of containers of single objects."""
1283
1284 def __init__(self, val, viz, hint=None):
1285 self._contained_value = val
1286 self._visualizer = viz
1287 self._hint = hint
1288
1289 def _recognize(self, type):
1290 """Return type as a string after applying type printers."""
1291 global _use_type_printing
1292 if not _use_type_printing:
1293 return str(type)
1294 return gdb.types.apply_type_recognizers(gdb.types.get_type_recognizers(),
1295 type) or str(type)
1296
1297 class _contained(Iterator):
1298 def __init__(self, val):
1299 self._val = val
1300
1301 def __iter__(self):
1302 return self
1303
1304 def __next__(self):
1305 if self._val is None:
1306 raise StopIteration
1307 retval = self._val
1308 self._val = None
1309 return ('[contained value]', retval)
1310
1311 def children(self):
1312 if self._contained_value is None:
1313 return self._contained(None)
1314 if hasattr(self._visualizer, 'children'):
1315 return self._visualizer.children()
1316 return self._contained(self._contained_value)
1317
1318 def display_hint(self):
1319 if (hasattr(self._visualizer, 'children')
1320 and hasattr(self._visualizer, 'display_hint')):
1321 # If contained value is a map we want to display in the same way.
1322 return self._visualizer.display_hint()
1323 return self._hint
1324
1325
1326 def function_pointer_to_name(f):
1327 """Find the name of the function referred to by the gdb.Value f,
1328 which should contain a function pointer from the program."""
1329
1330 # Turn the function pointer into an actual address.
1331 # This is needed to unpack ppc64 function descriptors.
1332 f = f.dereference().address
1333
1334 if sys.version_info[0] == 2:
1335 # Older versions of GDB need to use long for Python 2,
1336 # because int(f) on 64-bit big-endian values raises a
1337 # gdb.error saying "Cannot convert value to int."
1338 f = long(f)
1339 else:
1340 f = int(f)
1341
1342 try:
1343 # If the function can't be found older versions of GDB raise a
1344 # RuntimeError saying "Cannot locate object file for block."
1345 return gdb.block_for_pc(f).function.name
1346 except:
1347 return None
1348
1349
1350 class StdExpAnyPrinter(SingleObjContainerPrinter):
1351 """Print a std::any or std::experimental::any."""
1352
1353 def __init__(self, typename, val):
1354 self._typename = strip_versioned_namespace(typename)
1355 self._typename = re.sub(r'^std::experimental::fundamentals_v\d::',
1356 'std::experimental::', self._typename, 1)
1357 self._val = val
1358 self._contained_type = None
1359 contained_value = None
1360 visualizer = None
1361 mgr = self._val['_M_manager']
1362 if mgr != 0:
1363 func = function_pointer_to_name(mgr)
1364 if not func:
1365 raise ValueError(
1366 "Invalid function pointer in %s" % (self._typename))
1367 # We want to use this regular expression:
1368 # T::_Manager_xxx<.*>::_S_manage\(T::_Op, const T\*, T::_Arg\*\)
1369 # where T is std::any or std::experimental::any.
1370 # But we need to account for variances in demangled names
1371 # between GDB versions, e.g. 'enum T::_Op' instead of 'T::_Op'.
1372 rx = (
1373 r"({0}::_Manager_\w+<.*>)::_S_manage\("
1374 r"(enum )?{0}::_Op, (const {0}|{0} const) ?\*, "
1375 r"(union )?{0}::_Arg ?\*\)"
1376 ).format(typename)
1377 m = re.match(rx, func)
1378 if not m:
1379 raise ValueError(
1380 "Unknown manager function in %s" % self._typename)
1381
1382 mgrname = m.group(1)
1383 # FIXME need to expand 'std::string' so that gdb.lookup_type works
1384 if 'std::string' in mgrname:
1385 mgrtypes = []
1386 for s in StdExpAnyPrinter._string_types():
1387 try:
1388 x = re.sub(r"std::string(?!\w)", s, m.group(1))
1389 # The following lookup might raise gdb.error if the
1390 # manager function was never instantiated for 's' in
1391 # the program, because there will be no such type.
1392 mgrtypes.append(gdb.lookup_type(x))
1393 except gdb.error:
1394 pass
1395 if len(mgrtypes) != 1:
1396 # FIXME: this is unlikely in practice, but possible for
1397 # programs that use both old and new string types with
1398 # std::any in a single program. Can we do better?
1399 # Maybe find the address of each type's _S_manage and
1400 # compare to the address stored in _M_manager?
1401 raise ValueError(
1402 'Cannot uniquely determine std::string type '
1403 'used in std::any'
1404 )
1405 mgrtype = mgrtypes[0]
1406 else:
1407 mgrtype = gdb.lookup_type(mgrname)
1408 self._contained_type = mgrtype.template_argument(0)
1409 valptr = None
1410 if '::_Manager_internal' in mgrname:
1411 valptr = self._val['_M_storage']['_M_buffer'].address
1412 elif '::_Manager_external' in mgrname:
1413 valptr = self._val['_M_storage']['_M_ptr']
1414 else:
1415 raise ValueError(
1416 "Unknown manager function in %s" % self._typename)
1417 contained_value = valptr.cast(
1418 self._contained_type.pointer()).dereference()
1419 visualizer = gdb.default_visualizer(contained_value)
1420 super(StdExpAnyPrinter, self).__init__(contained_value, visualizer)
1421
1422 def to_string(self):
1423 if self._contained_type is None:
1424 return '%s [no contained value]' % self._typename
1425 desc = "%s containing " % self._typename
1426 if hasattr(self._visualizer, 'children'):
1427 return desc + self._visualizer.to_string()
1428 valtype = self._recognize(self._contained_type)
1429 return desc + strip_versioned_namespace(str(valtype))
1430
1431 @staticmethod
1432 def _string_types():
1433 # This lookup for std::string might return the __cxx11 version,
1434 # but that's not necessarily the one used by the std::any
1435 # manager function we're trying to find.
1436 strings = {str(gdb.lookup_type('std::string').strip_typedefs())}
1437 # So also consider all the other possible std::string types!
1438 s = 'basic_string<char, std::char_traits<char>, std::allocator<char> >'
1439 quals = ['std::', 'std::__cxx11::',
1440 'std::' + _versioned_namespace]
1441 strings |= {q + s for q in quals} # set of unique strings
1442 return strings
1443
1444
1445 class StdExpOptionalPrinter(SingleObjContainerPrinter):
1446 """Print a std::optional or std::experimental::optional."""
1447
1448 def __init__(self, typename, val):
1449 typename = strip_versioned_namespace(typename)
1450 self._typename = re.sub(
1451 r'^std::(experimental::|)(fundamentals_v\d::|)(.*)',
1452 r'std::\1\3', typename, 1)
1453 payload = val['_M_payload']
1454 if self._typename.startswith('std::experimental'):
1455 engaged = val['_M_engaged']
1456 contained_value = payload
1457 else:
1458 engaged = payload['_M_engaged']
1459 contained_value = payload['_M_payload']
1460 try:
1461 # Since GCC 9
1462 contained_value = contained_value['_M_value']
1463 except:
1464 pass
1465 visualizer = gdb.default_visualizer(contained_value)
1466 if not engaged:
1467 contained_value = None
1468 super(StdExpOptionalPrinter, self).__init__(
1469 contained_value, visualizer)
1470
1471 def to_string(self):
1472 if self._contained_value is None:
1473 return "%s [no contained value]" % self._typename
1474 if hasattr(self._visualizer, 'children'):
1475 return "%s containing %s" % (self._typename,
1476 self._visualizer.to_string())
1477 return self._typename
1478
1479
1480 class StdVariantPrinter(SingleObjContainerPrinter):
1481 """Print a std::variant."""
1482
1483 def __init__(self, typename, val):
1484 alternatives = get_template_arg_list(val.type)
1485 self._typename = strip_versioned_namespace(typename)
1486 self._index = val['_M_index']
1487 if self._index >= len(alternatives):
1488 self._contained_type = None
1489 contained_value = None
1490 visualizer = None
1491 else:
1492 self._contained_type = alternatives[int(self._index)]
1493 addr = val['_M_u']['_M_first']['_M_storage'].address
1494 contained_value = addr.cast(
1495 self._contained_type.pointer()).dereference()
1496 visualizer = gdb.default_visualizer(contained_value)
1497 super(StdVariantPrinter, self).__init__(
1498 contained_value, visualizer, 'array')
1499
1500 def to_string(self):
1501 if self._contained_value is None:
1502 return "%s [no contained value]" % self._typename
1503 if hasattr(self._visualizer, 'children'):
1504 return "%s [index %d] containing %s" % (self._typename, self._index,
1505 self._visualizer.to_string())
1506 return "%s [index %d]" % (self._typename, self._index)
1507
1508
1509 class StdNodeHandlePrinter(SingleObjContainerPrinter):
1510 """Print a container node handle."""
1511
1512 def __init__(self, typename, val):
1513 self._value_type = val.type.template_argument(1)
1514 nodetype = val.type.template_argument(2).template_argument(0)
1515 self._is_rb_tree_node = is_specialization_of(
1516 nodetype.name, '_Rb_tree_node')
1517 self._is_map_node = val.type.template_argument(0) != self._value_type
1518 nodeptr = val['_M_ptr']
1519 if nodeptr:
1520 if self._is_rb_tree_node:
1521 contained_value = get_value_from_Rb_tree_node(
1522 nodeptr.dereference())
1523 else:
1524 contained_value = get_value_from_aligned_membuf(nodeptr['_M_storage'],
1525 self._value_type)
1526 visualizer = gdb.default_visualizer(contained_value)
1527 else:
1528 contained_value = None
1529 visualizer = None
1530 optalloc = val['_M_alloc']
1531 self._alloc = optalloc['_M_payload'] if optalloc['_M_engaged'] else None
1532 super(StdNodeHandlePrinter, self).__init__(contained_value, visualizer,
1533 'array')
1534
1535 def to_string(self):
1536 desc = 'node handle for '
1537 if not self._is_rb_tree_node:
1538 desc += 'unordered '
1539 if self._is_map_node:
1540 desc += 'map'
1541 else:
1542 desc += 'set'
1543
1544 if self._contained_value:
1545 desc += ' with element'
1546 if hasattr(self._visualizer, 'children'):
1547 return "%s = %s" % (desc, self._visualizer.to_string())
1548 return desc
1549 else:
1550 return 'empty %s' % desc
1551
1552
1553 class StdExpStringViewPrinter(printer_base):
1554 """
1555 Print a std::basic_string_view or std::experimental::basic_string_view
1556 """
1557
1558 def __init__(self, typename, val):
1559 self._val = val
1560
1561 def to_string(self):
1562 ptr = self._val['_M_str']
1563 len = self._val['_M_len']
1564 if hasattr(ptr, "lazy_string"):
1565 return ptr.lazy_string(length=len)
1566 return ptr.string(length=len)
1567
1568 def display_hint(self):
1569 return 'string'
1570
1571
1572 class StdExpPathPrinter(printer_base):
1573 """Print a std::experimental::filesystem::path."""
1574
1575 def __init__(self, typename, val):
1576 self._val = val
1577 self._typename = typename
1578 start = self._val['_M_cmpts']['_M_impl']['_M_start']
1579 finish = self._val['_M_cmpts']['_M_impl']['_M_finish']
1580 self._num_cmpts = int(finish - start)
1581
1582 def _path_type(self):
1583 t = str(self._val['_M_type'])
1584 if t[-9:] == '_Root_dir':
1585 return "root-directory"
1586 if t[-10:] == '_Root_name':
1587 return "root-name"
1588 return None
1589
1590 def to_string(self):
1591 path = "%s" % self._val['_M_pathname']
1592 if self._num_cmpts == 0:
1593 t = self._path_type()
1594 if t:
1595 path = '%s [%s]' % (path, t)
1596 return "experimental::filesystem::path %s" % path
1597
1598 class _iterator(Iterator):
1599 def __init__(self, cmpts, pathtype):
1600 self._pathtype = pathtype
1601 self._item = cmpts['_M_impl']['_M_start']
1602 self._finish = cmpts['_M_impl']['_M_finish']
1603 self._count = 0
1604
1605 def __iter__(self):
1606 return self
1607
1608 def __next__(self):
1609 if self._item == self._finish:
1610 raise StopIteration
1611 item = self._item.dereference()
1612 count = self._count
1613 self._count = self._count + 1
1614 self._item = self._item + 1
1615 path = item['_M_pathname']
1616 t = StdExpPathPrinter(self._pathtype, item)._path_type()
1617 if not t:
1618 t = count
1619 return ('[%s]' % t, path)
1620
1621 def children(self):
1622 return self._iterator(self._val['_M_cmpts'], self._typename)
1623
1624
1625 class StdPathPrinter(printer_base):
1626 """Print a std::filesystem::path."""
1627
1628 def __init__(self, typename, val):
1629 self._val = val
1630 self._typename = typename
1631 impl = unique_ptr_get(self._val['_M_cmpts']['_M_impl'])
1632 self._type = impl.cast(gdb.lookup_type('uintptr_t')) & 3
1633 if self._type == 0:
1634 self._impl = impl
1635 else:
1636 self._impl = None
1637
1638 def _path_type(self):
1639 t = str(self._type.cast(gdb.lookup_type(self._typename + '::_Type')))
1640 if t[-9:] == '_Root_dir':
1641 return "root-directory"
1642 if t[-10:] == '_Root_name':
1643 return "root-name"
1644 return None
1645
1646 def to_string(self):
1647 path = "%s" % self._val['_M_pathname']
1648 if self._type != 0:
1649 t = self._path_type()
1650 if t:
1651 path = '%s [%s]' % (path, t)
1652 return "filesystem::path %s" % path
1653
1654 class _iterator(Iterator):
1655 def __init__(self, impl, pathtype):
1656 self._pathtype = pathtype
1657 if impl:
1658 # We can't access _Impl::_M_size because _Impl is incomplete
1659 # so cast to int* to access the _M_size member at offset zero,
1660 int_type = gdb.lookup_type('int')
1661 cmpt_type = gdb.lookup_type(pathtype + '::_Cmpt')
1662 char_type = gdb.lookup_type('char')
1663 impl = impl.cast(int_type.pointer())
1664 size = impl.dereference()
1665 #self._capacity = (impl + 1).dereference()
1666 if hasattr(gdb.Type, 'alignof'):
1667 sizeof_Impl = max(2 * int_type.sizeof, cmpt_type.alignof)
1668 else:
1669 sizeof_Impl = 2 * int_type.sizeof
1670 begin = impl.cast(char_type.pointer()) + sizeof_Impl
1671 self._item = begin.cast(cmpt_type.pointer())
1672 self._finish = self._item + size
1673 self._count = 0
1674 else:
1675 self._item = None
1676 self._finish = None
1677
1678 def __iter__(self):
1679 return self
1680
1681 def __next__(self):
1682 if self._item == self._finish:
1683 raise StopIteration
1684 item = self._item.dereference()
1685 count = self._count
1686 self._count = self._count + 1
1687 self._item = self._item + 1
1688 path = item['_M_pathname']
1689 t = StdPathPrinter(self._pathtype, item)._path_type()
1690 if not t:
1691 t = count
1692 return ('[%s]' % t, path)
1693
1694 def children(self):
1695 return self._iterator(self._impl, self._typename)
1696
1697
1698 class StdPairPrinter(printer_base):
1699 """Print a std::pair object, with 'first' and 'second' as children."""
1700
1701 def __init__(self, typename, val):
1702 self._val = val
1703
1704 class _iter(Iterator):
1705 """An iterator for std::pair types. Returns 'first' then 'second'."""
1706
1707 def __init__(self, val):
1708 self._val = val
1709 self._which = 'first'
1710
1711 def __iter__(self):
1712 return self
1713
1714 def __next__(self):
1715 if self._which is None:
1716 raise StopIteration
1717 which = self._which
1718 if which == 'first':
1719 self._which = 'second'
1720 else:
1721 self._which = None
1722 return (which, self._val[which])
1723
1724 def children(self):
1725 return self._iter(self._val)
1726
1727 def to_string(self):
1728 return None
1729
1730
1731 class StdCmpCatPrinter(printer_base):
1732 """Print a comparison category object."""
1733
1734 def __init__(self, typename, val):
1735 self._typename = typename[typename.rfind(':') + 1:]
1736 self._val = val['_M_value']
1737
1738 def to_string(self):
1739 if self._typename == 'strong_ordering' and self._val == 0:
1740 name = 'equal'
1741 else:
1742 names = {2: 'unordered', -1: 'less', 0: 'equivalent', 1: 'greater'}
1743 name = names[int(self._val)]
1744 return 'std::{}::{}'.format(self._typename, name)
1745
1746
1747 class StdErrorCodePrinter(printer_base):
1748 """Print a std::error_code or std::error_condition."""
1749
1750 _system_is_posix = None # Whether std::system_category() use errno values.
1751
1752 def __init__(self, typename, val):
1753 self._val = val
1754 self._typename = strip_versioned_namespace(typename)
1755 # Do this only once ...
1756 if StdErrorCodePrinter._system_is_posix is None:
1757 try:
1758 import posix
1759 StdErrorCodePrinter._system_is_posix = True
1760 except ImportError:
1761 StdErrorCodePrinter._system_is_posix = False
1762
1763 @staticmethod
1764 def _find_errc_enum(name):
1765 typ = gdb.lookup_type(name)
1766 if typ is not None and typ.code == gdb.TYPE_CODE_ENUM:
1767 return typ
1768 return None
1769
1770 @classmethod
1771 def _find_standard_errc_enum(cls, name):
1772 for ns in ['', _versioned_namespace]:
1773 try:
1774 qname = 'std::{}{}'.format(ns, name)
1775 return cls._find_errc_enum(qname)
1776 except RuntimeError:
1777 pass
1778
1779 @classmethod
1780 def _match_net_ts_category(cls, cat):
1781 net_cats = ['stream', 'socket', 'ip::resolver']
1782 for c in net_cats:
1783 func = c + '_category()'
1784 for ns in ['', _versioned_namespace]:
1785 ns = 'std::{}experimental::net::v1'.format(ns)
1786 sym = gdb.lookup_symbol('{}::{}::__c'.format(ns, func))[0]
1787 if sym is not None:
1788 if cat == sym.value().address:
1789 name = 'net::' + func
1790 enum = cls._find_errc_enum('{}::{}_errc'.format(ns, c))
1791 return (name, enum)
1792 return (None, None)
1793
1794 @classmethod
1795 def _category_info(cls, cat):
1796 """Return details of a std::error_category."""
1797
1798 name = None
1799 enum = None
1800 is_errno = False
1801
1802 # Try these first, or we get "warning: RTTI symbol not found" when
1803 # using cat.dynamic_type on the local class types for Net TS
1804 # categories.
1805 func, enum = cls._match_net_ts_category(cat)
1806 if func is not None:
1807 return (None, func, enum, is_errno)
1808
1809 # This might give a warning for a program-defined category defined as
1810 # a local class, but there doesn't seem to be any way to avoid that.
1811 typ = cat.dynamic_type.target()
1812 # Shortcuts for the known categories defined by libstdc++.
1813 if typ.tag.endswith('::generic_error_category'):
1814 name = 'generic'
1815 is_errno = True
1816 if typ.tag.endswith('::system_error_category'):
1817 name = 'system'
1818 is_errno = cls._system_is_posix
1819 if typ.tag.endswith('::future_error_category'):
1820 name = 'future'
1821 enum = cls._find_standard_errc_enum('future_errc')
1822 if typ.tag.endswith('::io_error_category'):
1823 name = 'io'
1824 enum = cls._find_standard_errc_enum('io_errc')
1825
1826 if name is None:
1827 try:
1828 # Want to call std::error_category::name() override, but it's
1829 # unsafe: https://sourceware.org/bugzilla/show_bug.cgi?id=28856
1830 # gdb.set_convenience_variable('__cat', cat)
1831 # return '"%s"' % gdb.parse_and_eval('$__cat->name()').string()
1832 pass
1833 except:
1834 pass
1835 return (name, typ.tag, enum, is_errno)
1836
1837 @staticmethod
1838 def _unqualified_name(name):
1839 """
1840 Strip any nested-name-specifier from name to give an unqualified name.
1841 """
1842 return name.split('::')[-1]
1843
1844 def to_string(self):
1845 value = self._val['_M_value']
1846 cat = self._val['_M_cat']
1847 name, alt_name, enum, is_errno = self._category_info(cat)
1848 if value == 0:
1849 default_cats = {'error_code': 'system',
1850 'error_condition': 'generic'}
1851 if name == default_cats[self._unqualified_name(self._typename)]:
1852 return self._typename + ' = { }' # default-constructed value
1853
1854 strval = str(value)
1855 if is_errno and value != 0:
1856 try:
1857 strval = errno.errorcode[int(value)]
1858 except:
1859 pass
1860 elif enum is not None:
1861 strval = self._unqualified_name(str(value.cast(enum)))
1862
1863 if name is not None:
1864 name = '"%s"' % name
1865 else:
1866 name = alt_name
1867 return '%s = {%s: %s}' % (self._typename, name, strval)
1868
1869
1870 class StdRegexStatePrinter(printer_base):
1871 """Print a state node in the NFA for a std::regex."""
1872
1873 def __init__(self, typename, val):
1874 self._val = val
1875 self._typename = typename
1876
1877 def to_string(self):
1878 opcode = str(self._val['_M_opcode'])
1879 if opcode:
1880 opcode = opcode[25:]
1881 next_id = self._val['_M_next']
1882
1883 variants = {'repeat': 'alt', 'alternative': 'alt',
1884 'subexpr_begin': 'subexpr', 'subexpr_end': 'subexpr',
1885 'line_begin_assertion': None, 'line_end_assertion': None,
1886 'word_boundary': 'neg', 'subexpr_lookahead': 'neg',
1887 'backref': 'backref_index',
1888 'match': None, 'accept': None,
1889 'dummy': None, 'unknown': None
1890 }
1891 v = variants[opcode]
1892
1893 s = "opcode={}, next={}".format(opcode, next_id)
1894 if v is not None and self._val['_M_' + v] is not None:
1895 s = "{}, {}={}".format(s, v, self._val['_M_' + v])
1896 return "{%s}" % (s)
1897
1898
1899 class StdSpanPrinter(printer_base):
1900 """Print a std::span."""
1901
1902 class _iterator(Iterator):
1903 def __init__(self, begin, size):
1904 self._count = 0
1905 self._begin = begin
1906 self._size = size
1907
1908 def __iter__(self):
1909 return self
1910
1911 def __next__(self):
1912 if self._count == self._size:
1913 raise StopIteration
1914
1915 count = self._count
1916 self._count = self._count + 1
1917 return '[%d]' % count, (self._begin + count).dereference()
1918
1919 def __init__(self, typename, val):
1920 self._typename = strip_versioned_namespace(typename)
1921 self._val = val
1922 size_max = gdb.parse_and_eval('static_cast<std::size_t>(-1)')
1923 if val.type.template_argument(1) == size_max:
1924 self._size = val['_M_extent']['_M_extent_value']
1925 else:
1926 self._size = val.type.template_argument(1)
1927
1928 def to_string(self):
1929 return '%s of length %d' % (self._typename, self._size)
1930
1931 def children(self):
1932 return self._iterator(self._val['_M_ptr'], self._size)
1933
1934 def display_hint(self):
1935 return 'array'
1936
1937
1938 class StdInitializerListPrinter(printer_base):
1939 """Print a std::initializer_list."""
1940
1941 def __init__(self, typename, val):
1942 self._typename = typename
1943 self._val = val
1944 self._size = val['_M_len']
1945
1946 def to_string(self):
1947 return '%s of length %d' % (self._typename, self._size)
1948
1949 def children(self):
1950 return StdSpanPrinter._iterator(self._val['_M_array'], self._size)
1951
1952 def display_hint(self):
1953 return 'array'
1954
1955
1956 class StdAtomicPrinter(printer_base):
1957 """Print a std:atomic."""
1958
1959 def __init__(self, typename, val):
1960 self._typename = strip_versioned_namespace(typename)
1961 self._val = val
1962 self._shptr_printer = None
1963 self._value_type = self._val.type.template_argument(0)
1964 if self._value_type.tag is not None:
1965 typ = strip_versioned_namespace(self._value_type.tag)
1966 if (typ.startswith('std::shared_ptr<')
1967 or typ.startswith('std::weak_ptr<')):
1968 impl = val['_M_impl']
1969 self._shptr_printer = SharedPointerPrinter(typename, impl)
1970 self.children = self._shptr_children
1971
1972 def _shptr_children(self):
1973 return SmartPtrIterator(self._shptr_printer._pointer)
1974
1975 def to_string(self):
1976 if self._shptr_printer is not None:
1977 return self._shptr_printer.to_string()
1978
1979 if self._value_type.code == gdb.TYPE_CODE_INT:
1980 val = self._val['_M_i']
1981 elif self._value_type.code == gdb.TYPE_CODE_FLT:
1982 val = self._val['_M_fp']
1983 elif self._value_type.code == gdb.TYPE_CODE_PTR:
1984 val = self._val['_M_b']['_M_p']
1985 elif self._value_type.code == gdb.TYPE_CODE_BOOL:
1986 val = self._val['_M_base']['_M_i']
1987 else:
1988 val = self._val['_M_i']
1989 return '%s<%s> = { %s }' % (self._typename, str(self._value_type), val)
1990
1991
1992 class StdFormatArgsPrinter(printer_base):
1993 """Print a std::basic_format_args."""
1994 # TODO: add printer for basic_format_arg<Context> and print out children.
1995 # TODO: add printer for __format::_ArgStore<Context, Args...>.
1996
1997 def __init__(self, typename, val):
1998 self._typename = strip_versioned_namespace(typename)
1999 self._val = val
2000
2001 def to_string(self):
2002 targs = get_template_arg_list(self._val.type)
2003 char_type = get_template_arg_list(targs[0])[1]
2004 if char_type == gdb.lookup_type('char'):
2005 typ = 'std::format_args'
2006 elif char_type == gdb.lookup_type('wchar_t'):
2007 typ = 'std::wformat_args'
2008 else:
2009 typ = 'std::basic_format_args'
2010
2011 size = self._val['_M_packed_size']
2012 if size == 1:
2013 return "%s with 1 argument" % (typ)
2014 if size == 0:
2015 size = self._val['_M_unpacked_size']
2016 return "%s with %d arguments" % (typ, size)
2017
2018
2019 class StdChronoDurationPrinter(printer_base):
2020 """Print a std::chrono::duration."""
2021
2022 def __init__(self, typename, val):
2023 self._typename = strip_versioned_namespace(typename)
2024 self._val = val
2025
2026 def _ratio(self):
2027 # TODO use reduced period i.e. duration::period
2028 period = self._val.type.template_argument(1)
2029 num = period.template_argument(0)
2030 den = period.template_argument(1)
2031 return (num, den)
2032
2033 def _suffix(self):
2034 num, den = self._ratio()
2035 if num == 1:
2036 if den == 1:
2037 return 's'
2038 if den == 1000:
2039 return 'ms'
2040 if den == 1000000:
2041 return 'us'
2042 if den == 1000000000:
2043 return 'ns'
2044 elif den == 1:
2045 if num == 60:
2046 return 'min'
2047 if num == 3600:
2048 return 'h'
2049 if num == 86400:
2050 return 'd'
2051 return '[{}]s'.format(num)
2052 return "[{}/{}]s".format(num, den)
2053
2054 def to_string(self):
2055 r = self._val['__r']
2056 if r.type.strip_typedefs().code == gdb.TYPE_CODE_FLT:
2057 r = "%g" % r
2058 return "std::chrono::duration = {{ {}{} }}".format(r, self._suffix())
2059
2060
2061 class StdChronoTimePointPrinter(printer_base):
2062 """Print a std::chrono::time_point."""
2063
2064 def __init__(self, typename, val):
2065 self._typename = strip_versioned_namespace(typename)
2066 self._val = val
2067
2068 def _clock(self):
2069 clock = self._val.type.template_argument(0)
2070 name = strip_versioned_namespace(clock.name)
2071 if name == 'std::chrono::_V2::system_clock' \
2072 or name == 'std::chrono::system_clock':
2073 return ('std::chrono::sys_time', 0)
2074 # XXX need to remove leap seconds from utc, gps, and tai
2075 if name == 'std::chrono::utc_clock':
2076 return ('std::chrono::utc_time', None) # XXX
2077 if name == 'std::chrono::gps_clock':
2078 return ('std::chrono::gps_time', None) # XXX 315964809
2079 if name == 'std::chrono::tai_clock':
2080 return ('std::chrono::tai_time', None) # XXX -378691210
2081 if name == 'std::filesystem::__file_clock':
2082 return ('std::chrono::file_time', 6437664000)
2083 if name == 'std::chrono::local_t':
2084 return ('std::chrono::local_time', 0)
2085 return ('{} time_point'.format(name), None)
2086
2087 def to_string(self, abbrev=False):
2088 clock, offset = self._clock()
2089 d = self._val['__d']
2090 r = d['__r']
2091 printer = StdChronoDurationPrinter(d.type.name, d)
2092 suffix = printer._suffix()
2093 time = ''
2094 if offset is not None:
2095 num, den = printer._ratio()
2096 secs = (r * num / den) + offset
2097 try:
2098 dt = datetime.datetime.fromtimestamp(secs, _utc_timezone)
2099 time = ' [{:%Y-%m-%d %H:%M:%S}]'.format(dt)
2100 except:
2101 pass
2102 s = '%d%s%s' % (r, suffix, time)
2103 if abbrev:
2104 return s
2105 return '%s = { %s }' % (clock, s)
2106
2107
2108 class StdChronoZonedTimePrinter(printer_base):
2109 """Print a std::chrono::zoned_time."""
2110
2111 def __init__(self, typename, val):
2112 self._typename = strip_versioned_namespace(typename)
2113 self._val = val
2114
2115 def to_string(self):
2116 zone = self._val['_M_zone'].dereference()['_M_name']
2117 time = self._val['_M_tp']
2118 printer = StdChronoTimePointPrinter(time.type.name, time)
2119 time = printer.to_string(True)
2120 return 'std::chrono::zoned_time = {{ {} {} }}'.format(zone, time)
2121
2122
2123 months = [None, 'January', 'February', 'March', 'April', 'May', 'June',
2124 'July', 'August', 'September', 'October', 'November', 'December']
2125
2126 weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
2127 'Saturday', 'Sunday']
2128
2129
2130 class StdChronoCalendarPrinter(printer_base):
2131 """Print a std::chrono::day, std::chrono::month, std::chrono::year etc."""
2132
2133 def __init__(self, typename, val):
2134 self._typename = strip_versioned_namespace(typename)
2135 self._val = val
2136
2137 def to_string(self):
2138 val = self._val
2139 typ = self._typename
2140 if 'month' in typ and typ != 'std::chrono::year_month_day_last':
2141 m = val['_M_m']
2142 if typ.startswith('std::chrono::year'):
2143 y = val['_M_y']
2144
2145 if typ == 'std::chrono::day':
2146 return '{}'.format(int(val['_M_d']))
2147 if typ == 'std::chrono::month':
2148 if m < 1 or m >= len(months):
2149 return "%d is not a valid month" % m
2150 return months[m]
2151 if typ == 'std::chrono::year':
2152 return '{}y'.format(y)
2153 if typ == 'std::chrono::weekday':
2154 wd = val['_M_wd']
2155 if wd < 0 or wd >= len(weekdays):
2156 return "%d is not a valid weekday" % wd
2157 return '{}'.format(weekdays[wd])
2158 if typ == 'std::chrono::weekday_indexed':
2159 return '{}[{}]'.format(val['_M_wd'], int(val['_M_index']))
2160 if typ == 'std::chrono::weekday_last':
2161 return '{}[last]'.format(val['_M_wd'])
2162 if typ == 'std::chrono::month_day':
2163 return '{}/{}'.format(m, val['_M_d'])
2164 if typ == 'std::chrono::month_day_last':
2165 return '{}/last'.format(m)
2166 if typ == 'std::chrono::month_weekday':
2167 return '{}/{}'.format(m, val['_M_wdi'])
2168 if typ == 'std::chrono::month_weekday_last':
2169 return '{}/{}'.format(m, val['_M_wdl'])
2170 if typ == 'std::chrono::year_month':
2171 return '{}/{}'.format(y, m)
2172 if typ == 'std::chrono::year_month_day':
2173 return '{}/{}/{}'.format(y, m, val['_M_d'])
2174 if typ == 'std::chrono::year_month_day_last':
2175 return '{}/{}'.format(y, val['_M_mdl'])
2176 if typ == 'std::chrono::year_month_weekday':
2177 return '{}/{}/{}'.format(y, m, val['_M_wdi'])
2178 if typ == 'std::chrono::year_month_weekday_last':
2179 return '{}/{}/{}'.format(y, m, val['_M_wdl'])
2180 if typ.startswith('std::chrono::hh_mm_ss'):
2181 fract = ''
2182 if val['fractional_width'] != 0:
2183 fract = '.{:0{}d}'.format(int(val['_M_ss']['_M_r']),
2184 int(val['fractional_width']))
2185 h = int(val['_M_h']['__r'])
2186 m = int(val['_M_m']['__r'])
2187 s = int(val['_M_s']['__r'])
2188 if val['_M_is_neg']:
2189 h = -h
2190 return '{:02}:{:02}:{:02}{}'.format(h, m, s, fract)
2191
2192
2193 class StdChronoTimeZonePrinter(printer_base):
2194 """Print a chrono::time_zone or chrono::time_zone_link."""
2195
2196 def __init__(self, typename, val):
2197 self._typename = strip_versioned_namespace(typename)
2198 self._val = val
2199
2200 def to_string(self):
2201 str = '%s = %s' % (self._typename, self._val['_M_name'])
2202 if self._typename.endswith("_link"):
2203 str += ' -> %s' % (self._val['_M_target'])
2204 return str
2205
2206
2207 class StdChronoLeapSecondPrinter(printer_base):
2208 """Print a chrono::leap_second."""
2209
2210 def __init__(self, typename, val):
2211 self._typename = strip_versioned_namespace(typename)
2212 self._val = val
2213
2214 def to_string(self):
2215 date = self._val['_M_s']['__r']
2216 neg = '+-'[date < 0]
2217 return '%s %d (%c)' % (self._typename, abs(date), neg)
2218
2219
2220 class StdChronoTzdbPrinter(printer_base):
2221 """Print a chrono::tzdb."""
2222
2223 def __init__(self, typename, val):
2224 self._typename = strip_versioned_namespace(typename)
2225 self._val = val
2226
2227 def to_string(self):
2228 return '%s %s' % (self._typename, self._val['version'])
2229
2230
2231 class StdChronoTimeZoneRulePrinter(printer_base):
2232 """Print a chrono::time_zone rule."""
2233
2234 def __init__(self, typename, val):
2235 self._typename = strip_versioned_namespace(typename)
2236 self._val = val
2237
2238 def to_string(self):
2239 on = self._val['on']
2240 kind = on['kind']
2241 month = months[on['month']]
2242 suffixes = {1: 'st', 2: 'nd', 3: 'rd',
2243 21: 'st', 22: 'nd', 23: 'rd', 31: 'st'}
2244 day = on['day_of_month']
2245 ordinal_day = '{}{}'.format(day, suffixes.get(day, 'th'))
2246 if kind == 0: # DayOfMonth
2247 start = '{} {}'.format(month, ordinal_day)
2248 else:
2249 weekday = weekdays[on['day_of_week']]
2250 if kind == 1: # LastWeekDay
2251 start = 'last {} in {}'.format(weekday, month)
2252 else:
2253 if kind == 2: # LessEq
2254 direction = ('last', '<=')
2255 else:
2256 direction = ('first', '>=')
2257 day = on['day_of_month']
2258 start = '{} {} {} {} {}'.format(direction[0], weekday,
2259 direction[1], month,
2260 ordinal_day)
2261 return 'time_zone rule {} from {} to {} starting on {}'.format(
2262 self._val['name'], self._val['from'], self._val['to'], start)
2263
2264
2265 class StdLocalePrinter(printer_base):
2266 """Print a std::locale."""
2267
2268 def __init__(self, typename, val):
2269 self._val = val
2270 self._typename = typename
2271
2272 def to_string(self):
2273 names = self._val['_M_impl']['_M_names']
2274 mod = ''
2275 if names[0] == 0:
2276 name = '*'
2277 else:
2278 cats = gdb.parse_and_eval(self._typename + '::_S_categories')
2279 ncat = gdb.parse_and_eval(self._typename + '::_S_categories_size')
2280 n = names[0].string()
2281 cat = cats[0].string()
2282 name = '{}={}'.format(cat, n)
2283 cat_names = {cat: n}
2284 i = 1
2285 while i < ncat and names[i] != 0:
2286 n = names[i].string()
2287 cat = cats[i].string()
2288 name = '{};{}={}'.format(name, cat, n)
2289 cat_names[cat] = n
2290 i = i + 1
2291 uniq_names = set(cat_names.values())
2292 if len(uniq_names) == 1:
2293 name = n
2294 elif len(uniq_names) == 2:
2295 n1, n2 = (uniq_names)
2296 name_list = list(cat_names.values())
2297 other = None
2298 if name_list.count(n1) == 1:
2299 name = n2
2300 other = n1
2301 elif name_list.count(n2) == 1:
2302 name = n1
2303 other = n2
2304 if other is not None:
2305 cat = next(c for c, n in cat_names.items() if n == other)
2306 mod = ' with "{}={}"'.format(cat, other)
2307 return 'std::locale = "{}"{}'.format(name, mod)
2308
2309
2310 # A "regular expression" printer which conforms to the
2311 # "SubPrettyPrinter" protocol from gdb.printing.
2312 class RxPrinter(object):
2313 def __init__(self, name, function):
2314 super(RxPrinter, self).__init__()
2315 self.name = name
2316 self._function = function
2317 self.enabled = True
2318
2319 def invoke(self, value):
2320 if not self.enabled:
2321 return None
2322
2323 if value.type.code == gdb.TYPE_CODE_REF:
2324 if hasattr(gdb.Value, "referenced_value"):
2325 value = value.referenced_value()
2326
2327 return self._function(self.name, value)
2328
2329 # A pretty-printer that conforms to the "PrettyPrinter" protocol from
2330 # gdb.printing. It can also be used directly as an old-style printer.
2331
2332
2333 class Printer(object):
2334 def __init__(self, name):
2335 super(Printer, self).__init__()
2336 self.name = name
2337 self._subprinters = []
2338 self._lookup = {}
2339 self.enabled = True
2340 self._compiled_rx = re.compile('^([a-zA-Z0-9_:]+)(<.*>)?$')
2341
2342 def add(self, name, function):
2343 # A small sanity check.
2344 # FIXME
2345 if not self._compiled_rx.match(name):
2346 raise ValueError(
2347 'libstdc++ programming error: "%s" does not match' % name)
2348 printer = RxPrinter(name, function)
2349 self._subprinters.append(printer)
2350 self._lookup[name] = printer
2351
2352 # Add a name using _GLIBCXX_BEGIN_NAMESPACE_VERSION.
2353 def add_version(self, base, name, function):
2354 self.add(base + name, function)
2355 if '__cxx11' not in base:
2356 vbase = re.sub('^(std|__gnu_cxx)::', r'\g<0>%s' %
2357 _versioned_namespace, base)
2358 self.add(vbase + name, function)
2359
2360 # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
2361 def add_container(self, base, name, function):
2362 self.add_version(base, name, function)
2363 self.add_version(base + '__cxx1998::', name, function)
2364
2365 @staticmethod
2366 def get_basic_type(type):
2367 # If it points to a reference, get the reference.
2368 if type.code == gdb.TYPE_CODE_REF:
2369 type = type.target()
2370
2371 # Get the unqualified type, stripped of typedefs.
2372 type = type.unqualified().strip_typedefs()
2373
2374 return type.tag
2375
2376 def __call__(self, val):
2377 typename = self.get_basic_type(val.type)
2378 if not typename:
2379 return None
2380
2381 # All the types we match are template types, so we can use a
2382 # dictionary.
2383 match = self._compiled_rx.match(typename)
2384 if not match:
2385 return None
2386
2387 basename = match.group(1)
2388
2389 if val.type.code == gdb.TYPE_CODE_REF:
2390 if hasattr(gdb.Value, "referenced_value"):
2391 val = val.referenced_value()
2392
2393 if basename in self._lookup:
2394 return self._lookup[basename].invoke(val)
2395
2396 # Cannot find a pretty printer. Return None.
2397 return None
2398
2399
2400 libstdcxx_printer = None
2401
2402
2403 class TemplateTypePrinter(object):
2404 """
2405 A type printer for class templates with default template arguments.
2406
2407 Recognizes specializations of class templates and prints them without
2408 any template arguments that use a default template argument.
2409 Type printers are recursively applied to the template arguments.
2410
2411 e.g. replace 'std::vector<T, std::allocator<T> >' with 'std::vector<T>'.
2412 """
2413
2414 def __init__(self, name, defargs):
2415 self.name = name
2416 self._defargs = defargs
2417 self.enabled = True
2418
2419 class _recognizer(object):
2420 """The recognizer class for TemplateTypePrinter."""
2421
2422 def __init__(self, name, defargs):
2423 self.name = name
2424 self._defargs = defargs
2425 # self._type_obj = None
2426
2427 def recognize(self, type_obj):
2428 """
2429 If type_obj is a specialization of self.name that uses all the
2430 default template arguments for the class template, then return
2431 a string representation of the type without default arguments.
2432 Otherwise, return None.
2433 """
2434
2435 if type_obj.tag is None:
2436 return None
2437
2438 if not type_obj.tag.startswith(self.name):
2439 return None
2440
2441 template_args = get_template_arg_list(type_obj)
2442 displayed_args = []
2443 require_defaulted = False
2444 for n in range(len(template_args)):
2445 # The actual template argument in the type:
2446 targ = template_args[n]
2447 # The default template argument for the class template:
2448 defarg = self._defargs.get(n)
2449 if defarg is not None:
2450 # Substitute other template arguments into the default:
2451 defarg = defarg.format(*template_args)
2452 # Fail to recognize the type (by returning None)
2453 # unless the actual argument is the same as the default.
2454 try:
2455 if targ != gdb.lookup_type(defarg):
2456 return None
2457 except gdb.error:
2458 # Type lookup failed, just use string comparison:
2459 if targ.tag != defarg:
2460 return None
2461 # All subsequent args must have defaults:
2462 require_defaulted = True
2463 elif require_defaulted:
2464 return None
2465 else:
2466 # Recursively apply recognizers to the template argument
2467 # and add it to the arguments that will be displayed:
2468 displayed_args.append(self._recognize_subtype(targ))
2469
2470 # This assumes no class templates in the nested-name-specifier:
2471 template_name = type_obj.tag[0:type_obj.tag.find('<')]
2472 template_name = strip_inline_namespaces(template_name)
2473
2474 return template_name + '<' + ', '.join(displayed_args) + '>'
2475
2476 def _recognize_subtype(self, type_obj):
2477 """Convert a gdb.Type to a string by applying recognizers,
2478 or if that fails then simply converting to a string."""
2479
2480 if type_obj.code == gdb.TYPE_CODE_PTR:
2481 return self._recognize_subtype(type_obj.target()) + '*'
2482 if type_obj.code == gdb.TYPE_CODE_ARRAY:
2483 type_str = self._recognize_subtype(type_obj.target())
2484 if str(type_obj.strip_typedefs()).endswith('[]'):
2485 return type_str + '[]' # array of unknown bound
2486 return "%s[%d]" % (type_str, type_obj.range()[1] + 1)
2487 if type_obj.code == gdb.TYPE_CODE_REF:
2488 return self._recognize_subtype(type_obj.target()) + '&'
2489 if hasattr(gdb, 'TYPE_CODE_RVALUE_REF'):
2490 if type_obj.code == gdb.TYPE_CODE_RVALUE_REF:
2491 return self._recognize_subtype(type_obj.target()) + '&&'
2492
2493 type_str = gdb.types.apply_type_recognizers(
2494 gdb.types.get_type_recognizers(), type_obj)
2495 if type_str:
2496 return type_str
2497 return str(type_obj)
2498
2499 def instantiate(self):
2500 """Return a recognizer object for this type printer."""
2501 return self._recognizer(self.name, self._defargs)
2502
2503
2504 def add_one_template_type_printer(obj, name, defargs):
2505 """
2506 Add a type printer for a class template with default template arguments.
2507
2508 Args:
2509 name (str): The template-name of the class template.
2510 defargs (dict int:string) The default template arguments.
2511
2512 Types in defargs can refer to the Nth template-argument using {N}
2513 (with zero-based indices).
2514
2515 e.g. 'unordered_map' has these defargs:
2516 { 2: 'std::hash<{0}>',
2517 3: 'std::equal_to<{0}>',
2518 4: 'std::allocator<std::pair<const {0}, {1}> >' }
2519 """
2520 printer = TemplateTypePrinter('std::' + name, defargs)
2521 gdb.types.register_type_printer(obj, printer)
2522
2523 # Add type printer for same type in debug namespace:
2524 printer = TemplateTypePrinter('std::__debug::' + name, defargs)
2525 gdb.types.register_type_printer(obj, printer)
2526
2527 if '__cxx11' not in name:
2528 # Add second type printer for same type in versioned namespace:
2529 ns = 'std::' + _versioned_namespace
2530 # PR 86112 Cannot use dict comprehension here:
2531 defargs = dict((n, d.replace('std::', ns))
2532 for (n, d) in defargs.items())
2533 printer = TemplateTypePrinter(ns + name, defargs)
2534 gdb.types.register_type_printer(obj, printer)
2535
2536 # Add type printer for same type in debug namespace:
2537 printer = TemplateTypePrinter('std::__debug::' + name, defargs)
2538 gdb.types.register_type_printer(obj, printer)
2539
2540
2541 class FilteringTypePrinter(object):
2542 """
2543 A type printer that uses typedef names for common template specializations.
2544
2545 Args:
2546 template (str): The class template to recognize.
2547 name (str): The typedef-name that will be used instead.
2548 targ1 (str, optional): The first template argument. Defaults to None.
2549
2550 Checks if a specialization of the class template 'template' is the same type
2551 as the typedef 'name', and prints it as 'name' instead.
2552
2553 e.g. if an instantiation of std::basic_istream<C, T> is the same type as
2554 std::istream then print it as std::istream.
2555
2556 If targ1 is provided (not None), match only template specializations with
2557 this type as the first template argument, e.g. if template='basic_string'
2558 and targ1='char' then only match 'basic_string<char,...>' and not
2559 'basic_string<wchar_t,...>'. This rejects non-matching specializations
2560 more quickly, without needing to do GDB type lookups.
2561 """
2562
2563 def __init__(self, template, name, targ1=None):
2564 self._template = template
2565 self.name = name
2566 self._targ1 = targ1
2567 self.enabled = True
2568
2569 class _recognizer(object):
2570 """The recognizer class for FilteringTypePrinter."""
2571
2572 def __init__(self, template, name, targ1):
2573 self._template = template
2574 self.name = name
2575 self._targ1 = targ1
2576 self._type_obj = None
2577
2578 def recognize(self, type_obj):
2579 """
2580 If type_obj starts with self._template and is the same type as
2581 self.name then return self.name, otherwise None.
2582 """
2583 if type_obj.tag is None:
2584 return None
2585
2586 if self._type_obj is None:
2587 if self._targ1 is not None:
2588 s = '{}<{}'.format(self._template, self._targ1)
2589 if not type_obj.tag.startswith(s):
2590 # Filter didn't match.
2591 return None
2592 elif not type_obj.tag.startswith(self._template):
2593 # Filter didn't match.
2594 return None
2595
2596 try:
2597 self._type_obj = gdb.lookup_type(
2598 self.name).strip_typedefs()
2599 except:
2600 pass
2601
2602 if self._type_obj is None:
2603 return None
2604
2605 t1 = gdb.types.get_basic_type(self._type_obj)
2606 t2 = gdb.types.get_basic_type(type_obj)
2607 if t1 == t2:
2608 return strip_inline_namespaces(self.name)
2609
2610 # Workaround ambiguous typedefs matching both std:: and
2611 # std::__cxx11:: symbols.
2612 if self._template.split('::')[-1] == 'basic_string':
2613 s1 = self._type_obj.tag.replace('__cxx11::', '')
2614 s2 = type_obj.tag.replace('__cxx11::', '')
2615 if s1 == s2:
2616 return strip_inline_namespaces(self.name)
2617
2618 return None
2619
2620 def instantiate(self):
2621 """Return a recognizer object for this type printer."""
2622 return self._recognizer(self._template, self.name, self._targ1)
2623
2624
2625 def add_one_type_printer(obj, template, name, targ1=None):
2626 printer = FilteringTypePrinter('std::' + template, 'std::' + name, targ1)
2627 gdb.types.register_type_printer(obj, printer)
2628 if '__cxx11' not in template:
2629 ns = 'std::' + _versioned_namespace
2630 printer = FilteringTypePrinter(ns + template, ns + name, targ1)
2631 gdb.types.register_type_printer(obj, printer)
2632
2633
2634 def register_type_printers(obj):
2635 global _use_type_printing
2636
2637 if not _use_type_printing:
2638 return
2639
2640 # Add type printers for typedefs std::string, std::wstring etc.
2641 for ch in (('', 'char'),
2642 ('w', 'wchar_t'),
2643 ('u8', 'char8_t'),
2644 ('u16', 'char16_t'),
2645 ('u32', 'char32_t')):
2646 add_one_type_printer(obj, 'basic_string', ch[0] + 'string', ch[1])
2647 add_one_type_printer(obj, '__cxx11::basic_string',
2648 ch[0] + 'string', ch[1])
2649 # Typedefs for __cxx11::basic_string used to be in namespace __cxx11:
2650 add_one_type_printer(obj, '__cxx11::basic_string',
2651 '__cxx11::' + ch[0] + 'string', ch[1])
2652 add_one_type_printer(obj, 'basic_string_view',
2653 ch[0] + 'string_view', ch[1])
2654
2655 # Add type printers for typedefs std::istream, std::wistream etc.
2656 for ch in (('', 'char'), ('w', 'wchar_t')):
2657 for x in ('ios', 'streambuf', 'istream', 'ostream', 'iostream',
2658 'filebuf', 'ifstream', 'ofstream', 'fstream'):
2659 add_one_type_printer(obj, 'basic_' + x, ch[0] + x, ch[1])
2660 for x in ('stringbuf', 'istringstream', 'ostringstream',
2661 'stringstream'):
2662 add_one_type_printer(obj, 'basic_' + x, ch[0] + x, ch[1])
2663 # <sstream> types are in __cxx11 namespace, but typedefs aren't:
2664 add_one_type_printer(obj, '__cxx11::basic_' + x, ch[0] + x, ch[1])
2665
2666 # Add type printers for typedefs regex, wregex, cmatch, wcmatch etc.
2667 for abi in ('', '__cxx11::'):
2668 for ch in (('', 'char'), ('w', 'wchar_t')):
2669 add_one_type_printer(obj, abi + 'basic_regex',
2670 abi + ch[0] + 'regex', ch[1])
2671 for ch in ('c', 's', 'wc', 'ws'):
2672 add_one_type_printer(
2673 obj, abi + 'match_results', abi + ch + 'match')
2674 for x in ('sub_match', 'regex_iterator', 'regex_token_iterator'):
2675 add_one_type_printer(obj, abi + x, abi + ch + x)
2676
2677 # Note that we can't have a printer for std::wstreampos, because
2678 # it is the same type as std::streampos.
2679 add_one_type_printer(obj, 'fpos', 'streampos')
2680
2681 # Add type printers for <chrono> typedefs.
2682 for dur in ('nanoseconds', 'microseconds', 'milliseconds', 'seconds',
2683 'minutes', 'hours', 'days', 'weeks', 'years', 'months'):
2684 add_one_type_printer(obj, 'chrono::duration', 'chrono::' + dur)
2685
2686 # Add type printers for <random> typedefs.
2687 add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand0')
2688 add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand')
2689 add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937')
2690 add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937_64')
2691 add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux24_base')
2692 add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux48_base')
2693 add_one_type_printer(obj, 'discard_block_engine', 'ranlux24')
2694 add_one_type_printer(obj, 'discard_block_engine', 'ranlux48')
2695 add_one_type_printer(obj, 'shuffle_order_engine', 'knuth_b')
2696
2697 # Add type printers for experimental::basic_string_view typedefs.
2698 ns = 'experimental::fundamentals_v1::'
2699 for ch in (('', 'char'),
2700 ('w', 'wchar_t'),
2701 ('u8', 'char8_t'),
2702 ('u16', 'char16_t'),
2703 ('u32', 'char32_t')):
2704 add_one_type_printer(obj, ns + 'basic_string_view',
2705 ns + ch[0] + 'string_view', ch[1])
2706
2707 # Do not show defaulted template arguments in class templates.
2708 add_one_template_type_printer(obj, 'unique_ptr',
2709 {1: 'std::default_delete<{0}>'})
2710 add_one_template_type_printer(obj, 'deque', {1: 'std::allocator<{0}>'})
2711 add_one_template_type_printer(
2712 obj, 'forward_list', {1: 'std::allocator<{0}>'})
2713 add_one_template_type_printer(obj, 'list', {1: 'std::allocator<{0}>'})
2714 add_one_template_type_printer(
2715 obj, '__cxx11::list', {1: 'std::allocator<{0}>'})
2716 add_one_template_type_printer(obj, 'vector', {1: 'std::allocator<{0}>'})
2717 add_one_template_type_printer(obj, 'map',
2718 {2: 'std::less<{0}>',
2719 3: 'std::allocator<std::pair<{0} const, {1}>>'})
2720 add_one_template_type_printer(obj, 'multimap',
2721 {2: 'std::less<{0}>',
2722 3: 'std::allocator<std::pair<{0} const, {1}>>'})
2723 add_one_template_type_printer(obj, 'set',
2724 {1: 'std::less<{0}>', 2: 'std::allocator<{0}>'})
2725 add_one_template_type_printer(obj, 'multiset',
2726 {1: 'std::less<{0}>', 2: 'std::allocator<{0}>'})
2727 add_one_template_type_printer(obj, 'unordered_map',
2728 {2: 'std::hash<{0}>',
2729 3: 'std::equal_to<{0}>',
2730 4: 'std::allocator<std::pair<{0} const, {1}>>'})
2731 add_one_template_type_printer(obj, 'unordered_multimap',
2732 {2: 'std::hash<{0}>',
2733 3: 'std::equal_to<{0}>',
2734 4: 'std::allocator<std::pair<{0} const, {1}>>'})
2735 add_one_template_type_printer(obj, 'unordered_set',
2736 {1: 'std::hash<{0}>',
2737 2: 'std::equal_to<{0}>',
2738 3: 'std::allocator<{0}>'})
2739 add_one_template_type_printer(obj, 'unordered_multiset',
2740 {1: 'std::hash<{0}>',
2741 2: 'std::equal_to<{0}>',
2742 3: 'std::allocator<{0}>'})
2743
2744
2745 def register_libstdcxx_printers(obj):
2746 """Register libstdc++ pretty-printers with objfile Obj."""
2747
2748 global _use_gdb_pp
2749 global libstdcxx_printer
2750
2751 if _use_gdb_pp:
2752 gdb.printing.register_pretty_printer(obj, libstdcxx_printer)
2753 else:
2754 if obj is None:
2755 obj = gdb
2756 obj.pretty_printers.append(libstdcxx_printer)
2757
2758 register_type_printers(obj)
2759
2760
2761 def build_libstdcxx_dictionary():
2762 global libstdcxx_printer
2763
2764 libstdcxx_printer = Printer("libstdc++-v6")
2765
2766 # libstdc++ objects requiring pretty-printing.
2767 # In order from:
2768 # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
2769 libstdcxx_printer.add_version('std::', 'basic_string', StdStringPrinter)
2770 libstdcxx_printer.add_version(
2771 'std::__cxx11::', 'basic_string', StdStringPrinter)
2772 libstdcxx_printer.add_container('std::', 'bitset', StdBitsetPrinter)
2773 libstdcxx_printer.add_container('std::', 'deque', StdDequePrinter)
2774 libstdcxx_printer.add_container('std::', 'list', StdListPrinter)
2775 libstdcxx_printer.add_container('std::__cxx11::', 'list', StdListPrinter)
2776 libstdcxx_printer.add_container('std::', 'map', StdMapPrinter)
2777 libstdcxx_printer.add_container('std::', 'multimap', StdMapPrinter)
2778 libstdcxx_printer.add_container('std::', 'multiset', StdSetPrinter)
2779 libstdcxx_printer.add_version('std::', 'pair', StdPairPrinter)
2780 libstdcxx_printer.add_version('std::', 'priority_queue',
2781 StdStackOrQueuePrinter)
2782 libstdcxx_printer.add_version('std::', 'queue', StdStackOrQueuePrinter)
2783 libstdcxx_printer.add_version('std::', 'tuple', StdTuplePrinter)
2784 libstdcxx_printer.add_container('std::', 'set', StdSetPrinter)
2785 libstdcxx_printer.add_version('std::', 'stack', StdStackOrQueuePrinter)
2786 libstdcxx_printer.add_version('std::', 'unique_ptr', UniquePointerPrinter)
2787 libstdcxx_printer.add_container('std::', 'vector', StdVectorPrinter)
2788 # vector<bool>
2789 libstdcxx_printer.add_version('std::', 'locale', StdLocalePrinter)
2790
2791 if hasattr(gdb.Value, 'dynamic_type'):
2792 libstdcxx_printer.add_version('std::', 'error_code',
2793 StdErrorCodePrinter)
2794 libstdcxx_printer.add_version('std::', 'error_condition',
2795 StdErrorCodePrinter)
2796
2797 # Printer registrations for classes compiled with -D_GLIBCXX_DEBUG.
2798 libstdcxx_printer.add('std::__debug::bitset', StdBitsetPrinter)
2799 libstdcxx_printer.add('std::__debug::deque', StdDequePrinter)
2800 libstdcxx_printer.add('std::__debug::list', StdListPrinter)
2801 libstdcxx_printer.add('std::__debug::map', StdMapPrinter)
2802 libstdcxx_printer.add('std::__debug::multimap', StdMapPrinter)
2803 libstdcxx_printer.add('std::__debug::multiset', StdSetPrinter)
2804 libstdcxx_printer.add('std::__debug::set', StdSetPrinter)
2805 libstdcxx_printer.add('std::__debug::vector', StdVectorPrinter)
2806
2807 # These are the TR1 and C++11 printers.
2808 # For array - the default GDB pretty-printer seems reasonable.
2809 libstdcxx_printer.add_version('std::', 'shared_ptr', SharedPointerPrinter)
2810 libstdcxx_printer.add_version('std::', 'weak_ptr', SharedPointerPrinter)
2811 libstdcxx_printer.add_container('std::', 'unordered_map',
2812 Tr1UnorderedMapPrinter)
2813 libstdcxx_printer.add_container('std::', 'unordered_set',
2814 Tr1UnorderedSetPrinter)
2815 libstdcxx_printer.add_container('std::', 'unordered_multimap',
2816 Tr1UnorderedMapPrinter)
2817 libstdcxx_printer.add_container('std::', 'unordered_multiset',
2818 Tr1UnorderedSetPrinter)
2819 libstdcxx_printer.add_container('std::', 'forward_list',
2820 StdForwardListPrinter)
2821
2822 libstdcxx_printer.add_version(
2823 'std::tr1::', 'shared_ptr', SharedPointerPrinter)
2824 libstdcxx_printer.add_version(
2825 'std::tr1::', 'weak_ptr', SharedPointerPrinter)
2826 libstdcxx_printer.add_version('std::tr1::', 'unordered_map',
2827 Tr1UnorderedMapPrinter)
2828 libstdcxx_printer.add_version('std::tr1::', 'unordered_set',
2829 Tr1UnorderedSetPrinter)
2830 libstdcxx_printer.add_version('std::tr1::', 'unordered_multimap',
2831 Tr1UnorderedMapPrinter)
2832 libstdcxx_printer.add_version('std::tr1::', 'unordered_multiset',
2833 Tr1UnorderedSetPrinter)
2834
2835 libstdcxx_printer.add_version('std::', 'initializer_list',
2836 StdInitializerListPrinter)
2837 libstdcxx_printer.add_version('std::', 'atomic', StdAtomicPrinter)
2838 libstdcxx_printer.add_version(
2839 'std::', 'basic_stringbuf', StdStringBufPrinter)
2840 libstdcxx_printer.add_version(
2841 'std::__cxx11::', 'basic_stringbuf', StdStringBufPrinter)
2842 for sstream in ('istringstream', 'ostringstream', 'stringstream'):
2843 libstdcxx_printer.add_version(
2844 'std::', 'basic_' + sstream, StdStringStreamPrinter)
2845 libstdcxx_printer.add_version(
2846 'std::__cxx11::', 'basic_' + sstream, StdStringStreamPrinter)
2847
2848 libstdcxx_printer.add_version('std::chrono::', 'duration',
2849 StdChronoDurationPrinter)
2850 libstdcxx_printer.add_version('std::chrono::', 'time_point',
2851 StdChronoTimePointPrinter)
2852
2853 # std::regex components
2854 libstdcxx_printer.add_version('std::__detail::', '_State',
2855 StdRegexStatePrinter)
2856
2857 # These are the C++11 printer registrations for -D_GLIBCXX_DEBUG cases.
2858 # The tr1 namespace containers do not have any debug equivalents,
2859 # so do not register printers for them.
2860 libstdcxx_printer.add('std::__debug::unordered_map',
2861 Tr1UnorderedMapPrinter)
2862 libstdcxx_printer.add('std::__debug::unordered_set',
2863 Tr1UnorderedSetPrinter)
2864 libstdcxx_printer.add('std::__debug::unordered_multimap',
2865 Tr1UnorderedMapPrinter)
2866 libstdcxx_printer.add('std::__debug::unordered_multiset',
2867 Tr1UnorderedSetPrinter)
2868 libstdcxx_printer.add('std::__debug::forward_list',
2869 StdForwardListPrinter)
2870
2871 # Library Fundamentals TS components
2872 libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
2873 'any', StdExpAnyPrinter)
2874 libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
2875 'optional', StdExpOptionalPrinter)
2876 libstdcxx_printer.add_version('std::experimental::fundamentals_v1::',
2877 'basic_string_view', StdExpStringViewPrinter)
2878 # Filesystem TS components
2879 libstdcxx_printer.add_version('std::experimental::filesystem::v1::',
2880 'path', StdExpPathPrinter)
2881 libstdcxx_printer.add_version('std::experimental::filesystem::v1::__cxx11::',
2882 'path', StdExpPathPrinter)
2883 libstdcxx_printer.add_version('std::filesystem::',
2884 'path', StdPathPrinter)
2885 libstdcxx_printer.add_version('std::filesystem::__cxx11::',
2886 'path', StdPathPrinter)
2887
2888 # C++17 components
2889 libstdcxx_printer.add_version('std::',
2890 'any', StdExpAnyPrinter)
2891 libstdcxx_printer.add_version('std::',
2892 'optional', StdExpOptionalPrinter)
2893 libstdcxx_printer.add_version('std::',
2894 'basic_string_view', StdExpStringViewPrinter)
2895 libstdcxx_printer.add_version('std::',
2896 'variant', StdVariantPrinter)
2897 libstdcxx_printer.add_version('std::',
2898 '_Node_handle', StdNodeHandlePrinter)
2899
2900 # C++20 components
2901 libstdcxx_printer.add_version(
2902 'std::', 'partial_ordering', StdCmpCatPrinter)
2903 libstdcxx_printer.add_version('std::', 'weak_ordering', StdCmpCatPrinter)
2904 libstdcxx_printer.add_version('std::', 'strong_ordering', StdCmpCatPrinter)
2905 libstdcxx_printer.add_version('std::', 'span', StdSpanPrinter)
2906 libstdcxx_printer.add_version('std::', 'basic_format_args',
2907 StdFormatArgsPrinter)
2908 for c in ['day', 'month', 'year', 'weekday', 'weekday_indexed', 'weekday_last',
2909 'month_day', 'month_day_last', 'month_weekday', 'month_weekday_last',
2910 'year_month', 'year_month_day', 'year_month_day_last',
2911 'year_month_weekday', 'year_month_weekday_last', 'hh_mm_ss']:
2912 libstdcxx_printer.add_version('std::chrono::', c,
2913 StdChronoCalendarPrinter)
2914 libstdcxx_printer.add_version('std::chrono::', 'time_zone',
2915 StdChronoTimeZonePrinter)
2916 libstdcxx_printer.add_version('std::chrono::', 'time_zone_link',
2917 StdChronoTimeZonePrinter)
2918 libstdcxx_printer.add_version('std::chrono::', 'zoned_time',
2919 StdChronoZonedTimePrinter)
2920 libstdcxx_printer.add_version('std::chrono::', 'leap_second',
2921 StdChronoLeapSecondPrinter)
2922 libstdcxx_printer.add_version(
2923 'std::chrono::', 'tzdb', StdChronoTzdbPrinter)
2924 # libstdcxx_printer.add_version('std::chrono::(anonymous namespace)', 'Rule',
2925 # StdChronoTimeZoneRulePrinter)
2926
2927 # Extensions.
2928 libstdcxx_printer.add_version('__gnu_cxx::', 'slist', StdSlistPrinter)
2929
2930 if True:
2931 # These shouldn't be necessary, if GDB "print *i" worked.
2932 # But it often doesn't, so here they are.
2933 libstdcxx_printer.add_container('std::', '_List_iterator',
2934 StdListIteratorPrinter)
2935 libstdcxx_printer.add_container('std::', '_List_const_iterator',
2936 StdListIteratorPrinter)
2937 libstdcxx_printer.add_version('std::', '_Rb_tree_iterator',
2938 StdRbtreeIteratorPrinter)
2939 libstdcxx_printer.add_version('std::', '_Rb_tree_const_iterator',
2940 StdRbtreeIteratorPrinter)
2941 libstdcxx_printer.add_container('std::', '_Deque_iterator',
2942 StdDequeIteratorPrinter)
2943 libstdcxx_printer.add_container('std::', '_Deque_const_iterator',
2944 StdDequeIteratorPrinter)
2945 libstdcxx_printer.add_version('__gnu_cxx::', '__normal_iterator',
2946 StdVectorIteratorPrinter)
2947 libstdcxx_printer.add_container('std::', '_Bit_iterator',
2948 StdBitIteratorPrinter)
2949 libstdcxx_printer.add_container('std::', '_Bit_const_iterator',
2950 StdBitIteratorPrinter)
2951 libstdcxx_printer.add_container('std::', '_Bit_reference',
2952 StdBitReferencePrinter)
2953 libstdcxx_printer.add_version('__gnu_cxx::', '_Slist_iterator',
2954 StdSlistIteratorPrinter)
2955 libstdcxx_printer.add_container('std::', '_Fwd_list_iterator',
2956 StdFwdListIteratorPrinter)
2957 libstdcxx_printer.add_container('std::', '_Fwd_list_const_iterator',
2958 StdFwdListIteratorPrinter)
2959
2960 # Debug (compiled with -D_GLIBCXX_DEBUG) printer
2961 # registrations.
2962 libstdcxx_printer.add('__gnu_debug::_Safe_iterator',
2963 StdDebugIteratorPrinter)
2964
2965
2966 build_libstdcxx_dictionary()