]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/l4re-core/libstdc++-v3/contrib/libstdc++-v3-4.9/python/libstdcxx/v6/printers.py
Update
[l4.git] / l4 / pkg / l4re-core / libstdc++-v3 / contrib / libstdc++-v3-4.9 / python / libstdcxx / v6 / printers.py
1 # Pretty-printers for libstdc++.
2
3 # Copyright (C) 2008-2014 Free Software Foundation, Inc.
4
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 import gdb
19 import itertools
20 import re
21 import sys
22
23 ### Python 2 + Python 3 compatibility code
24
25 # Resources about compatibility:
26 #
27 #  * <http://pythonhosted.org/six/>: Documentation of the "six" module
28
29 # FIXME: The handling of e.g. std::basic_string (at least on char)
30 # probably needs updating to work with Python 3's new string rules.
31 #
32 # In particular, Python 3 has a separate type (called byte) for
33 # bytestrings, and a special b"" syntax for the byte literals; the old
34 # str() type has been redefined to always store Unicode text.
35 #
36 # We probably can't do much about this until this GDB PR is addressed:
37 # <https://sourceware.org/bugzilla/show_bug.cgi?id=17138>
38
39 if sys.version_info[0] > 2:
40     ### Python 3 stuff
41     Iterator = object
42     # Python 3 folds these into the normal functions.
43     imap = map
44     izip = zip
45     # Also, int subsumes long
46     long = int
47 else:
48     ### Python 2 stuff
49     class Iterator:
50         """Compatibility mixin for iterators
51
52         Instead of writing next() methods for iterators, write
53         __next__() methods and use this mixin to make them work in
54         Python 2 as well as Python 3.
55
56         Idea stolen from the "six" documentation:
57         <http://pythonhosted.org/six/#six.Iterator>
58         """
59
60         def next(self):
61             return self.__next__()
62
63     # In Python 2, we still need these from itertools
64     from itertools import imap, izip
65
66 # Try to use the new-style pretty-printing if available.
67 _use_gdb_pp = True
68 try:
69     import gdb.printing
70 except ImportError:
71     _use_gdb_pp = False
72
73 # Try to install type-printers.
74 _use_type_printing = False
75 try:
76     import gdb.types
77     if hasattr(gdb.types, 'TypePrinter'):
78         _use_type_printing = True
79 except ImportError:
80     pass
81
82 # Starting with the type ORIG, search for the member type NAME.  This
83 # handles searching upward through superclasses.  This is needed to
84 # work around http://sourceware.org/bugzilla/show_bug.cgi?id=13615.
85 def find_type(orig, name):
86     typ = orig.strip_typedefs()
87     while True:
88         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
101 class 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
120 class 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
131 class 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
167 class 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
179 class 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
213 class 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
224 class 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
300 class 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
309 class 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
369 class 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
388 class 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 def get_value_from_Rb_tree_node(node):
423     """Returns the value held in an _Rb_tree_node<_Val>"""
424     try:
425         member = node.type.fields()[1].name
426         if member == '_M_value_field':
427             # C++03 implementation, node contains the value as a member
428             return node['_M_value_field']
429         elif member == '_M_storage':
430             # C++11 implementation, node stores value in __aligned_buffer
431             p = node['_M_storage']['_M_storage'].address
432             p = p.cast(node.type.template_argument(0).pointer())
433             return p.dereference()
434     except:
435         pass
436     raise ValueError("Unsupported implementation for %s" % str(node.type))
437
438 # This is a pretty printer for std::_Rb_tree_iterator (which is
439 # std::map::iterator), and has nothing to do with the RbtreeIterator
440 # class above.
441 class StdRbtreeIteratorPrinter:
442     "Print std::map::iterator"
443
444     def __init__ (self, typename, val):
445         self.val = val
446
447     def to_string (self):
448         typename = str(self.val.type.strip_typedefs()) + '::_Link_type'
449         nodetype = gdb.lookup_type(typename).strip_typedefs()
450         node = self.val.cast(nodetype).dereference()
451         return get_value_from_Rb_tree_node(node)
452
453 class StdDebugIteratorPrinter:
454     "Print a debug enabled version of an iterator"
455
456     def __init__ (self, typename, val):
457         self.val = val
458
459     # Just strip away the encapsulating __gnu_debug::_Safe_iterator
460     # and return the wrapped iterator value.
461     def to_string (self):
462         itype = self.val.type.template_argument(0)
463         return self.val['_M_current'].cast(itype)
464
465 class StdMapPrinter:
466     "Print a std::map or std::multimap"
467
468     # Turn an RbtreeIterator into a pretty-print iterator.
469     class _iter(Iterator):
470         def __init__(self, rbiter, type):
471             self.rbiter = rbiter
472             self.count = 0
473             self.type = type
474
475         def __iter__(self):
476             return self
477
478         def __next__(self):
479             if self.count % 2 == 0:
480                 n = next(self.rbiter)
481                 n = n.cast(self.type).dereference()
482                 n = get_value_from_Rb_tree_node(n)
483                 self.pair = n
484                 item = n['first']
485             else:
486                 item = self.pair['second']
487             result = ('[%d]' % self.count, item)
488             self.count = self.count + 1
489             return result
490
491     def __init__ (self, typename, val):
492         self.typename = typename
493         self.val = val
494
495     def to_string (self):
496         return '%s with %d elements' % (self.typename,
497                                         len (RbtreeIterator (self.val)))
498
499     def children (self):
500         rep_type = find_type(self.val.type, '_Rep_type')
501         node = find_type(rep_type, '_Link_type')
502         node = node.strip_typedefs()
503         return self._iter (RbtreeIterator (self.val), node)
504
505     def display_hint (self):
506         return 'map'
507
508 class StdSetPrinter:
509     "Print a std::set or std::multiset"
510
511     # Turn an RbtreeIterator into a pretty-print iterator.
512     class _iter(Iterator):
513         def __init__(self, rbiter, type):
514             self.rbiter = rbiter
515             self.count = 0
516             self.type = type
517
518         def __iter__(self):
519             return self
520
521         def __next__(self):
522             item = next(self.rbiter)
523             item = item.cast(self.type).dereference()
524             item = get_value_from_Rb_tree_node(item)
525             # FIXME: this is weird ... what to do?
526             # Maybe a 'set' display hint?
527             result = ('[%d]' % self.count, item)
528             self.count = self.count + 1
529             return result
530
531     def __init__ (self, typename, val):
532         self.typename = typename
533         self.val = val
534
535     def to_string (self):
536         return '%s with %d elements' % (self.typename,
537                                         len (RbtreeIterator (self.val)))
538
539     def children (self):
540         rep_type = find_type(self.val.type, '_Rep_type')
541         node = find_type(rep_type, '_Link_type')
542         node = node.strip_typedefs()
543         return self._iter (RbtreeIterator (self.val), node)
544
545 class StdBitsetPrinter:
546     "Print a std::bitset"
547
548     def __init__(self, typename, val):
549         self.typename = typename
550         self.val = val
551
552     def to_string (self):
553         # If template_argument handled values, we could print the
554         # size.  Or we could use a regexp on the type.
555         return '%s' % (self.typename)
556
557     def children (self):
558         words = self.val['_M_w']
559         wtype = words.type
560
561         # The _M_w member can be either an unsigned long, or an
562         # array.  This depends on the template specialization used.
563         # If it is a single long, convert to a single element list.
564         if wtype.code == gdb.TYPE_CODE_ARRAY:
565             tsize = wtype.target ().sizeof
566         else:
567             words = [words]
568             tsize = wtype.sizeof 
569
570         nwords = wtype.sizeof / tsize
571         result = []
572         byte = 0
573         while byte < nwords:
574             w = words[byte]
575             bit = 0
576             while w != 0:
577                 if (w & 1) != 0:
578                     # Another spot where we could use 'set'?
579                     result.append(('[%d]' % (byte * tsize * 8 + bit), 1))
580                 bit = bit + 1
581                 w = w >> 1
582             byte = byte + 1
583         return result
584
585 class StdDequePrinter:
586     "Print a std::deque"
587
588     class _iter(Iterator):
589         def __init__(self, node, start, end, last, buffer_size):
590             self.node = node
591             self.p = start
592             self.end = end
593             self.last = last
594             self.buffer_size = buffer_size
595             self.count = 0
596
597         def __iter__(self):
598             return self
599
600         def __next__(self):
601             if self.p == self.last:
602                 raise StopIteration
603
604             result = ('[%d]' % self.count, self.p.dereference())
605             self.count = self.count + 1
606
607             # Advance the 'cur' pointer.
608             self.p = self.p + 1
609             if self.p == self.end:
610                 # If we got to the end of this bucket, move to the
611                 # next bucket.
612                 self.node = self.node + 1
613                 self.p = self.node[0]
614                 self.end = self.p + self.buffer_size
615
616             return result
617
618     def __init__(self, typename, val):
619         self.typename = typename
620         self.val = val
621         self.elttype = val.type.template_argument(0)
622         size = self.elttype.sizeof
623         if size < 512:
624             self.buffer_size = int (512 / size)
625         else:
626             self.buffer_size = 1
627
628     def to_string(self):
629         start = self.val['_M_impl']['_M_start']
630         end = self.val['_M_impl']['_M_finish']
631
632         delta_n = end['_M_node'] - start['_M_node'] - 1
633         delta_s = start['_M_last'] - start['_M_cur']
634         delta_e = end['_M_cur'] - end['_M_first']
635
636         size = self.buffer_size * delta_n + delta_s + delta_e
637
638         return '%s with %d elements' % (self.typename, long (size))
639
640     def children(self):
641         start = self.val['_M_impl']['_M_start']
642         end = self.val['_M_impl']['_M_finish']
643         return self._iter(start['_M_node'], start['_M_cur'], start['_M_last'],
644                           end['_M_cur'], self.buffer_size)
645
646     def display_hint (self):
647         return 'array'
648
649 class StdDequeIteratorPrinter:
650     "Print std::deque::iterator"
651
652     def __init__(self, typename, val):
653         self.val = val
654
655     def to_string(self):
656         return self.val['_M_cur'].dereference()
657
658 class StdStringPrinter:
659     "Print a std::basic_string of some kind"
660
661     def __init__(self, typename, val):
662         self.val = val
663
664     def to_string(self):
665         # Make sure &string works, too.
666         type = self.val.type
667         if type.code == gdb.TYPE_CODE_REF:
668             type = type.target ()
669
670         # Calculate the length of the string so that to_string returns
671         # the string according to length, not according to first null
672         # encountered.
673         ptr = self.val ['_M_dataplus']['_M_p']
674         realtype = type.unqualified ().strip_typedefs ()
675         reptype = gdb.lookup_type (str (realtype) + '::_Rep').pointer ()
676         header = ptr.cast(reptype) - 1
677         len = header.dereference ()['_M_length']
678         if hasattr(ptr, "lazy_string"):
679             return ptr.lazy_string (length = len)
680         return ptr.string (length = len)
681
682     def display_hint (self):
683         return 'string'
684
685 class Tr1HashtableIterator(Iterator):
686     def __init__ (self, hash):
687         self.buckets = hash['_M_buckets']
688         self.bucket = 0
689         self.bucket_count = hash['_M_bucket_count']
690         self.node_type = find_type(hash.type, '_Node').pointer()
691         self.node = 0
692         while self.bucket != self.bucket_count:
693             self.node = self.buckets[self.bucket]
694             if self.node:
695                 break
696             self.bucket = self.bucket + 1        
697
698     def __iter__ (self):
699         return self
700
701     def __next__ (self):
702         if self.node == 0:
703             raise StopIteration
704         node = self.node.cast(self.node_type)
705         result = node.dereference()['_M_v']
706         self.node = node.dereference()['_M_next'];
707         if self.node == 0:
708             self.bucket = self.bucket + 1
709             while self.bucket != self.bucket_count:
710                 self.node = self.buckets[self.bucket]
711                 if self.node:
712                     break
713                 self.bucket = self.bucket + 1
714         return result
715
716 class StdHashtableIterator(Iterator):
717     def __init__(self, hash):
718         self.node = hash['_M_before_begin']['_M_nxt']
719         self.node_type = find_type(hash.type, '__node_type').pointer()
720
721     def __iter__(self):
722         return self
723
724     def __next__(self):
725         if self.node == 0:
726             raise StopIteration
727         elt = self.node.cast(self.node_type).dereference()
728         self.node = elt['_M_nxt']
729         valptr = elt['_M_storage'].address
730         valptr = valptr.cast(elt.type.template_argument(0).pointer())
731         return valptr.dereference()
732
733 class Tr1UnorderedSetPrinter:
734     "Print a tr1::unordered_set"
735
736     def __init__ (self, typename, val):
737         self.typename = typename
738         self.val = val
739
740     def hashtable (self):
741         if self.typename.startswith('std::tr1'):
742             return self.val
743         return self.val['_M_h']
744
745     def to_string (self):
746         return '%s with %d elements' % (self.typename, self.hashtable()['_M_element_count'])
747
748     @staticmethod
749     def format_count (i):
750         return '[%d]' % i
751
752     def children (self):
753         counter = imap (self.format_count, itertools.count())
754         if self.typename.startswith('std::tr1'):
755             return izip (counter, Tr1HashtableIterator (self.hashtable()))
756         return izip (counter, StdHashtableIterator (self.hashtable()))
757
758 class Tr1UnorderedMapPrinter:
759     "Print a tr1::unordered_map"
760
761     def __init__ (self, typename, val):
762         self.typename = typename
763         self.val = val
764
765     def hashtable (self):
766         if self.typename.startswith('std::tr1'):
767             return self.val
768         return self.val['_M_h']
769
770     def to_string (self):
771         return '%s with %d elements' % (self.typename, self.hashtable()['_M_element_count'])
772
773     @staticmethod
774     def flatten (list):
775         for elt in list:
776             for i in elt:
777                 yield i
778
779     @staticmethod
780     def format_one (elt):
781         return (elt['first'], elt['second'])
782
783     @staticmethod
784     def format_count (i):
785         return '[%d]' % i
786
787     def children (self):
788         counter = imap (self.format_count, itertools.count())
789         # Map over the hash table and flatten the result.
790         if self.typename.startswith('std::tr1'):
791             data = self.flatten (imap (self.format_one, Tr1HashtableIterator (self.hashtable())))
792             # Zip the two iterators together.
793             return izip (counter, data)
794         data = self.flatten (imap (self.format_one, StdHashtableIterator (self.hashtable())))
795         # Zip the two iterators together.
796         return izip (counter, data)
797         
798
799     def display_hint (self):
800         return 'map'
801
802 class StdForwardListPrinter:
803     "Print a std::forward_list"
804
805     class _iterator(Iterator):
806         def __init__(self, nodetype, head):
807             self.nodetype = nodetype
808             self.base = head['_M_next']
809             self.count = 0
810
811         def __iter__(self):
812             return self
813
814         def __next__(self):
815             if self.base == 0:
816                 raise StopIteration
817             elt = self.base.cast(self.nodetype).dereference()
818             self.base = elt['_M_next']
819             count = self.count
820             self.count = self.count + 1
821             valptr = elt['_M_storage'].address
822             valptr = valptr.cast(elt.type.template_argument(0).pointer())
823             return ('[%d]' % count, valptr.dereference())
824
825     def __init__(self, typename, val):
826         self.val = val
827         self.typename = typename
828
829     def children(self):
830         nodetype = find_type(self.val.type, '_Node')
831         nodetype = nodetype.strip_typedefs().pointer()
832         return self._iterator(nodetype, self.val['_M_impl']['_M_head'])
833
834     def to_string(self):
835         if self.val['_M_impl']['_M_head']['_M_next'] == 0:
836             return 'empty %s' % (self.typename)
837         return '%s' % (self.typename)
838
839
840 # A "regular expression" printer which conforms to the
841 # "SubPrettyPrinter" protocol from gdb.printing.
842 class RxPrinter(object):
843     def __init__(self, name, function):
844         super(RxPrinter, self).__init__()
845         self.name = name
846         self.function = function
847         self.enabled = True
848
849     def invoke(self, value):
850         if not self.enabled:
851             return None
852
853         if value.type.code == gdb.TYPE_CODE_REF:
854             if hasattr(gdb.Value,"referenced_value"):
855                 value = value.referenced_value()
856
857         return self.function(self.name, value)
858
859 # A pretty-printer that conforms to the "PrettyPrinter" protocol from
860 # gdb.printing.  It can also be used directly as an old-style printer.
861 class Printer(object):
862     def __init__(self, name):
863         super(Printer, self).__init__()
864         self.name = name
865         self.subprinters = []
866         self.lookup = {}
867         self.enabled = True
868         self.compiled_rx = re.compile('^([a-zA-Z0-9_:]+)<.*>$')
869
870     def add(self, name, function):
871         # A small sanity check.
872         # FIXME
873         if not self.compiled_rx.match(name + '<>'):
874             raise ValueError('libstdc++ programming error: "%s" does not match' % name)
875         printer = RxPrinter(name, function)
876         self.subprinters.append(printer)
877         self.lookup[name] = printer
878
879     # Add a name using _GLIBCXX_BEGIN_NAMESPACE_VERSION.
880     def add_version(self, base, name, function):
881         self.add(base + name, function)
882         self.add(base + '__7::' + name, function)
883
884     # Add a name using _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
885     def add_container(self, base, name, function):
886         self.add_version(base, name, function)
887         self.add_version(base + '__cxx1998::', name, function)
888
889     @staticmethod
890     def get_basic_type(type):
891         # If it points to a reference, get the reference.
892         if type.code == gdb.TYPE_CODE_REF:
893             type = type.target ()
894
895         # Get the unqualified type, stripped of typedefs.
896         type = type.unqualified ().strip_typedefs ()
897
898         return type.tag
899
900     def __call__(self, val):
901         typename = self.get_basic_type(val.type)
902         if not typename:
903             return None
904
905         # All the types we match are template types, so we can use a
906         # dictionary.
907         match = self.compiled_rx.match(typename)
908         if not match:
909             return None
910
911         basename = match.group(1)
912
913         if val.type.code == gdb.TYPE_CODE_REF:
914             if hasattr(gdb.Value,"referenced_value"):
915                 val = val.referenced_value()
916
917         if basename in self.lookup:
918             return self.lookup[basename].invoke(val)
919
920         # Cannot find a pretty printer.  Return None.
921         return None
922
923 libstdcxx_printer = None
924
925 class FilteringTypePrinter(object):
926     def __init__(self, match, name):
927         self.match = match
928         self.name = name
929         self.enabled = True
930
931     class _recognizer(object):
932         def __init__(self, match, name):
933             self.match = match
934             self.name = name
935             self.type_obj = None
936
937         def recognize(self, type_obj):
938             if type_obj.tag is None:
939                 return None
940
941             if self.type_obj is None:
942                 if not self.match in type_obj.tag:
943                     # Filter didn't match.
944                     return None
945                 try:
946                     self.type_obj = gdb.lookup_type(self.name).strip_typedefs()
947                 except:
948                     pass
949             if self.type_obj == type_obj:
950                 return self.name
951             return None
952
953     def instantiate(self):
954         return self._recognizer(self.match, self.name)
955
956 def add_one_type_printer(obj, match, name):
957     printer = FilteringTypePrinter(match, 'std::' + name)
958     gdb.types.register_type_printer(obj, printer)
959
960 def register_type_printers(obj):
961     global _use_type_printing
962
963     if not _use_type_printing:
964         return
965
966     for pfx in ('', 'w'):
967         add_one_type_printer(obj, 'basic_string', pfx + 'string')
968         add_one_type_printer(obj, 'basic_ios', pfx + 'ios')
969         add_one_type_printer(obj, 'basic_streambuf', pfx + 'streambuf')
970         add_one_type_printer(obj, 'basic_istream', pfx + 'istream')
971         add_one_type_printer(obj, 'basic_ostream', pfx + 'ostream')
972         add_one_type_printer(obj, 'basic_iostream', pfx + 'iostream')
973         add_one_type_printer(obj, 'basic_stringbuf', pfx + 'stringbuf')
974         add_one_type_printer(obj, 'basic_istringstream',
975                                  pfx + 'istringstream')
976         add_one_type_printer(obj, 'basic_ostringstream',
977                                  pfx + 'ostringstream')
978         add_one_type_printer(obj, 'basic_stringstream',
979                                  pfx + 'stringstream')
980         add_one_type_printer(obj, 'basic_filebuf', pfx + 'filebuf')
981         add_one_type_printer(obj, 'basic_ifstream', pfx + 'ifstream')
982         add_one_type_printer(obj, 'basic_ofstream', pfx + 'ofstream')
983         add_one_type_printer(obj, 'basic_fstream', pfx + 'fstream')
984         add_one_type_printer(obj, 'basic_regex', pfx + 'regex')
985         add_one_type_printer(obj, 'sub_match', pfx + 'csub_match')
986         add_one_type_printer(obj, 'sub_match', pfx + 'ssub_match')
987         add_one_type_printer(obj, 'match_results', pfx + 'cmatch')
988         add_one_type_printer(obj, 'match_results', pfx + 'smatch')
989         add_one_type_printer(obj, 'regex_iterator', pfx + 'cregex_iterator')
990         add_one_type_printer(obj, 'regex_iterator', pfx + 'sregex_iterator')
991         add_one_type_printer(obj, 'regex_token_iterator',
992                                  pfx + 'cregex_token_iterator')
993         add_one_type_printer(obj, 'regex_token_iterator',
994                                  pfx + 'sregex_token_iterator')
995
996     # Note that we can't have a printer for std::wstreampos, because
997     # it shares the same underlying type as std::streampos.
998     add_one_type_printer(obj, 'fpos', 'streampos')
999     add_one_type_printer(obj, 'basic_string', 'u16string')
1000     add_one_type_printer(obj, 'basic_string', 'u32string')
1001
1002     for dur in ('nanoseconds', 'microseconds', 'milliseconds',
1003                 'seconds', 'minutes', 'hours'):
1004         add_one_type_printer(obj, 'duration', dur)
1005
1006     add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand0')
1007     add_one_type_printer(obj, 'linear_congruential_engine', 'minstd_rand')
1008     add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937')
1009     add_one_type_printer(obj, 'mersenne_twister_engine', 'mt19937_64')
1010     add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux24_base')
1011     add_one_type_printer(obj, 'subtract_with_carry_engine', 'ranlux48_base')
1012     add_one_type_printer(obj, 'discard_block_engine', 'ranlux24')
1013     add_one_type_printer(obj, 'discard_block_engine', 'ranlux48')
1014     add_one_type_printer(obj, 'shuffle_order_engine', 'knuth_b')
1015
1016 def register_libstdcxx_printers (obj):
1017     "Register libstdc++ pretty-printers with objfile Obj."
1018
1019     global _use_gdb_pp
1020     global libstdcxx_printer
1021
1022     if _use_gdb_pp:
1023         gdb.printing.register_pretty_printer(obj, libstdcxx_printer)
1024     else:
1025         if obj is None:
1026             obj = gdb
1027         obj.pretty_printers.append(libstdcxx_printer)
1028
1029     register_type_printers(obj)
1030
1031 def build_libstdcxx_dictionary ():
1032     global libstdcxx_printer
1033
1034     libstdcxx_printer = Printer("libstdc++-v6")
1035
1036     # For _GLIBCXX_BEGIN_NAMESPACE_VERSION.
1037     vers = '(__7::)?'
1038     # For _GLIBCXX_BEGIN_NAMESPACE_CONTAINER.
1039     container = '(__cxx1998::' + vers + ')?'
1040
1041     # libstdc++ objects requiring pretty-printing.
1042     # In order from:
1043     # http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a01847.html
1044     libstdcxx_printer.add_version('std::', 'basic_string', StdStringPrinter)
1045     libstdcxx_printer.add_container('std::', 'bitset', StdBitsetPrinter)
1046     libstdcxx_printer.add_container('std::', 'deque', StdDequePrinter)
1047     libstdcxx_printer.add_container('std::', 'list', StdListPrinter)
1048     libstdcxx_printer.add_container('std::', 'map', StdMapPrinter)
1049     libstdcxx_printer.add_container('std::', 'multimap', StdMapPrinter)
1050     libstdcxx_printer.add_container('std::', 'multiset', StdSetPrinter)
1051     libstdcxx_printer.add_version('std::', 'priority_queue',
1052                                   StdStackOrQueuePrinter)
1053     libstdcxx_printer.add_version('std::', 'queue', StdStackOrQueuePrinter)
1054     libstdcxx_printer.add_version('std::', 'tuple', StdTuplePrinter)
1055     libstdcxx_printer.add_container('std::', 'set', StdSetPrinter)
1056     libstdcxx_printer.add_version('std::', 'stack', StdStackOrQueuePrinter)
1057     libstdcxx_printer.add_version('std::', 'unique_ptr', UniquePointerPrinter)
1058     libstdcxx_printer.add_container('std::', 'vector', StdVectorPrinter)
1059     # vector<bool>
1060
1061     # Printer registrations for classes compiled with -D_GLIBCXX_DEBUG.
1062     libstdcxx_printer.add('std::__debug::bitset', StdBitsetPrinter)
1063     libstdcxx_printer.add('std::__debug::deque', StdDequePrinter)
1064     libstdcxx_printer.add('std::__debug::list', StdListPrinter)
1065     libstdcxx_printer.add('std::__debug::map', StdMapPrinter)
1066     libstdcxx_printer.add('std::__debug::multimap', StdMapPrinter)
1067     libstdcxx_printer.add('std::__debug::multiset', StdSetPrinter)
1068     libstdcxx_printer.add('std::__debug::priority_queue',
1069                           StdStackOrQueuePrinter)
1070     libstdcxx_printer.add('std::__debug::queue', StdStackOrQueuePrinter)
1071     libstdcxx_printer.add('std::__debug::set', StdSetPrinter)
1072     libstdcxx_printer.add('std::__debug::stack', StdStackOrQueuePrinter)
1073     libstdcxx_printer.add('std::__debug::unique_ptr', UniquePointerPrinter)
1074     libstdcxx_printer.add('std::__debug::vector', StdVectorPrinter)
1075
1076     # These are the TR1 and C++0x printers.
1077     # For array - the default GDB pretty-printer seems reasonable.
1078     libstdcxx_printer.add_version('std::', 'shared_ptr', SharedPointerPrinter)
1079     libstdcxx_printer.add_version('std::', 'weak_ptr', SharedPointerPrinter)
1080     libstdcxx_printer.add_container('std::', 'unordered_map',
1081                                     Tr1UnorderedMapPrinter)
1082     libstdcxx_printer.add_container('std::', 'unordered_set',
1083                                     Tr1UnorderedSetPrinter)
1084     libstdcxx_printer.add_container('std::', 'unordered_multimap',
1085                                     Tr1UnorderedMapPrinter)
1086     libstdcxx_printer.add_container('std::', 'unordered_multiset',
1087                                     Tr1UnorderedSetPrinter)
1088     libstdcxx_printer.add_container('std::', 'forward_list',
1089                                     StdForwardListPrinter)
1090
1091     libstdcxx_printer.add_version('std::tr1::', 'shared_ptr', SharedPointerPrinter)
1092     libstdcxx_printer.add_version('std::tr1::', 'weak_ptr', SharedPointerPrinter)
1093     libstdcxx_printer.add_version('std::tr1::', 'unordered_map',
1094                                   Tr1UnorderedMapPrinter)
1095     libstdcxx_printer.add_version('std::tr1::', 'unordered_set',
1096                                   Tr1UnorderedSetPrinter)
1097     libstdcxx_printer.add_version('std::tr1::', 'unordered_multimap',
1098                                   Tr1UnorderedMapPrinter)
1099     libstdcxx_printer.add_version('std::tr1::', 'unordered_multiset',
1100                                   Tr1UnorderedSetPrinter)
1101
1102     # These are the C++0x printer registrations for -D_GLIBCXX_DEBUG cases.
1103     # The tr1 namespace printers do not seem to have any debug
1104     # equivalents, so do no register them.
1105     libstdcxx_printer.add('std::__debug::unordered_map',
1106                           Tr1UnorderedMapPrinter)
1107     libstdcxx_printer.add('std::__debug::unordered_set',
1108                           Tr1UnorderedSetPrinter)
1109     libstdcxx_printer.add('std::__debug::unordered_multimap',
1110                           Tr1UnorderedMapPrinter)
1111     libstdcxx_printer.add('std::__debug::unordered_multiset',
1112                           Tr1UnorderedSetPrinter)
1113     libstdcxx_printer.add('std::__debug::forward_list',
1114                           StdForwardListPrinter)
1115
1116
1117     # Extensions.
1118     libstdcxx_printer.add_version('__gnu_cxx::', 'slist', StdSlistPrinter)
1119
1120     if True:
1121         # These shouldn't be necessary, if GDB "print *i" worked.
1122         # But it often doesn't, so here they are.
1123         libstdcxx_printer.add_container('std::', '_List_iterator',
1124                                         StdListIteratorPrinter)
1125         libstdcxx_printer.add_container('std::', '_List_const_iterator',
1126                                         StdListIteratorPrinter)
1127         libstdcxx_printer.add_version('std::', '_Rb_tree_iterator',
1128                                       StdRbtreeIteratorPrinter)
1129         libstdcxx_printer.add_version('std::', '_Rb_tree_const_iterator',
1130                                       StdRbtreeIteratorPrinter)
1131         libstdcxx_printer.add_container('std::', '_Deque_iterator',
1132                                         StdDequeIteratorPrinter)
1133         libstdcxx_printer.add_container('std::', '_Deque_const_iterator',
1134                                         StdDequeIteratorPrinter)
1135         libstdcxx_printer.add_version('__gnu_cxx::', '__normal_iterator',
1136                                       StdVectorIteratorPrinter)
1137         libstdcxx_printer.add_version('__gnu_cxx::', '_Slist_iterator',
1138                                       StdSlistIteratorPrinter)
1139
1140         # Debug (compiled with -D_GLIBCXX_DEBUG) printer
1141         # registrations.  The Rb_tree debug iterator when unwrapped
1142         # from the encapsulating __gnu_debug::_Safe_iterator does not
1143         # have the __norm namespace. Just use the existing printer
1144         # registration for that.
1145         libstdcxx_printer.add('__gnu_debug::_Safe_iterator',
1146                               StdDebugIteratorPrinter)
1147         libstdcxx_printer.add('std::__norm::_List_iterator',
1148                               StdListIteratorPrinter)
1149         libstdcxx_printer.add('std::__norm::_List_const_iterator',
1150                               StdListIteratorPrinter)
1151         libstdcxx_printer.add('std::__norm::_Deque_const_iterator',
1152                               StdDequeIteratorPrinter)
1153         libstdcxx_printer.add('std::__norm::_Deque_iterator',
1154                               StdDequeIteratorPrinter)
1155
1156 build_libstdcxx_dictionary ()