1 # Pretty-printer utilities.
2 # Copyright (C) 2010-2025 Free Software Foundation, Inc.
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.
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.
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/>.
17 """Utilities for working with pretty-printers."""
26 class PrettyPrinter(object):
27 """A basic pretty-printer.
30 name: A unique string among all printers for the context in which
31 it is defined (objfile, progspace, or global(gdb)), and should
32 meaningfully describe what can be pretty-printed.
33 E.g., "StringPiece" or "protobufs".
34 subprinters: An iterable object with each element having a `name'
35 attribute, and, potentially, "enabled" attribute.
36 Or this is None if there are no subprinters.
37 enabled: A boolean indicating if the printer is enabled.
39 Subprinters are for situations where "one" pretty-printer is actually a
40 collection of several printers. E.g., The libstdc++ pretty-printer has
41 a pretty-printer for each of several different types, based on regexps.
44 # While one might want to push subprinters into the subclass, it's
45 # present here to formalize such support to simplify
46 # commands/pretty_printers.py.
48 def __init__(self
, name
, subprinters
=None):
50 self
.subprinters
= subprinters
53 def __call__(self
, val
):
54 # The subclass must define this.
55 raise NotImplementedError("PrettyPrinter __call__")
58 class SubPrettyPrinter(object):
59 """Baseclass for sub-pretty-printers.
61 Sub-pretty-printers needn't use this, but it formalizes what's needed.
64 name: The name of the subprinter.
65 enabled: A boolean indicating if the subprinter is enabled.
68 def __init__(self
, name
):
73 def register_pretty_printer(obj
, printer
, replace
=False):
74 """Register pretty-printer PRINTER with OBJ.
76 The printer is added to the front of the search list, thus one can override
77 an existing printer if one needs to. Use a different name when overriding
78 an existing printer, otherwise an exception will be raised; multiple
79 printers with the same name are disallowed.
82 obj: Either an objfile, progspace, or None (in which case the printer
83 is registered globally).
84 printer: Either a function of one argument (old way) or any object
85 which has attributes: name, enabled, __call__.
86 replace: If True replace any existing copy of the printer.
87 Otherwise if the printer already exists raise an exception.
93 TypeError: A problem with the type of the printer.
94 ValueError: The printer's name contains a semicolon ";".
95 RuntimeError: A printer with the same name is already registered.
97 If the caller wants the printer to be listable and disableable, it must
98 follow the PrettyPrinter API. This applies to the old way (functions) too.
99 If printer is an object, __call__ is a method of two arguments:
100 self, and the value to be pretty-printed. See PrettyPrinter.
103 # Watch for both __name__ and name.
104 # Functions get the former for free, but we don't want to use an
105 # attribute named __foo__ for pretty-printers-as-objects.
106 # If printer has both, we use `name'.
107 if not hasattr(printer
, "__name__") and not hasattr(printer
, "name"):
108 raise TypeError("printer missing attribute: name")
109 if hasattr(printer
, "name") and not hasattr(printer
, "enabled"):
110 raise TypeError("printer missing attribute: enabled")
111 if not hasattr(printer
, "__call__"):
112 raise TypeError("printer missing attribute: __call__")
114 if hasattr(printer
, "name"):
117 name
= printer
.__name
__
118 if obj
is None or obj
is gdb
:
119 if gdb
.parameter("verbose"):
120 gdb
.write("Registering global %s pretty-printer ...\n" % name
)
123 if gdb
.parameter("verbose"):
125 "Registering %s pretty-printer for %s ...\n" % (name
, obj
.filename
)
128 # Printers implemented as functions are old-style. In order to not risk
129 # breaking anything we do not check __name__ here.
130 if hasattr(printer
, "name"):
131 if not isinstance(printer
.name
, str):
132 raise TypeError("printer name is not a string")
133 # If printer provides a name, make sure it doesn't contain ";".
134 # Semicolon is used by the info/enable/disable pretty-printer commands
135 # to delimit subprinters.
136 if printer
.name
.find(";") >= 0:
137 raise ValueError("semicolon ';' in printer name")
138 # Also make sure the name is unique.
139 # Alas, we can't do the same for functions and __name__, they could
140 # all have a canonical name like "lookup_function".
141 # PERF: gdb records printers in a list, making this inefficient.
143 for p
in obj
.pretty_printers
:
144 if hasattr(p
, "name") and p
.name
== printer
.name
:
146 del obj
.pretty_printers
[i
]
150 "pretty-printer already registered: %s" % printer
.name
154 obj
.pretty_printers
.insert(0, printer
)
157 class RegexpCollectionPrettyPrinter(PrettyPrinter
):
158 """Class for implementing a collection of regular-expression based pretty-printers.
162 pretty_printer = RegexpCollectionPrettyPrinter("my_library")
163 pretty_printer.add_printer("myclass1", "^myclass1$", MyClass1Printer)
165 pretty_printer.add_printer("myclassN", "^myclassN$", MyClassNPrinter)
166 register_pretty_printer(obj, pretty_printer)
169 class RegexpSubprinter(SubPrettyPrinter
):
170 def __init__(self
, name
, regexp
, gen_printer
):
171 super(RegexpCollectionPrettyPrinter
.RegexpSubprinter
, self
).__init
__(name
)
173 self
.gen_printer
= gen_printer
174 self
.compiled_re
= re
.compile(regexp
)
176 def __init__(self
, name
):
177 super(RegexpCollectionPrettyPrinter
, self
).__init
__(name
, [])
179 def add_printer(self
, name
, regexp
, gen_printer
):
180 """Add a printer to the list.
182 The printer is added to the end of the list.
185 name: The name of the subprinter.
186 regexp: The regular expression, as a string.
187 gen_printer: A function/method that given a value returns an
188 object to pretty-print it.
194 # NOTE: A previous version made the name of each printer the regexp.
195 # That makes it awkward to pass to the enable/disable commands (it's
196 # cumbersome to make a regexp of a regexp). So now the name is a
197 # separate parameter.
199 self
.subprinters
.append(self
.RegexpSubprinter(name
, regexp
, gen_printer
))
201 def __call__(self
, val
):
202 """Lookup the pretty-printer for the provided value."""
205 typename
= gdb
.types
.get_basic_type(val
.type).tag
207 typename
= val
.type.name
211 # Iterate over table of type regexps to determine
212 # if a printer is registered for that type.
213 # Return an instantiation of the printer if found.
214 for printer
in self
.subprinters
:
215 if printer
.enabled
and printer
.compiled_re
.search(typename
):
216 return printer
.gen_printer(val
)
218 # Cannot find a pretty printer. Return None.
222 # A helper class for printing enum types. This class is instantiated
223 # with a list of enumerators to print a particular Value.
224 class _EnumInstance(gdb
.ValuePrinter
):
225 def __init__(self
, enumerators
, val
):
226 self
.__enumerators
= enumerators
233 for e_name
, e_value
in self
.__enumerators
:
235 flag_list
.append(e_name
)
238 if not any_found
or v
!= 0:
240 flag_list
.append("<unknown: 0x%x>" % v
)
241 return "0x%x [%s]" % (int(self
.__val
), " | ".join(flag_list
))
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."""
253 def __init__(self
, enum_type
):
254 super(FlagEnumerationPrinter
, self
).__init
__(enum_type
)
255 self
.initialized
= False
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
266 self
.enumerators
.sort(key
=lambda x
: x
[1])
269 return _EnumInstance(self
.enumerators
, val
)
274 class NoOpScalarPrinter(gdb
.ValuePrinter
):
275 """A no-op pretty printer that wraps a scalar value."""
277 def __init__(self
, value
):
281 return self
.__value
.format_string(raw
=True)
284 class NoOpStringPrinter(gdb
.ValuePrinter
):
285 """A no-op pretty printer that wraps a string value."""
287 def __init__(self
, ty
, value
):
292 # We need some special cases here.
294 # * If the gdb.Value was created from a Python string, it will
295 # be a non-lazy array -- but will have address 0 and so the
296 # contents will be lost on conversion to lazy string.
297 # (Weirdly, the .address attribute will not be 0 though.)
298 # Since conversion to lazy string is to avoid fetching too
299 # much data, and since the array is already non-lazy, just
302 # * To avoid weird printing for a C "string" that is just a
303 # NULL pointer, special case this as well.
305 # * Lazy strings only understand arrays and pointers; other
306 # string-like objects (like a Rust &str) should simply be
308 code
= self
.__ty
.code
309 if code
== gdb
.TYPE_CODE_ARRAY
and not self
.__value
.is_lazy
:
311 elif code
== gdb
.TYPE_CODE_PTR
and self
.__value
== 0:
313 elif code
!= gdb
.TYPE_CODE_PTR
and code
!= gdb
.TYPE_CODE_ARRAY
:
316 return self
.__value
.lazy_string()
318 def display_hint(self
):
322 class NoOpPointerReferencePrinter(gdb
.ValuePrinter
):
323 """A no-op pretty printer that wraps a pointer or reference."""
325 def __init__(self
, value
):
329 return self
.__value
.format_string(deref_refs
=False)
331 def num_children(self
):
335 return "value", self
.__value
.referenced_value()
338 yield "value", self
.__value
.referenced_value()
341 class NoOpArrayPrinter(gdb
.ValuePrinter
):
342 """A no-op pretty printer that wraps an array value."""
344 def __init__(self
, ty
, value
):
346 (low
, high
) = ty
.range()
347 # In Ada, an array can have an index type that is a
348 # non-contiguous enum. In this case the indexing must be done
349 # by using the indices into the enum type, not the underlying
351 range_type
= ty
.fields()[0].type
352 if range_type
.target().code
== gdb
.TYPE_CODE_ENUM
:
353 e_values
= range_type
.target().fields()
354 # Drop any values before LOW.
355 e_values
= itertools
.dropwhile(lambda x
: x
.enumval
< low
, e_values
)
356 # Drop any values after HIGH.
357 e_values
= itertools
.takewhile(lambda x
: x
.enumval
<= high
, e_values
)
359 high
= len(list(e_values
)) - 1
366 def display_hint(self
):
369 def num_children(self
):
370 return self
.__high
- self
.__low
+ 1
373 return (self
.__low
+ i
, self
.__value
[self
.__low
+ i
])
376 for i
in range(self
.__low
, self
.__high
+ 1):
377 yield (i
, self
.__value
[i
])
380 class NoOpStructPrinter(gdb
.ValuePrinter
):
381 """A no-op pretty printer that wraps a struct or union value."""
383 def __init__(self
, ty
, value
):
391 for field
in self
.__ty
.fields():
392 if hasattr(field
, "bitpos") and field
.name
is not None:
393 yield (field
.name
, self
.__value
[field
])
396 def make_visualizer(value
):
397 """Given a gdb.Value, wrap it in a pretty-printer.
399 If a pretty-printer is found by the usual means, it is returned.
400 Otherwise, VALUE will be wrapped in a no-op visualizer."""
402 result
= gdb
.default_visualizer(value
)
403 if result
is not None:
404 # Found a pretty-printer.
407 ty
= value
.type.strip_typedefs()
408 if ty
.is_string_like
:
409 result
= NoOpStringPrinter(ty
, value
)
410 elif ty
.code
== gdb
.TYPE_CODE_ARRAY
:
411 result
= NoOpArrayPrinter(ty
, value
)
412 elif ty
.is_array_like
:
413 value
= value
.to_array()
414 ty
= value
.type.strip_typedefs()
415 result
= NoOpArrayPrinter(ty
, value
)
416 elif ty
.code
in (gdb
.TYPE_CODE_STRUCT
, gdb
.TYPE_CODE_UNION
):
417 result
= NoOpStructPrinter(ty
, value
)
421 gdb
.TYPE_CODE_RVALUE_REF
,
423 result
= NoOpPointerReferencePrinter(value
)
425 result
= NoOpScalarPrinter(value
)
429 # Builtin pretty-printers.
430 # The set is defined as empty, and files in printing/*.py add their printers
431 # to this with add_builtin_pretty_printer.
433 _builtin_pretty_printers
= RegexpCollectionPrettyPrinter("builtin")
435 register_pretty_printer(None, _builtin_pretty_printers
)
437 # Add a builtin pretty-printer.
440 def add_builtin_pretty_printer(name
, regexp
, printer
):
441 _builtin_pretty_printers
.add_printer(name
, regexp
, printer
)