1# Pretty-printers for libstdc++.
2
3# Copyright (C) 2008-2013 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        search = str(typ) + '::' + name
89        try:
90            return gdb.lookup_type(search)
91        except RuntimeError:
92            pass
93        # The type was not found, so try the superclass.  We only need
94        # to check the first superclass, so we don't bother with
95        # anything fancier here.
96        field = typ.fields()[0]
97        if not field.is_base_class:
98            raise ValueError("Cannot find type %s::%s" % (str(orig), name))
99        typ = field.type
100
101class SharedPointerPrinter:
102    "Print a shared_ptr or weak_ptr"
103
104    def __init__ (self, typename, val):
105        self.typename = typename
106        self.val = val
107
108    def to_string (self):
109        state = 'empty'
110        refcounts = self.val['_M_refcount']['_M_pi']
111        if refcounts != 0:
112            usecount = refcounts['_M_use_count']
113            weakcount = refcounts['_M_weak_count']
114            if usecount == 0:
115                state = 'expired, weak %d' % weakcount
116            else:
117                state = 'count %d, weak %d' % (usecount, weakcount - 1)
118        return '%s (%s) %s' % (self.typename, state, self.val['_M_ptr'])
119
120class UniquePointerPrinter:
121    "Print a unique_ptr"
122
123    def __init__ (self, typename, val):
124        self.val = val
125
126    def to_string (self):
127        v = self.val['_M_t']['_M_head_impl']
128        return ('std::unique_ptr<%s> containing %s' % (str(v.type.target()),
129                                                       str(v)))
130
131class StdListPrinter:
132    "Print a std::list"
133
134    class _iterator(Iterator):
135        def __init__(self, nodetype, head):
136            self.nodetype = nodetype
137            self.base = head['_M_next']
138            self.head = head.address
139            self.count = 0
140
141        def __iter__(self):
142            return self
143
144        def __next__(self):
145            if self.base == self.head:
146                raise StopIteration
147            elt = self.base.cast(self.nodetype).dereference()
148            self.base = elt['_M_next']
149            count = self.count
150            self.count = self.count + 1
151            return ('[%d]' % count, elt['_M_data'])
152
153    def __init__(self, typename, val):
154        self.typename = typename
155        self.val = val
156
157    def children(self):
158        nodetype = find_type(self.val.type, '_Node')
159        nodetype = nodetype.strip_typedefs().pointer()
160        return self._iterator(nodetype, self.val['_M_impl']['_M_node'])
161
162    def to_string(self):
163        if self.val['_M_impl']['_M_node'].address == self.val['_M_impl']['_M_node']['_M_next']:
164            return 'empty %s' % (self.typename)
165        return '%s' % (self.typename)
166
167class StdListIteratorPrinter:
168    "Print std::list::iterator"
169
170    def __init__(self, typename, val):
171        self.val = val
172        self.typename = typename
173
174    def to_string(self):
175        nodetype = find_type(self.val.type, '_Node')
176        nodetype = nodetype.strip_typedefs().pointer()
177        return self.val['_M_node'].cast(nodetype).dereference()['_M_data']
178
179class StdSlistPrinter:
180    "Print a __gnu_cxx::slist"
181
182    class _iterator(Iterator):
183        def __init__(self, nodetype, head):
184            self.nodetype = nodetype
185            self.base = head['_M_head']['_M_next']
186            self.count = 0
187
188        def __iter__(self):
189            return self
190
191        def __next__(self):
192            if self.base == 0:
193                raise StopIteration
194            elt = self.base.cast(self.nodetype).dereference()
195            self.base = elt['_M_next']
196            count = self.count
197            self.count = self.count + 1
198            return ('[%d]' % count, elt['_M_data'])
199
200    def __init__(self, typename, val):
201        self.val = val
202
203    def children(self):
204        nodetype = find_type(self.val.type, '_Node')
205        nodetype = nodetype.strip_typedefs().pointer()
206        return self._iterator(nodetype, self.val)
207
208    def to_string(self):
209        if self.val['_M_head']['_M_next'] == 0:
210            return 'empty __gnu_cxx::slist'
211        return '__gnu_cxx::slist'
212
213class StdSlistIteratorPrinter:
214    "Print __gnu_cxx::slist::iterator"
215
216    def __init__(self, typename, val):
217        self.val = val
218
219    def to_string(self):
220        nodetype = find_type(self.val.type, '_Node')
221        nodetype = nodetype.strip_typedefs().pointer()
222        return self.val['_M_node'].cast(nodetype).dereference()['_M_data']
223
224class StdVectorPrinter:
225    "Print a std::vector"
226
227    class _iterator(Iterator):
228        def __init__ (self, start, finish, bitvec):
229            self.bitvec = bitvec
230            if bitvec:
231                self.item   = start['_M_p']
232                self.so     = start['_M_offset']
233                self.finish = finish['_M_p']
234                self.fo     = finish['_M_offset']
235                itype = self.item.dereference().type
236                self.isize = 8 * itype.sizeof
237            else:
238                self.item = start
239                self.finish = finish
240            self.count = 0
241
242        def __iter__(self):
243            return self
244
245        def __next__(self):
246            count = self.count
247            self.count = self.count + 1
248            if self.bitvec:
249                if self.item == self.finish and self.so >= self.fo:
250                    raise StopIteration
251                elt = self.item.dereference()
252                if elt & (1 << self.so):
253                    obit = 1
254                else:
255                    obit = 0
256                self.so = self.so + 1
257                if self.so >= self.isize:
258                    self.item = self.item + 1
259                    self.so = 0
260                return ('[%d]' % count, obit)
261            else:
262                if self.item == self.finish:
263                    raise StopIteration
264                elt = self.item.dereference()
265                self.item = self.item + 1
266                return ('[%d]' % count, elt)
267
268    def __init__(self, typename, val):
269        self.typename = typename
270        self.val = val
271        self.is_bool = val.type.template_argument(0).code  == gdb.TYPE_CODE_BOOL
272
273    def children(self):
274        return self._iterator(self.val['_M_impl']['_M_start'],
275                              self.val['_M_impl']['_M_finish'],
276                              self.is_bool)
277
278    def to_string(self):
279        start = self.val['_M_impl']['_M_start']
280        finish = self.val['_M_impl']['_M_finish']
281        end = self.val['_M_impl']['_M_end_of_storage']
282        if self.is_bool:
283            start = self.val['_M_impl']['_M_start']['_M_p']
284            so    = self.val['_M_impl']['_M_start']['_M_offset']
285            finish = self.val['_M_impl']['_M_finish']['_M_p']
286            fo     = self.val['_M_impl']['_M_finish']['_M_offset']
287            itype = start.dereference().type
288            bl = 8 * itype.sizeof
289            length   = (bl - so) + bl * ((finish - start) - 1) + fo
290            capacity = bl * (end - start)
291            return ('%s<bool> of length %d, capacity %d'
292                    % (self.typename, int (length), int (capacity)))
293        else:
294            return ('%s of length %d, capacity %d'
295                    % (self.typename, int (finish - start), int (end - start)))
296
297    def display_hint(self):
298        return 'array'
299
300class StdVectorIteratorPrinter:
301    "Print std::vector::iterator"
302
303    def __init__(self, typename, val):
304        self.val = val
305
306    def to_string(self):
307        return self.val['_M_current'].dereference()
308
309class StdTuplePrinter:
310    "Print a std::tuple"
311
312    class _iterator(Iterator):
313        def __init__ (self, head):
314            self.head = head
315
316            # Set the base class as the initial head of the
317            # tuple.
318            nodes = self.head.type.fields ()
319            if len (nodes) == 1:
320                # Set the actual head to the first pair.
321                self.head  = self.head.cast (nodes[0].type)
322            elif len (nodes) != 0:
323                raise ValueError("Top of tuple tree does not consist of a single node.")
324            self.count = 0
325
326        def __iter__ (self):
327            return self
328
329        def __next__ (self):
330            nodes = self.head.type.fields ()
331            # Check for further recursions in the inheritance tree.
332            if len (nodes) == 0:
333                raise StopIteration
334            # Check that this iteration has an expected structure.
335            if len (nodes) != 2:
336                raise ValueError("Cannot parse more than 2 nodes in a tuple tree.")
337
338            # - Left node is the next recursion parent.
339            # - Right node is the actual class contained in the tuple.
340
341            # Process right node.
342            impl = self.head.cast (nodes[1].type)
343
344            # Process left node and set it as head.
345            self.head  = self.head.cast (nodes[0].type)
346            self.count = self.count + 1
347
348            # Finally, check the implementation.  If it is
349            # wrapped in _M_head_impl return that, otherwise return
350            # the value "as is".
351            fields = impl.type.fields ()
352            if len (fields) < 1 or fields[0].name != "_M_head_impl":
353                return ('[%d]' % self.count, impl)
354            else:
355                return ('[%d]' % self.count, impl['_M_head_impl'])
356
357    def __init__ (self, typename, val):
358        self.typename = typename
359        self.val = val;
360
361    def children (self):
362        return self._iterator (self.val)
363
364    def to_string (self):
365        if len (self.val.type.fields ()) == 0:
366            return 'empty %s' % (self.typename)
367        return '%s containing' % (self.typename)
368
369class StdStackOrQueuePrinter:
370    "Print a std::stack or std::queue"
371
372    def __init__ (self, typename, val):
373        self.typename = typename
374        self.visualizer = gdb.default_visualizer(val['c'])
375
376    def children (self):
377        return self.visualizer.children()
378
379    def to_string (self):
380        return '%s wrapping: %s' % (self.typename,
381                                    self.visualizer.to_string())
382
383    def display_hint (self):
384        if hasattr (self.visualizer, 'display_hint'):
385            return self.visualizer.display_hint ()
386        return None
387
388class RbtreeIterator(Iterator):
389    def __init__(self, rbtree):
390        self.size = rbtree['_M_t']['_M_impl']['_M_node_count']
391        self.node = rbtree['_M_t']['_M_impl']['_M_header']['_M_left']
392        self.count = 0
393
394    def __iter__(self):
395        return self
396
397    def __len__(self):
398        return int (self.size)
399
400    def __next__(self):
401        if self.count == self.size:
402            raise StopIteration
403        result = self.node
404        self.count = self.count + 1
405        if self.count < self.size:
406            # Compute the next node.
407            node = self.node
408            if node.dereference()['_M_right']:
409                node = node.dereference()['_M_right']
410                while node.dereference()['_M_left']:
411                    node = node.dereference()['_M_left']
412            else:
413                parent = node.dereference()['_M_parent']
414                while node == parent.dereference()['_M_right']:
415                    node = parent
416                    parent = parent.dereference()['_M_parent']
417                if node.dereference()['_M_right'] != parent:
418                    node = parent
419            self.node = node
420        return result
421
422# This is a pretty printer for std::_Rb_tree_iterator (which is
423# std::map::iterator), and has nothing to do with the RbtreeIterator
424# class above.
425class StdRbtreeIteratorPrinter:
426    "Print std::map::iterator"
427
428    def __init__ (self, typename, val):
429        self.val = val
430
431    def to_string (self):
432        typename = str(self.val.type.strip_typedefs()) + '::_Link_type'
433        nodetype = gdb.lookup_type(typename).strip_typedefs()
434        return self.val.cast(nodetype).dereference()['_M_value_field']
435
436class StdDebugIteratorPrinter:
437    "Print a debug enabled version of an iterator"
438
439    def __init__ (self, typename, val):
440        self.val = val
441
442    # Just strip away the encapsulating __gnu_debug::_Safe_iterator
443    # and return the wrapped iterator value.
444    def to_string (self):
445        itype = self.val.type.template_argument(0)
446        return self.val['_M_current'].cast(itype)
447
448class StdMapPrinter:
449    "Print a std::map or std::multimap"
450
451    # Turn an RbtreeIterator into a pretty-print iterator.
452    class _iter(Iterator):
453        def __init__(self, rbiter, type):
454            self.rbiter = rbiter
455            self.count = 0
456            self.type = type
457
458        def __iter__(self):
459            return self
460
461        def __next__(self):
462            if self.count % 2 == 0:
463                n = next(self.rbiter)
464                n = n.cast(self.type).dereference()['_M_value_field']
465                self.pair = n
466                item = n['first']
467            else:
468                item = self.pair['second']
469            result = ('[%d]' % self.count, item)
470            self.count = self.count + 1
471            return result
472
473    def __init__ (self, typename, val):
474        self.typename = typename
475        self.val = val
476
477    def to_string (self):
478        return '%s with %d elements' % (self.typename,
479                                        len (RbtreeIterator (self.val)))
480
481    def children (self):
482        rep_type = find_type(self.val.type, '_Rep_type')
483        node = find_type(rep_type, '_Link_type')
484        node = node.strip_typedefs()
485        return self._iter (RbtreeIterator (self.val), node)
486
487    def display_hint (self):
488        return 'map'
489
490class StdSetPrinter:
491    "Print a std::set or std::multiset"
492
493    # Turn an RbtreeIterator into a pretty-print iterator.
494    class _iter(Iterator):
495        def __init__(self, rbiter, type):
496            self.rbiter = rbiter
497            self.count = 0
498            self.type = type
499
500        def __iter__(self):
501            return self
502
503        def __next__(self):
504            item = next(self.rbiter)
505            item = item.cast(self.type).dereference()['_M_value_field']
506            # FIXME: this is weird ... what to do?
507            # Maybe a 'set' display hint?
508            result = ('[%d]' % self.count, item)
509            self.count = self.count + 1
510            return result
511
512    def __init__ (self, typename, val):
513        self.typename = typename
514        self.val = val
515
516    def to_string (self):
517        return '%s with %d elements' % (self.typename,
518                                        len (RbtreeIterator (self.val)))
519
520    def children (self):
521        rep_type = find_type(self.val.type, '_Rep_type')
522        node = find_type(rep_type, '_Link_type')
523        node = node.strip_typedefs()
524        return self._iter (RbtreeIterator (self.val), node)
525
526class StdBitsetPrinter:
527    "Print a std::bitset"
528
529    def __init__(self, typename, val):
530        self.typename = typename
531        self.val = val
532
533    def to_string (self):
534        # If template_argument handled values, we could print the
535        # size.  Or we could use a regexp on the type.
536        return '%s' % (self.typename)
537
538    def children (self):
539        words = self.val['_M_w']
540        wtype = words.type
541
542        # The _M_w member can be either an unsigned long, or an
543        # array.  This depends on the template specialization used.
544        # If it is a single long, convert to a single element list.
545        if wtype.code == gdb.TYPE_CODE_ARRAY:
546            tsize = wtype.target ().sizeof
547        else:
548            words = [words]
549            tsize = wtype.sizeof
550
551        nwords = wtype.sizeof / tsize
552        result = []
553        byte = 0
554        while byte < nwords:
555            w = words[byte]
556            bit = 0
557            while w != 0:
558                if (w & 1) != 0:
559                    # Another spot where we could use 'set'?
560                    result.append(('[%d]' % (byte * tsize * 8 + bit), 1))
561                bit = bit + 1
562                w = w >> 1
563            byte = byte + 1
564        return result
565
566class StdDequePrinter:
567    "Print a std::deque"
568
569    class _iter(Iterator):
570        def __init__(self, node, start, end, last, buffer_size):
571            self.node = node
572            self.p = start
573            self.end = end
574            self.last = last
575            self.buffer_size = buffer_size
576            self.count = 0
577
578        def __iter__(self):
579            return self
580
581        def __next__(self):
582            if self.p == self.last:
583                raise StopIteration
584
585            result = ('[%d]' % self.count, self.p.dereference())
586            self.count = self.count + 1
587
588            # Advance the 'cur' pointer.
589            self.p = self.p + 1
590            if self.p == self.end:
591                # If we got to the end of this bucket, move to the
592                # next bucket.
593                self.node = self.node + 1
594                self.p = self.node[0]
595                self.end = self.p + self.buffer_size
596
597            return result
598
599    def __init__(self, typename, val):
600        self.typename = typename
601        self.val = val
602        self.elttype = val.type.template_argument(0)
603        size = self.elttype.sizeof
604        if size < 512:
605            self.buffer_size = int (512 / size)
606        else:
607            self.buffer_size = 1
608
609    def to_string(self):
610        start = self.val['_M_impl']['_M_start']
611        end = self.val['_M_impl']['_M_finish']
612
613        delta_n = end['_M_node'] - start['_M_node'] - 1
614        delta_s = start['_M_last'] - start['_M_cur']
615        delta_e = end['_M_cur'] - end['_M_first']
616
617        size = self.buffer_size * delta_n + delta_s + delta_e
618
619        return '%s with %d elements' % (self.typename, long (size))
620
621    def children(self):
622        start = self.val['_M_impl']['_M_start']
623        end = self.val['_M_impl']['_M_finish']
624        return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
625                          end['_M_cur'], self.buffer_size)
626
627    def display_hint (self):
628        return 'array'
629
630class StdDequeIteratorPrinter:
631    "Print std::deque::iterator"
632
633    def __init__(self, typename, val):
634        self.val = val
635
636    def to_string(self):
637        return self.val['_M_cur'].dereference()
638
639class StdStringPrinter:
640    "Print a std::basic_string of some kind"
641
642    def __init__(self, typename, val):
643        self.val = val
644
645    def to_string(self):
646        # Make sure &string works, too.
647        type = self.val.type
648        if type.code == gdb.TYPE_CODE_REF:
649            type = type.target ()
650
651        # Calculate the length of the string so that to_string returns
652        # the string according to length, not according to first null
653        # encountered.
654        ptr = self.val ['_M_dataplus']['_M_p']
655        realtype = type.unqualified ().strip_typedefs ()
656        reptype = gdb.lookup_type (str (realtype) + '::_Rep').pointer ()
657        header = ptr.cast(reptype) - 1
658        len = header.dereference ()['_M_length']
659        if hasattr(ptr, "lazy_string"):
660            return ptr.lazy_string (length = len)
661        return ptr.string (length = len)
662
663    def display_hint (self):
664        return 'string'
665
666class Tr1HashtableIterator(Iterator):
667    def __init__ (self, hash):
668        self.node = hash['_M_bbegin']['_M_node']['_M_nxt']
669        self.node_type = find_type(hash.type, '__node_type').pointer()
670
671    def __iter__ (self):
672        return self
673
674    def __next__ (self):
675        if self.node == 0:
676            raise StopIteration
677        node = self.node.cast(self.node_type)
678        result = node.dereference()['_M_v']
679        self.node = node.dereference()['_M_nxt']
680        return result
681
682class Tr1UnorderedSetPrinter:
683    "Print a tr1::unordered_set"
684
685    def __init__ (self, typename, val):
686        self.typename = typename
687        self.val = val
688
689    def hashtable (self):
690        if self.typename.startswith('std::tr1'):
691            return self.val
692        return self.val['_M_h']
693
694    def to_string (self):
695        return '%s with %d elements' % (self.typename, self.hashtable()['_M_element_count'])
696
697    @staticmethod
698    def format_count (i):
699        return '[%d]' % i
700
701    def children (self):
702        counter = imap (self.format_count, itertools.count())
703        return izip (counter, Tr1HashtableIterator (self.hashtable()))
704
705class Tr1UnorderedMapPrinter:
706    "Print a tr1::unordered_map"
707
708    def __init__ (self, typename, val):
709        self.typename = typename
710        self.val = val
711
712    def hashtable (self):
713        if self.typename.startswith('std::tr1'):
714            return self.val
715        return self.val['_M_h']
716
717    def to_string (self):
718        return '%s with %d elements' % (self.typename, self.hashtable()['_M_element_count'])
719
720    @staticmethod
721    def flatten (list):
722        for elt in list:
723            for i in elt:
724                yield i
725
726    @staticmethod
727    def format_one (elt):
728        return (elt['first'], elt['second'])
729
730    @staticmethod
731    def format_count (i):
732        return '[%d]' % i
733
734    def children (self):
735        counter = imap (self.format_count, itertools.count())
736        # Map over the hash table and flatten the result.
737        data = self.flatten (imap (self.format_one, Tr1HashtableIterator (self.hashtable())))
738        # Zip the two iterators together.
739        return izip (counter, data)
740
741    def display_hint (self):
742        return 'map'
743
744class StdForwardListPrinter:
745    "Print a std::forward_list"
746
747    class _iterator(Iterator):
748        def __init__(self, nodetype, head):
749            self.nodetype = nodetype
750            self.base = head['_M_next']
751            self.count = 0
752
753        def __iter__(self):
754            return self
755
756        def __next__(self):
757            if self.base == 0:
758                raise StopIteration
759            elt = self.base.cast(self.nodetype).dereference()
760            self.base = elt['_M_next']
761            count = self.count
762            self.count = self.count + 1
763            valptr = elt['_M_storage'].address
764            valptr = valptr.cast(elt.type.template_argument(0).pointer())
765            return ('[%d]' % count, valptr.dereference())
766
767    def __init__(self, typename, val):
768        self.val = val
769        self.typename = typename
770
771    def children(self):
772        nodetype = find_type(self.val.type, '_Node')
773        nodetype = nodetype.strip_typedefs().pointer()
774        return self._iterator(nodetype, self.val['_M_impl']['_M_head'])
775
776    def to_string(self):
777        if self.val['_M_impl']['_M_head']['_M_next'] == 0:
778            return 'empty %s' % (self.typename)
779        return '%s' % (self.typename)
780
781
782# A "regular expression" printer which conforms to the
783# "SubPrettyPrinter" protocol from gdb.printing.
784class RxPrinter(object):
785    def __init__(self, name, function):
786        super(RxPrinter, self).__init__()
787        self.name = name
788        self.function = function
789        self.enabled = True
790
791    def invoke(self, value):
792        if not self.enabled:
793            return None
794        return self.function(self.name, value)
795
796# A pretty-printer that conforms to the "PrettyPrinter" protocol from
797# gdb.printing.  It can also be used directly as an old-style printer.
798class Printer(object):
799    def __init__(self, name):
800        super(Printer, self).__init__()
801        self.name = name
802        self.subprinters = []
803        self.lookup = {}
804        self.enabled = True
805        self.compiled_rx = re.compile('^([a-zA-Z0-9_:]+)<.*>$')
806
807    def add(self, name, function):
808        # A small sanity check.
809        # FIXME
810        if not self.compiled_rx.match(name + '<>'):
811            raise ValueError('libstdc++ programming error: "%s" does not match' % name)
812        printer = RxPrinter(name, function)
813        self.subprinters.append(printer)
814        self.lookup[name] = printer
815
816    # Add a name using _GLIBCXX_BEGIN_NAMESPACE_VERSION.
817    def add_version(self, base, name, function):
818        self.add(base + name, function)
819        self.add(base + '__7::' + name, function)
820
821    # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
822    def add_container(self, base, name, function):
823        self.add_version(base, name, function)
824        self.add_version(base + '__cxx1998::', name, function)
825
826    @staticmethod
827    def get_basic_type(type):
828        # If it points to a reference, get the reference.
829        if type.code == gdb.TYPE_CODE_REF:
830            type = type.target ()
831
832        # Get the unqualified type, stripped of typedefs.
833        type = type.unqualified ().strip_typedefs ()
834
835        return type.tag
836
837    def __call__(self, val):
838        typename = self.get_basic_type(val.type)
839        if not typename:
840            return None
841
842        # All the types we match are template types, so we can use a
843        # dictionary.
844        match = self.compiled_rx.match(typename)
845        if not match:
846            return None
847
848        basename = match.group(1)
849        if basename in self.lookup:
850            return self.lookup[basename].invoke(val)
851
852        # Cannot find a pretty printer.  Return None.
853        return None
854
855libstdcxx_printer = None
856
857class FilteringTypePrinter(object):
858    def __init__(self, match, name):
859        self.match = match
860        self.name = name
861        self.enabled = True
862
863    class _recognizer(object):
864        def __init__(self, match, name):
865            self.match = match
866            self.name = name
867            self.type_obj = None
868
869        def recognize(self, type_obj):
870            if type_obj.tag is None:
871                return None
872
873            if self.type_obj is None:
874                if not self.match in type_obj.tag:
875                    # Filter didn't match.
876                    return None
877                try:
878                    self.type_obj = gdb.lookup_type(self.name).strip_typedefs()
879                except:
880                    pass
881            if self.type_obj == type_obj:
882                return self.name
883            return None
884
885    def instantiate(self):
886        return self._recognizer(self.match, self.name)
887
888def add_one_type_printer(obj, match, name):
889    printer = FilteringTypePrinter(match, 'std::' + name)
890    gdb.types.register_type_printer(obj, printer)
891
892def register_type_printers(obj):
893    global _use_type_printing
894
895    if not _use_type_printing:
896        return
897
898    for pfx in ('', 'w'):
899        add_one_type_printer(obj, 'basic_string', pfx + 'string')
900        add_one_type_printer(obj, 'basic_ios', pfx + 'ios')
901        add_one_type_printer(obj, 'basic_streambuf', pfx + 'streambuf')
902        add_one_type_printer(obj, 'basic_istream', pfx + 'istream')
903        add_one_type_printer(obj, 'basic_ostream', pfx + 'ostream')
904        add_one_type_printer(obj, 'basic_iostream', pfx + 'iostream')
905        add_one_type_printer(obj, 'basic_stringbuf', pfx + 'stringbuf')
906        add_one_type_printer(obj, 'basic_istringstream',
907                                 pfx + 'istringstream')
908        add_one_type_printer(obj, 'basic_ostringstream',
909                                 pfx + 'ostringstream')
910        add_one_type_printer(obj, 'basic_stringstream',
911                                 pfx + 'stringstream')
912        add_one_type_printer(obj, 'basic_filebuf', pfx + 'filebuf')
913        add_one_type_printer(obj, 'basic_ifstream', pfx + 'ifstream')
914        add_one_type_printer(obj, 'basic_ofstream', pfx + 'ofstream')
915        add_one_type_printer(obj, 'basic_fstream', pfx + 'fstream')
916        add_one_type_printer(obj, 'basic_regex', pfx + 'regex')
917        add_one_type_printer(obj, 'sub_match', pfx + 'csub_match')
918        add_one_type_printer(obj, 'sub_match', pfx + 'ssub_match')
919        add_one_type_printer(obj, 'match_results', pfx + 'cmatch')
920        add_one_type_printer(obj, 'match_results', pfx + 'smatch')
921        add_one_type_printer(obj, 'regex_iterator', pfx + 'cregex_iterator')
922        add_one_type_printer(obj, 'regex_iterator', pfx + 'sregex_iterator')
923        add_one_type_printer(obj, 'regex_token_iterator',
924                                 pfx + 'cregex_token_iterator')
925        add_one_type_printer(obj, 'regex_token_iterator',
926                                 pfx + 'sregex_token_iterator')
927
928    # Note that we can't have a printer for std::wstreampos, because
929    # it shares the same underlying type as std::streampos.
930    add_one_type_printer(obj, 'fpos', 'streampos')
931    add_one_type_printer(obj, 'basic_string', 'u16string')
932    add_one_type_printer(obj, 'basic_string', 'u32string')
933
934    for dur in ('nanoseconds', 'microseconds', 'milliseconds',
935                'seconds', 'minutes', 'hours'):
936        add_one_type_printer(obj, 'duration', dur)
937
938    add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand0')
939    add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand')
940    add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937')
941    add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937_64')
942    add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux24_base')
943    add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux48_base')
944    add_one_type_printer(obj, 'discard_block_engine', 'ranlux24')
945    add_one_type_printer(obj, 'discard_block_engine', 'ranlux48')
946    add_one_type_printer(obj, 'shuffle_order_engine', 'knuth_b')
947
948def register_libstdcxx_printers (obj):
949    "Register libstdc++ pretty-printers with objfile Obj."
950
951    global _use_gdb_pp
952    global libstdcxx_printer
953
954    if _use_gdb_pp:
955        gdb.printing.register_pretty_printer(obj, libstdcxx_printer)
956    else:
957        if obj is None:
958            obj = gdb
959        obj.pretty_printers.append(libstdcxx_printer)
960
961    register_type_printers(obj)
962
963def build_libstdcxx_dictionary ():
964    global libstdcxx_printer
965
966    libstdcxx_printer = Printer("libstdc++-v6")
967
968    # For _GLIBCXX_BEGIN_NAMESPACE_VERSION.
969    vers = '(__7::)?'
970    # For _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
971    container = '(__cxx1998::' + vers + ')?'
972
973    # libstdc++ objects requiring pretty-printing.
974    # In order from:
975    # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
976    libstdcxx_printer.add_version('std::', 'basic_string', StdStringPrinter)
977    libstdcxx_printer.add_container('std::', 'bitset', StdBitsetPrinter)
978    libstdcxx_printer.add_container('std::', 'deque', StdDequePrinter)
979    libstdcxx_printer.add_container('std::', 'list', StdListPrinter)
980    libstdcxx_printer.add_container('std::', 'map', StdMapPrinter)
981    libstdcxx_printer.add_container('std::', 'multimap', StdMapPrinter)
982    libstdcxx_printer.add_container('std::', 'multiset', StdSetPrinter)
983    libstdcxx_printer.add_version('std::', 'priority_queue',
984                                  StdStackOrQueuePrinter)
985    libstdcxx_printer.add_version('std::', 'queue', StdStackOrQueuePrinter)
986    libstdcxx_printer.add_version('std::', 'tuple', StdTuplePrinter)
987    libstdcxx_printer.add_container('std::', 'set', StdSetPrinter)
988    libstdcxx_printer.add_version('std::', 'stack', StdStackOrQueuePrinter)
989    libstdcxx_printer.add_version('std::', 'unique_ptr', UniquePointerPrinter)
990    libstdcxx_printer.add_container('std::', 'vector', StdVectorPrinter)
991    # vector<bool>
992
993    # Printer registrations for classes compiled with -D_GLIBCXX_DEBUG.
994    libstdcxx_printer.add('std::__debug::bitset', StdBitsetPrinter)
995    libstdcxx_printer.add('std::__debug::deque', StdDequePrinter)
996    libstdcxx_printer.add('std::__debug::list', StdListPrinter)
997    libstdcxx_printer.add('std::__debug::map', StdMapPrinter)
998    libstdcxx_printer.add('std::__debug::multimap', StdMapPrinter)
999    libstdcxx_printer.add('std::__debug::multiset', StdSetPrinter)
1000    libstdcxx_printer.add('std::__debug::priority_queue',
1001                          StdStackOrQueuePrinter)
1002    libstdcxx_printer.add('std::__debug::queue', StdStackOrQueuePrinter)
1003    libstdcxx_printer.add('std::__debug::set', StdSetPrinter)
1004    libstdcxx_printer.add('std::__debug::stack', StdStackOrQueuePrinter)
1005    libstdcxx_printer.add('std::__debug::unique_ptr', UniquePointerPrinter)
1006    libstdcxx_printer.add('std::__debug::vector', StdVectorPrinter)
1007
1008    # These are the TR1 and C++0x printers.
1009    # For array - the default GDB pretty-printer seems reasonable.
1010    libstdcxx_printer.add_version('std::', 'shared_ptr', SharedPointerPrinter)
1011    libstdcxx_printer.add_version('std::', 'weak_ptr', SharedPointerPrinter)
1012    libstdcxx_printer.add_container('std::', 'unordered_map',
1013                                    Tr1UnorderedMapPrinter)
1014    libstdcxx_printer.add_container('std::', 'unordered_set',
1015                                    Tr1UnorderedSetPrinter)
1016    libstdcxx_printer.add_container('std::', 'unordered_multimap',
1017                                    Tr1UnorderedMapPrinter)
1018    libstdcxx_printer.add_container('std::', 'unordered_multiset',
1019                                    Tr1UnorderedSetPrinter)
1020    libstdcxx_printer.add_container('std::', 'forward_list',
1021                                    StdForwardListPrinter)
1022
1023    libstdcxx_printer.add_version('std::tr1::', 'shared_ptr', SharedPointerPrinter)
1024    libstdcxx_printer.add_version('std::tr1::', 'weak_ptr', SharedPointerPrinter)
1025    libstdcxx_printer.add_version('std::tr1::', 'unordered_map',
1026                                  Tr1UnorderedMapPrinter)
1027    libstdcxx_printer.add_version('std::tr1::', 'unordered_set',
1028                                  Tr1UnorderedSetPrinter)
1029    libstdcxx_printer.add_version('std::tr1::', 'unordered_multimap',
1030                                  Tr1UnorderedMapPrinter)
1031    libstdcxx_printer.add_version('std::tr1::', 'unordered_multiset',
1032                                  Tr1UnorderedSetPrinter)
1033
1034    # These are the C++0x printer registrations for -D_GLIBCXX_DEBUG cases.
1035    # The tr1 namespace printers do not seem to have any debug
1036    # equivalents, so do no register them.
1037    libstdcxx_printer.add('std::__debug::unordered_map',
1038                          Tr1UnorderedMapPrinter)
1039    libstdcxx_printer.add('std::__debug::unordered_set',
1040                          Tr1UnorderedSetPrinter)
1041    libstdcxx_printer.add('std::__debug::unordered_multimap',
1042                          Tr1UnorderedMapPrinter)
1043    libstdcxx_printer.add('std::__debug::unordered_multiset',
1044                          Tr1UnorderedSetPrinter)
1045    libstdcxx_printer.add('std::__debug::forward_list',
1046                          StdForwardListPrinter)
1047
1048
1049    # Extensions.
1050    libstdcxx_printer.add_version('__gnu_cxx::', 'slist', StdSlistPrinter)
1051
1052    if True:
1053        # These shouldn't be necessary, if GDB "print *i" worked.
1054        # But it often doesn't, so here they are.
1055        libstdcxx_printer.add_container('std::', '_List_iterator',
1056                                        StdListIteratorPrinter)
1057        libstdcxx_printer.add_container('std::', '_List_const_iterator',
1058                                        StdListIteratorPrinter)
1059        libstdcxx_printer.add_version('std::', '_Rb_tree_iterator',
1060                                      StdRbtreeIteratorPrinter)
1061        libstdcxx_printer.add_version('std::', '_Rb_tree_const_iterator',
1062                                      StdRbtreeIteratorPrinter)
1063        libstdcxx_printer.add_container('std::', '_Deque_iterator',
1064                                        StdDequeIteratorPrinter)
1065        libstdcxx_printer.add_container('std::', '_Deque_const_iterator',
1066                                        StdDequeIteratorPrinter)
1067        libstdcxx_printer.add_version('__gnu_cxx::', '__normal_iterator',
1068                                      StdVectorIteratorPrinter)
1069        libstdcxx_printer.add_version('__gnu_cxx::', '_Slist_iterator',
1070                                      StdSlistIteratorPrinter)
1071
1072        # Debug (compiled with -D_GLIBCXX_DEBUG) printer
1073        # registrations.  The Rb_tree debug iterator when unwrapped
1074        # from the encapsulating __gnu_debug::_Safe_iterator does not
1075        # have the __norm namespace. Just use the existing printer
1076        # registration for that.
1077        libstdcxx_printer.add('__gnu_debug::_Safe_iterator',
1078                              StdDebugIteratorPrinter)
1079        libstdcxx_printer.add('std::__norm::_List_iterator',
1080                              StdListIteratorPrinter)
1081        libstdcxx_printer.add('std::__norm::_List_const_iterator',
1082                              StdListIteratorPrinter)
1083        libstdcxx_printer.add('std::__norm::_Deque_const_iterator',
1084                              StdDequeIteratorPrinter)
1085        libstdcxx_printer.add('std::__norm::_Deque_iterator',
1086                              StdDequeIteratorPrinter)
1087
1088build_libstdcxx_dictionary ()
1089