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