GDB (xrefs)

printing.py
Go to the documentation of this file.
1 # Pretty-printer utilities.
2 # Copyright (C) 2010-2018 Free Software Foundation, Inc.
3
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Utilities for working with pretty-printers."""
18
19 import gdb
20 import gdb.types
21 import re
22 import sys
23
24 if sys.version_info[0] > 2:
25 # Python 3 removed basestring and long
26 basestring = str
27 long = int
28
29 class PrettyPrinter(object):
30 """A basic pretty-printer.
31
32 Attributes:
33 name: A unique string among all printers for the context in which
34 it is defined (objfile, progspace, or global(gdb)), and should
35 meaningfully describe what can be pretty-printed.
36 E.g., "StringPiece" or "protobufs".
37 subprinters: An iterable object with each element having a `name'
38 attribute, and, potentially, "enabled" attribute.
39 Or this is None if there are no subprinters.
40 enabled: A boolean indicating if the printer is enabled.
41
42 Subprinters are for situations where "one" pretty-printer is actually a
43 collection of several printers. E.g., The libstdc++ pretty-printer has
44 a pretty-printer for each of several different types, based on regexps.
45 """
46
47 # While one might want to push subprinters into the subclass, it's
48 # present here to formalize such support to simplify
49 # commands/pretty_printers.py.
50
51 def __init__(self, name, subprinters=None):
52 self.name = name
53 self.subprinters = subprinters
54 self.enabled = True
55
56 def __call__(self, val):
57 # The subclass must define this.
58 raise NotImplementedError("PrettyPrinter __call__")
59
60
61 class SubPrettyPrinter(object):
62 """Baseclass for sub-pretty-printers.
63
64 Sub-pretty-printers needn't use this, but it formalizes what's needed.
65
66 Attributes:
67 name: The name of the subprinter.
68 enabled: A boolean indicating if the subprinter is enabled.
69 """
70
71 def __init__(self, name):
72 self.name = name
73 self.enabled = True
74
75
76 def register_pretty_printer(obj, printer, replace=False):
77 """Register pretty-printer PRINTER with OBJ.
78
79 The printer is added to the front of the search list, thus one can override
80 an existing printer if one needs to. Use a different name when overriding
81 an existing printer, otherwise an exception will be raised; multiple
82 printers with the same name are disallowed.
83
84 Arguments:
85 obj: Either an objfile, progspace, or None (in which case the printer
86 is registered globally).
87 printer: Either a function of one argument (old way) or any object
88 which has attributes: name, enabled, __call__.
89 replace: If True replace any existing copy of the printer.
90 Otherwise if the printer already exists raise an exception.
91
92 Returns:
93 Nothing.
94
95 Raises:
96 TypeError: A problem with the type of the printer.
97 ValueError: The printer's name contains a semicolon ";".
98 RuntimeError: A printer with the same name is already registered.
99
100 If the caller wants the printer to be listable and disableable, it must
101 follow the PrettyPrinter API. This applies to the old way (functions) too.
102 If printer is an object, __call__ is a method of two arguments:
103 self, and the value to be pretty-printed. See PrettyPrinter.
104 """
105
106 # Watch for both __name__ and name.
107 # Functions get the former for free, but we don't want to use an
108 # attribute named __foo__ for pretty-printers-as-objects.
109 # If printer has both, we use `name'.
110 if not hasattr(printer, "__name__") and not hasattr(printer, "name"):
111 raise TypeError("printer missing attribute: name")
112 if hasattr(printer, "name") and not hasattr(printer, "enabled"):
113 raise TypeError("printer missing attribute: enabled")
114 if not hasattr(printer, "__call__"):
115 raise TypeError("printer missing attribute: __call__")
116
117 if hasattr(printer, "name"):
118 name = printer.name
119 else:
120 name = printer.__name__
121 if obj is None or obj is gdb:
122 if gdb.parameter("verbose"):
123 gdb.write("Registering global %s pretty-printer ...\n" % name)
124 obj = gdb
125 else:
126 if gdb.parameter("verbose"):
127 gdb.write("Registering %s pretty-printer for %s ...\n" % (
128 name, obj.filename))
129
130 # Printers implemented as functions are old-style. In order to not risk
131 # breaking anything we do not check __name__ here.
132 if hasattr(printer, "name"):
133 if not isinstance(printer.name, basestring):
134 raise TypeError("printer name is not a string")
135 # If printer provides a name, make sure it doesn't contain ";".
136 # Semicolon is used by the info/enable/disable pretty-printer commands
137 # to delimit subprinters.
138 if printer.name.find(";") >= 0:
139 raise ValueError("semicolon ';' in printer name")
140 # Also make sure the name is unique.
141 # Alas, we can't do the same for functions and __name__, they could
142 # all have a canonical name like "lookup_function".
143 # PERF: gdb records printers in a list, making this inefficient.
144 i = 0
145 for p in obj.pretty_printers:
146 if hasattr(p, "name") and p.name == printer.name:
147 if replace:
148 del obj.pretty_printers[i]
149 break
150 else:
151 raise RuntimeError("pretty-printer already registered: %s" %
152 printer.name)
153 i = i + 1
154
155 obj.pretty_printers.insert(0, printer)
156
157
158 class RegexpCollectionPrettyPrinter(PrettyPrinter):
159 """Class for implementing a collection of regular-expression based pretty-printers.
160
161 Intended usage:
162
163 pretty_printer = RegexpCollectionPrettyPrinter("my_library")
164 pretty_printer.add_printer("myclass1", "^myclass1$", MyClass1Printer)
165 ...
166 pretty_printer.add_printer("myclassN", "^myclassN$", MyClassNPrinter)
167 register_pretty_printer(obj, pretty_printer)
168 """
169
170 class RegexpSubprinter(SubPrettyPrinter):
171 def __init__(self, name, regexp, gen_printer):
172 super(RegexpCollectionPrettyPrinter.RegexpSubprinter, self).__init__(name)
173 self.regexp = regexp
174 self.gen_printer = gen_printer
175 self.compiled_re = re.compile(regexp)
176
177 def __init__(self, name):
178 super(RegexpCollectionPrettyPrinter, self).__init__(name, [])
179
180 def add_printer(self, name, regexp, gen_printer):
181 """Add a printer to the list.
182
183 The printer is added to the end of the list.
184
185 Arguments:
186 name: The name of the subprinter.
187 regexp: The regular expression, as a string.
188 gen_printer: A function/method that given a value returns an
189 object to pretty-print it.
190
191 Returns:
192 Nothing.
193 """
194
195 # NOTE: A previous version made the name of each printer the regexp.
196 # That makes it awkward to pass to the enable/disable commands (it's
197 # cumbersome to make a regexp of a regexp). So now the name is a
198 # separate parameter.
199
200 self.subprinters.append(self.RegexpSubprinter(name, regexp,
201 gen_printer))
202
203 def __call__(self, val):
204 """Lookup the pretty-printer for the provided value."""
205
206 # Get the type name.
207 typename = gdb.types.get_basic_type(val.type).tag
208 if not typename:
209 typename = val.type.name
210 if not typename:
211 return None
212
213 # Iterate over table of type regexps to determine
214 # if a printer is registered for that type.
215 # Return an instantiation of the printer if found.
216 for printer in self.subprinters:
217 if printer.enabled and printer.compiled_re.search(typename):
218 return printer.gen_printer(val)
219
220 # Cannot find a pretty printer. Return None.
221 return None
222
223 # A helper class for printing enum types. This class is instantiated
224 # with a list of enumerators to print a particular Value.
225 class _EnumInstance:
226 def __init__(self, enumerators, val):
227 self.enumerators = enumerators
228 self.val = val
229
230 def to_string(self):
231 flag_list = []
232 v = long(self.val)
233 any_found = False
234 for (e_name, e_value) in self.enumerators:
235 if v & e_value != 0:
236 flag_list.append(e_name)
237 v = v & ~e_value
238 any_found = True
239 if not any_found or v != 0:
240 # Leftover value.
241 flag_list.append('<unknown: 0x%x>' % v)
242 return "0x%x [%s]" % (int(self.val), " | ".join(flag_list))
243
244 class FlagEnumerationPrinter(PrettyPrinter):
245 """A pretty-printer which can be used to print a flag-style enumeration.
246 A flag-style enumeration is one where the enumerators are or'd
247 together to create values. The new printer will print these
248 symbolically using '|' notation. The printer must be registered
249 manually. This printer is most useful when an enum is flag-like,
250 but has some overlap. GDB's built-in printing will not handle
251 this case, but this printer will attempt to."""
252
253 def __init__(self, enum_type):
254 super(FlagEnumerationPrinter, self).__init__(enum_type)
255 self.initialized = False
256
257 def __call__(self, val):
258 if not self.initialized:
259 self.initialized = True
260 flags = gdb.lookup_type(self.name)
261 self.enumerators = []
262 for field in flags.fields():
263 self.enumerators.append((field.name, field.enumval))
264 # Sorting the enumerators by value usually does the right
265 # thing.
266 self.enumerators.sort(key = lambda x: x[1])
267
268 if self.enabled:
269 return _EnumInstance(self.enumerators, val)
270 else:
271 return None
272
273
274 # Builtin pretty-printers.
275 # The set is defined as empty, and files in printing/*.py add their printers
276 # to this with add_builtin_pretty_printer.
277
278 _builtin_pretty_printers = RegexpCollectionPrettyPrinter("builtin")
279
280 register_pretty_printer(None, _builtin_pretty_printers)
281
282 # Add a builtin pretty-printer.
283
284 def add_builtin_pretty_printer(name, regexp, printer):
285 _builtin_pretty_printers.add_printer(name, regexp, printer)
gdb.types.get_basic_type
def get_basic_type(type_)
Definition: types.py:22
gdb.printing.RegexpCollectionPrettyPrinter.RegexpSubprinter.regexp
regexp
Definition: printing.py:173
gdb.printing._EnumInstance.enumerators
enumerators
Definition: printing.py:227
gdb.printing.SubPrettyPrinter.enabled
enabled
Definition: printing.py:73
gdb.printing.RegexpCollectionPrettyPrinter.RegexpSubprinter.__init__
def __init__(self, name, regexp, gen_printer)
Definition: printing.py:171
gdb.printing.FlagEnumerationPrinter
Definition: printing.py:244
gdb.printing.FlagEnumerationPrinter.__init__
def __init__(self, enum_type)
Definition: printing.py:253
gdb.printing.FlagEnumerationPrinter.initialized
initialized
Definition: printing.py:255
gdb.printing.long
long
Definition: printing.py:27
gdb.printing.PrettyPrinter.enabled
enabled
Definition: printing.py:54
gdb.printing.PrettyPrinter.subprinters
subprinters
Definition: printing.py:53
gdb.printing.PrettyPrinter.__init__
def __init__(self, name, subprinters=None)
Definition: printing.py:51
gdb.printing.PrettyPrinter
Definition: printing.py:29
gdb.printing.RegexpCollectionPrettyPrinter.RegexpSubprinter.compiled_re
compiled_re
Definition: printing.py:175
gdb.printing.RegexpCollectionPrettyPrinter.add_printer
def add_printer(self, name, regexp, gen_printer)
Definition: printing.py:180
gdb.printing.add_builtin_pretty_printer
def add_builtin_pretty_printer(name, regexp, printer)
Definition: printing.py:284
gdb.printing.RegexpCollectionPrettyPrinter.RegexpSubprinter
Definition: printing.py:170
gdb.printing.FlagEnumerationPrinter.enumerators
enumerators
Definition: printing.py:261
gdb.printing.FlagEnumerationPrinter.__call__
def __call__(self, val)
Definition: printing.py:257
gdb.printing.PrettyPrinter.__call__
def __call__(self, val)
Definition: printing.py:56
gdb.printing._EnumInstance.val
val
Definition: printing.py:228
gdb.printing.RegexpCollectionPrettyPrinter.__init__
def __init__(self, name)
Definition: printing.py:177
gdb.printing._EnumInstance.to_string
def to_string(self)
Definition: printing.py:230
gdb.printing.RegexpCollectionPrettyPrinter
Definition: printing.py:158
gdb.printing.PrettyPrinter.name
name
Definition: printing.py:52
gdb.printing.RegexpCollectionPrettyPrinter.__call__
def __call__(self, val)
Definition: printing.py:203
gdb.printing.SubPrettyPrinter.__init__
def __init__(self, name)
Definition: printing.py:71
gdb.printing.SubPrettyPrinter.name
name
Definition: printing.py:72
gdb.types
Definition: types.py:1
gdb.printing.SubPrettyPrinter
Definition: printing.py:61
gdb.printing._EnumInstance.__init__
def __init__(self, enumerators, val)
Definition: printing.py:226
gdb.printing._EnumInstance
Definition: printing.py:225
gdb.printing.register_pretty_printer
def register_pretty_printer(obj, printer, replace=False)
Definition: printing.py:76
gdb.printing.RegexpCollectionPrettyPrinter.RegexpSubprinter.gen_printer
gen_printer
Definition: printing.py:174