]>
Commit | Line | Data |
---|---|---|
7b51bc51 | 1 | # Pretty-printer utilities. |
213516ef | 2 | # Copyright (C) 2010-2023 Free Software Foundation, Inc. |
7b51bc51 DE |
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 | |
9a27f2c6 | 22 | import sys |
7b51bc51 | 23 | |
13123da8 | 24 | |
7b51bc51 DE |
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 | |
690a4937 DE |
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". | |
7b51bc51 | 33 | subprinters: An iterable object with each element having a `name' |
690a4937 DE |
34 | attribute, and, potentially, "enabled" attribute. |
35 | Or this is None if there are no subprinters. | |
7b51bc51 DE |
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 | ||
1fa57852 | 72 | def register_pretty_printer(obj, printer, replace=False): |
7b51bc51 DE |
73 | """Register pretty-printer PRINTER with OBJ. |
74 | ||
75 | The printer is added to the front of the search list, thus one can override | |
690a4937 DE |
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. | |
7b51bc51 DE |
79 | |
80 | Arguments: | |
81 | obj: Either an objfile, progspace, or None (in which case the printer | |
690a4937 | 82 | is registered globally). |
7b51bc51 | 83 | printer: Either a function of one argument (old way) or any object |
690a4937 | 84 | which has attributes: name, enabled, __call__. |
1fa57852 DE |
85 | replace: If True replace any existing copy of the printer. |
86 | Otherwise if the printer already exists raise an exception. | |
7b51bc51 DE |
87 | |
88 | Returns: | |
89 | Nothing. | |
90 | ||
91 | Raises: | |
92 | TypeError: A problem with the type of the printer. | |
4e04c971 | 93 | ValueError: The printer's name contains a semicolon ";". |
6d64e6d4 | 94 | RuntimeError: A printer with the same name is already registered. |
7b51bc51 DE |
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"): | |
13123da8 | 109 | raise TypeError("printer missing attribute: enabled") |
7b51bc51 DE |
110 | if not hasattr(printer, "__call__"): |
111 | raise TypeError("printer missing attribute: __call__") | |
112 | ||
34f5f757 | 113 | if hasattr(printer, "name"): |
13123da8 | 114 | name = printer.name |
34f5f757 | 115 | else: |
13123da8 | 116 | name = printer.__name__ |
34f5f757 | 117 | if obj is None or obj is gdb: |
7b51bc51 DE |
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"): | |
13123da8 SM |
123 | gdb.write( |
124 | "Registering %s pretty-printer for %s ...\n" % (name, obj.filename) | |
125 | ) | |
7b51bc51 | 126 | |
34f5f757 DE |
127 | # Printers implemented as functions are old-style. In order to not risk |
128 | # breaking anything we do not check __name__ here. | |
7b51bc51 | 129 | if hasattr(printer, "name"): |
edae3fd6 | 130 | if not isinstance(printer.name, str): |
7b51bc51 | 131 | raise TypeError("printer name is not a string") |
4e04c971 DE |
132 | # If printer provides a name, make sure it doesn't contain ";". |
133 | # Semicolon is used by the info/enable/disable pretty-printer commands | |
7b51bc51 | 134 | # to delimit subprinters. |
4e04c971 DE |
135 | if printer.name.find(";") >= 0: |
136 | raise ValueError("semicolon ';' in printer name") | |
7b51bc51 DE |
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. | |
1fa57852 DE |
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: | |
13123da8 SM |
148 | raise RuntimeError( |
149 | "pretty-printer already registered: %s" % printer.name | |
150 | ) | |
1fa57852 | 151 | i = i + 1 |
7b51bc51 DE |
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 | |
690a4937 | 187 | object to pretty-print it. |
7b51bc51 DE |
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 | ||
13123da8 | 198 | self.subprinters.append(self.RegexpSubprinter(name, regexp, gen_printer)) |
7b51bc51 DE |
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 | |
1b588015 JB |
205 | if not typename: |
206 | typename = val.type.name | |
7b51bc51 DE |
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 | |
cafec441 | 219 | |
13123da8 | 220 | |
cafec441 TT |
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 = [] | |
edae3fd6 | 230 | v = int(self.val) |
cafec441 TT |
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. | |
13123da8 | 239 | flag_list.append("<unknown: 0x%x>" % v) |
10e3ed90 | 240 | return "0x%x [%s]" % (int(self.val), " | ".join(flag_list)) |
cafec441 | 241 | |
13123da8 | 242 | |
cafec441 TT |
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(): | |
14e75d8e | 262 | self.enumerators.append((field.name, field.enumval)) |
cafec441 TT |
263 | # Sorting the enumerators by value usually does the right |
264 | # thing. | |
13123da8 | 265 | self.enumerators.sort(key=lambda x: x[1]) |
cafec441 TT |
266 | |
267 | if self.enabled: | |
268 | return _EnumInstance(self.enumerators, val) | |
269 | else: | |
270 | return None | |
6979730b DE |
271 | |
272 | ||
273 | # Builtin pretty-printers. | |
274 | # The set is defined as empty, and files in printing/*.py add their printers | |
275 | # to this with add_builtin_pretty_printer. | |
276 | ||
277 | _builtin_pretty_printers = RegexpCollectionPrettyPrinter("builtin") | |
278 | ||
279 | register_pretty_printer(None, _builtin_pretty_printers) | |
280 | ||
281 | # Add a builtin pretty-printer. | |
282 | ||
13123da8 | 283 | |
6979730b DE |
284 | def add_builtin_pretty_printer(name, regexp, printer): |
285 | _builtin_pretty_printers.add_printer(name, regexp, printer) |