Debian Codegraph @

libstdc++-v3/python/libstdcxx/v6/printers.py

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