GDB (xrefs)
Loading...
Searching...
No Matches
printing.py
Go to the documentation of this file.
1# Pretty-printer utilities.
2# Copyright (C) 2010-2023 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
19import gdb
20import gdb.types
21import itertools
22import re
23
24
25class PrettyPrinter(object):
26 """A basic pretty-printer.
27
28 Attributes:
29 name: A unique string among all printers for the context in which
30 it is defined (objfile, progspace, or global(gdb)), and should
31 meaningfully describe what can be pretty-printed.
32 E.g., "StringPiece" or "protobufs".
33 subprinters: An iterable object with each element having a `name'
34 attribute, and, potentially, "enabled" attribute.
35 Or this is None if there are no subprinters.
36 enabled: A boolean indicating if the printer is enabled.
37
38 Subprinters are for situations where "one" pretty-printer is actually a
39 collection of several printers. E.g., The libstdc++ pretty-printer has
40 a pretty-printer for each of several different types, based on regexps.
41 """
42
43 # While one might want to push subprinters into the subclass, it's
44 # present here to formalize such support to simplify
45 # commands/pretty_printers.py.
46
47 def __init__(self, name, subprinters=None):
48 self.name = name
49 self.subprinters = subprinters
50 self.enabled = True
51
52 def __call__(self, val):
53 # The subclass must define this.
54 raise NotImplementedError("PrettyPrinter __call__")
55
56
57class SubPrettyPrinter(object):
58 """Baseclass for sub-pretty-printers.
59
60 Sub-pretty-printers needn't use this, but it formalizes what's needed.
61
62 Attributes:
63 name: The name of the subprinter.
64 enabled: A boolean indicating if the subprinter is enabled.
65 """
66
67 def __init__(self, name):
68 self.name = name
69 self.enabled = True
70
71
72def register_pretty_printer(obj, printer, replace=False):
73 """Register pretty-printer PRINTER with OBJ.
74
75 The printer is added to the front of the search list, thus one can override
76 an existing printer if one needs to. Use a different name when overriding
77 an existing printer, otherwise an exception will be raised; multiple
78 printers with the same name are disallowed.
79
80 Arguments:
81 obj: Either an objfile, progspace, or None (in which case the printer
82 is registered globally).
83 printer: Either a function of one argument (old way) or any object
84 which has attributes: name, enabled, __call__.
85 replace: If True replace any existing copy of the printer.
86 Otherwise if the printer already exists raise an exception.
87
88 Returns:
89 Nothing.
90
91 Raises:
92 TypeError: A problem with the type of the printer.
93 ValueError: The printer's name contains a semicolon ";".
94 RuntimeError: A printer with the same name is already registered.
95
96 If the caller wants the printer to be listable and disableable, it must
97 follow the PrettyPrinter API. This applies to the old way (functions) too.
98 If printer is an object, __call__ is a method of two arguments:
99 self, and the value to be pretty-printed. See PrettyPrinter.
100 """
101
102 # Watch for both __name__ and name.
103 # Functions get the former for free, but we don't want to use an
104 # attribute named __foo__ for pretty-printers-as-objects.
105 # If printer has both, we use `name'.
106 if not hasattr(printer, "__name__") and not hasattr(printer, "name"):
107 raise TypeError("printer missing attribute: name")
108 if hasattr(printer, "name") and not hasattr(printer, "enabled"):
109 raise TypeError("printer missing attribute: enabled")
110 if not hasattr(printer, "__call__"):
111 raise TypeError("printer missing attribute: __call__")
112
113 if hasattr(printer, "name"):
114 name = printer.name
115 else:
116 name = printer.__name__
117 if obj is None or obj is gdb:
118 if gdb.parameter("verbose"):
119 gdb.write("Registering global %s pretty-printer ...\n" % name)
120 obj = gdb
121 else:
122 if gdb.parameter("verbose"):
123 gdb.write(
124 "Registering %s pretty-printer for %s ...\n" % (name, obj.filename)
125 )
126
127 # Printers implemented as functions are old-style. In order to not risk
128 # breaking anything we do not check __name__ here.
129 if hasattr(printer, "name"):
130 if not isinstance(printer.name, str):
131 raise TypeError("printer name is not a string")
132 # If printer provides a name, make sure it doesn't contain ";".
133 # Semicolon is used by the info/enable/disable pretty-printer commands
134 # to delimit subprinters.
135 if printer.name.find(";") >= 0:
136 raise ValueError("semicolon ';' in printer name")
137 # Also make sure the name is unique.
138 # Alas, we can't do the same for functions and __name__, they could
139 # all have a canonical name like "lookup_function".
140 # PERF: gdb records printers in a list, making this inefficient.
141 i = 0
142 for p in obj.pretty_printers:
143 if hasattr(p, "name") and p.name == printer.name:
144 if replace:
145 del obj.pretty_printers[i]
146 break
147 else:
148 raise RuntimeError(
149 "pretty-printer already registered: %s" % printer.name
150 )
151 i = i + 1
152
153 obj.pretty_printers.insert(0, printer)
154
155
157 """Class for implementing a collection of regular-expression based pretty-printers.
158
159 Intended usage:
160
161 pretty_printer = RegexpCollectionPrettyPrinter("my_library")
162 pretty_printer.add_printer("myclass1", "^myclass1$", MyClass1Printer)
163 ...
164 pretty_printer.add_printer("myclassN", "^myclassN$", MyClassNPrinter)
165 register_pretty_printer(obj, pretty_printer)
166 """
167
168 class RegexpSubprinter(SubPrettyPrinter):
169 def __init__(self, name, regexp, gen_printer):
171 self.regexp = regexp
172 self.gen_printer = gen_printer
173 self.compiled_re = re.compile(regexp)
174
175 def __init__(self, name):
176 super(RegexpCollectionPrettyPrinter, self).__init__(name, [])
177
178 def add_printer(self, name, regexp, gen_printer):
179 """Add a printer to the list.
180
181 The printer is added to the end of the list.
182
183 Arguments:
184 name: The name of the subprinter.
185 regexp: The regular expression, as a string.
186 gen_printer: A function/method that given a value returns an
187 object to pretty-print it.
188
189 Returns:
190 Nothing.
191 """
192
193 # NOTE: A previous version made the name of each printer the regexp.
194 # That makes it awkward to pass to the enable/disable commands (it's
195 # cumbersome to make a regexp of a regexp). So now the name is a
196 # separate parameter.
197
198 self.subprinters.append(self.RegexpSubprinter(name, regexp, gen_printer))
199
200 def __call__(self, val):
201 """Lookup the pretty-printer for the provided value."""
202
203 # Get the type name.
204 typename = gdb.types.get_basic_type(val.type).tag
205 if not typename:
206 typename = val.type.name
207 if not typename:
208 return None
209
210 # Iterate over table of type regexps to determine
211 # if a printer is registered for that type.
212 # Return an instantiation of the printer if found.
213 for printer in self.subprinters:
214 if printer.enabled and printer.compiled_re.search(typename):
215 return printer.gen_printer(val)
216
217 # Cannot find a pretty printer. Return None.
218 return None
219
220
221# A helper class for printing enum types. This class is instantiated
222# with a list of enumerators to print a particular Value.
223class _EnumInstance(gdb.ValuePrinter):
224 def __init__(self, enumerators, val):
225 self.__enumerators = enumerators
226 self.__val = val
227
228 def to_string(self):
229 flag_list = []
230 v = int(self.__val)
231 any_found = False
232 for e_name, e_value in self.__enumerators:
233 if v & e_value != 0:
234 flag_list.append(e_name)
235 v = v & ~e_value
236 any_found = True
237 if not any_found or v != 0:
238 # Leftover value.
239 flag_list.append("<unknown: 0x%x>" % v)
240 return "0x%x [%s]" % (int(self.__val), " | ".join(flag_list))
241
242
244 """A pretty-printer which can be used to print a flag-style enumeration.
245 A flag-style enumeration is one where the enumerators are or'd
246 together to create values. The new printer will print these
247 symbolically using '|' notation. The printer must be registered
248 manually. This printer is most useful when an enum is flag-like,
249 but has some overlap. GDB's built-in printing will not handle
250 this case, but this printer will attempt to."""
251
252 def __init__(self, enum_type):
253 super(FlagEnumerationPrinter, self).__init__(enum_type)
254 self.initialized = False
255
256 def __call__(self, val):
257 if not self.initialized:
258 self.initialized = True
259 flags = gdb.lookup_type(self.name)
260 self.enumerators = []
261 for field in flags.fields():
262 self.enumerators.append((field.name, field.enumval))
263 # Sorting the enumerators by value usually does the right
264 # thing.
265 self.enumerators.sort(key=lambda x: x[1])
266
267 if self.enabled:
268 return _EnumInstance(self.enumerators, val)
269 else:
270 return None
271
272
273class NoOpScalarPrinter(gdb.ValuePrinter):
274 """A no-op pretty printer that wraps a scalar value."""
275
276 def __init__(self, value):
277 self.__value = value
278
279 def to_string(self):
280 return self.__value.format_string(raw=True)
281
282
283class NoOpPointerReferencePrinter(gdb.ValuePrinter):
284 """A no-op pretty printer that wraps a pointer or reference."""
285
286 def __init__(self, value):
287 self.__value = value
288
289 def to_string(self):
290 return self.__value.format_string(deref_refs=False)
291
292 def num_children(self):
293 return 1
294
295 def child(self, i):
296 return "value", self.__value.referenced_value()
297
298 def children(self):
299 yield "value", self.__value.referenced_value()
300
301
302class NoOpArrayPrinter(gdb.ValuePrinter):
303 """A no-op pretty printer that wraps an array value."""
304
305 def __init__(self, ty, value):
306 self.__value = value
307 (low, high) = ty.range()
308 # In Ada, an array can have an index type that is a
309 # non-contiguous enum. In this case the indexing must be done
310 # by using the indices into the enum type, not the underlying
311 # integer values.
312 range_type = ty.fields()[0].type
313 if range_type.target().code == gdb.TYPE_CODE_ENUM:
314 e_values = range_type.target().fields()
315 # Drop any values before LOW.
316 e_values = itertools.dropwhile(lambda x: x.enumval < low, e_values)
317 # Drop any values after HIGH.
318 e_values = itertools.takewhile(lambda x: x.enumval <= high, e_values)
319 low = 0
320 high = len(list(e_values)) - 1
321 self.__low = low
322 self.__high = high
323
324 def to_string(self):
325 return ""
326
327 def display_hint(self):
328 return "array"
329
330 def num_children(self):
331 return self.__high - self.__low + 1
332
333 def child(self, i):
334 return (self.__low + i, self.__value[self.__low + i])
335
336 def children(self):
337 for i in range(self.__low, self.__high + 1):
338 yield (i, self.__value[i])
339
340
341class NoOpStructPrinter(gdb.ValuePrinter):
342 """A no-op pretty printer that wraps a struct or union value."""
343
344 def __init__(self, ty, value):
345 self.__ty = ty
346 self.__value = value
347
348 def to_string(self):
349 return ""
350
351 def children(self):
352 for field in self.__ty.fields():
353 if hasattr(field, "bitpos") and field.name is not None:
354 yield (field.name, self.__value[field])
355
356
357def make_visualizer(value):
358 """Given a gdb.Value, wrap it in a pretty-printer.
359
360 If a pretty-printer is found by the usual means, it is returned.
361 Otherwise, VALUE will be wrapped in a no-op visualizer."""
362
363 result = gdb.default_visualizer(value)
364 if result is not None:
365 # Found a pretty-printer.
366 pass
367 else:
368 ty = value.type.strip_typedefs()
369 if ty.is_string_like:
370 result = NoOpScalarPrinter(value)
371 elif ty.code == gdb.TYPE_CODE_ARRAY:
372 result = NoOpArrayPrinter(ty, value)
373 elif ty.is_array_like:
374 value = value.to_array()
375 ty = value.type.strip_typedefs()
376 result = NoOpArrayPrinter(ty, value)
377 elif ty.code in (gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION):
378 result = NoOpStructPrinter(ty, value)
379 elif ty.code in (
380 gdb.TYPE_CODE_PTR,
381 gdb.TYPE_CODE_REF,
382 gdb.TYPE_CODE_RVALUE_REF,
383 ):
384 result = NoOpPointerReferencePrinter(value)
385 else:
386 result = NoOpScalarPrinter(value)
387 return result
388
389
390# Builtin pretty-printers.
391# The set is defined as empty, and files in printing/*.py add their printers
392# to this with add_builtin_pretty_printer.
393
394_builtin_pretty_printers = RegexpCollectionPrettyPrinter("builtin")
395
396register_pretty_printer(None, _builtin_pretty_printers)
397
398# Add a builtin pretty-printer.
399
400
401def add_builtin_pretty_printer(name, regexp, printer):
402 _builtin_pretty_printers.add_printer(name, regexp, printer)
__init__(self, ty, value)
Definition printing.py:305
__init__(self, ty, value)
Definition printing.py:344
__init__(self, name, subprinters=None)
Definition printing.py:47
add_printer(self, name, regexp, gen_printer)
Definition printing.py:178
__init__(self, enumerators, val)
Definition printing.py:224
register_pretty_printer(obj, printer, replace=False)
Definition printing.py:72
make_visualizer(value)
Definition printing.py:357
add_builtin_pretty_printer(name, regexp, printer)
Definition printing.py:401
get_basic_type(type_)
Definition types.py:22
display_hint
Definition value.h:90