Handle pointers and references correctly in DAP
[binutils-gdb.git] / gdb / python / lib / gdb / printing.py
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
19 import gdb
20 import gdb.types
21 import itertools
22 import re
23
24
25 class 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
57 class 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
72 def 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
156 class RegexpCollectionPrettyPrinter(PrettyPrinter):
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):
170 super(RegexpCollectionPrettyPrinter.RegexpSubprinter, self).__init__(name)
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.
223 class _EnumInstance:
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
243 class FlagEnumerationPrinter(PrettyPrinter):
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
273 class NoOpScalarPrinter:
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
283 class NoOpPointerReferencePrinter:
284 """A no-op pretty printer that wraps a pointer or reference."""
285
286 def __init__(self, value):
287 self.value = value
288 self.num_children = 1
289
290 def to_string(self):
291 return self.value.format_string(deref_refs=False)
292
293 def children(self):
294 yield "value", self.value.referenced_value()
295
296
297 class NoOpArrayPrinter:
298 """A no-op pretty printer that wraps an array value."""
299
300 def __init__(self, ty, value):
301 self.value = value
302 (low, high) = ty.range()
303 # In Ada, an array can have an index type that is a
304 # non-contiguous enum. In this case the indexing must be done
305 # by using the indices into the enum type, not the underlying
306 # integer values.
307 range_type = ty.fields()[0].type
308 if range_type.target().code == gdb.TYPE_CODE_ENUM:
309 e_values = range_type.target().fields()
310 # Drop any values before LOW.
311 e_values = itertools.dropwhile(lambda x: x.enumval < low, e_values)
312 # Drop any values after HIGH.
313 e_values = itertools.takewhile(lambda x: x.enumval <= high, e_values)
314 low = 0
315 high = len(list(e_values)) - 1
316 # This is a convenience to the DAP code and perhaps other
317 # users.
318 self.num_children = high - low + 1
319 self.low = low
320 self.high = high
321
322 def to_string(self):
323 return ""
324
325 def display_hint(self):
326 return "array"
327
328 def children(self):
329 for i in range(self.low, self.high + 1):
330 yield (i, self.value[i])
331
332
333 class NoOpStructPrinter:
334 """A no-op pretty printer that wraps a struct or union value."""
335
336 def __init__(self, ty, value):
337 self.ty = ty
338 self.value = value
339
340 def to_string(self):
341 return ""
342
343 def children(self):
344 for field in self.ty.fields():
345 if field.name is not None:
346 yield (field.name, self.value[field])
347
348
349 def make_visualizer(value):
350 """Given a gdb.Value, wrap it in a pretty-printer.
351
352 If a pretty-printer is found by the usual means, it is returned.
353 Otherwise, VALUE will be wrapped in a no-op visualizer."""
354
355 result = gdb.default_visualizer(value)
356 if result is not None:
357 # Found a pretty-printer.
358 pass
359 else:
360 ty = value.type.strip_typedefs()
361 if ty.is_string_like:
362 result = gdb.printing.NoOpScalarPrinter(value)
363 elif ty.code == gdb.TYPE_CODE_ARRAY:
364 result = gdb.printing.NoOpArrayPrinter(ty, value)
365 elif ty.is_array_like:
366 value = value.to_array()
367 ty = value.type.strip_typedefs()
368 result = gdb.printing.NoOpArrayPrinter(ty, value)
369 elif ty.code in (gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION):
370 result = gdb.printing.NoOpStructPrinter(ty, value)
371 elif ty.code in (gdb.TYPE_CODE_PTR, gdb.TYPE_CODE_REF, gdb.TYPE_CODE_RVALUE_REF):
372 result = NoOpPointerReferencePrinter(value)
373 else:
374 result = gdb.printing.NoOpScalarPrinter(value)
375 return result
376
377
378 # Builtin pretty-printers.
379 # The set is defined as empty, and files in printing/*.py add their printers
380 # to this with add_builtin_pretty_printer.
381
382 _builtin_pretty_printers = RegexpCollectionPrettyPrinter("builtin")
383
384 register_pretty_printer(None, _builtin_pretty_printers)
385
386 # Add a builtin pretty-printer.
387
388
389 def add_builtin_pretty_printer(name, regexp, printer):
390 _builtin_pretty_printers.add_printer(name, regexp, printer)