1 /* Python pretty-printing
3 Copyright (C) 2008-2019 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
25 #include "extension-priv.h"
27 #include "python-internal.h"
29 /* Return type of print_string_repr. */
31 enum string_repr_result
33 /* The string method returned None. */
35 /* The string method had an error. */
41 /* Helper function for find_pretty_printer which iterates over a list,
42 calls each function and inspects output. This will return a
43 printer object if one recognizes VALUE. If no printer is found, it
44 will return None. On error, it will set the Python error and
48 search_pp_list (PyObject
*list
, PyObject
*value
)
50 Py_ssize_t pp_list_size
, list_index
;
52 pp_list_size
= PyList_Size (list
);
53 for (list_index
= 0; list_index
< pp_list_size
; list_index
++)
55 PyObject
*function
= PyList_GetItem (list
, list_index
);
59 /* Skip if disabled. */
60 if (PyObject_HasAttr (function
, gdbpy_enabled_cst
))
62 gdbpy_ref
<> attr (PyObject_GetAttr (function
, gdbpy_enabled_cst
));
67 cmp
= PyObject_IsTrue (attr
.get ());
75 gdbpy_ref
<> printer (PyObject_CallFunctionObjArgs (function
, value
,
79 else if (printer
!= Py_None
)
83 return gdbpy_ref
<>::new_reference (Py_None
);
86 /* Subroutine of find_pretty_printer to simplify it.
87 Look for a pretty-printer to print VALUE in all objfiles.
88 The result is NULL if there's an error and the search should be terminated.
89 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
90 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
93 find_pretty_printer_from_objfiles (PyObject
*value
)
95 for (objfile
*obj
: current_program_space
->objfiles ())
97 gdbpy_ref
<> objf
= objfile_to_objfile_object (obj
);
100 /* Ignore the error and continue. */
105 gdbpy_ref
<> pp_list (objfpy_get_printers (objf
.get (), NULL
));
106 gdbpy_ref
<> function (search_pp_list (pp_list
.get (), value
));
108 /* If there is an error in any objfile list, abort the search and exit. */
109 if (function
== NULL
)
112 if (function
!= Py_None
)
113 return function
.release ();
119 /* Subroutine of find_pretty_printer to simplify it.
120 Look for a pretty-printer to print VALUE in the current program space.
121 The result is NULL if there's an error and the search should be terminated.
122 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
123 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
126 find_pretty_printer_from_progspace (PyObject
*value
)
128 gdbpy_ref
<> obj
= pspace_to_pspace_object (current_program_space
);
132 gdbpy_ref
<> pp_list (pspy_get_printers (obj
.get (), NULL
));
133 return search_pp_list (pp_list
.get (), value
);
136 /* Subroutine of find_pretty_printer to simplify it.
137 Look for a pretty-printer to print VALUE in the gdb module.
138 The result is NULL if there's an error and the search should be terminated.
139 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
140 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
143 find_pretty_printer_from_gdb (PyObject
*value
)
145 /* Fetch the global pretty printer list. */
146 if (gdb_python_module
== NULL
147 || ! PyObject_HasAttrString (gdb_python_module
, "pretty_printers"))
148 return gdbpy_ref
<>::new_reference (Py_None
);
149 gdbpy_ref
<> pp_list (PyObject_GetAttrString (gdb_python_module
,
151 if (pp_list
== NULL
|| ! PyList_Check (pp_list
.get ()))
152 return gdbpy_ref
<>::new_reference (Py_None
);
154 return search_pp_list (pp_list
.get (), value
);
157 /* Find the pretty-printing constructor function for VALUE. If no
158 pretty-printer exists, return None. If one exists, return a new
159 reference. On error, set the Python error and return NULL. */
162 find_pretty_printer (PyObject
*value
)
164 /* Look at the pretty-printer list for each objfile
165 in the current program-space. */
166 gdbpy_ref
<> function (find_pretty_printer_from_objfiles (value
));
167 if (function
== NULL
|| function
!= Py_None
)
170 /* Look at the pretty-printer list for the current program-space. */
171 function
= find_pretty_printer_from_progspace (value
);
172 if (function
== NULL
|| function
!= Py_None
)
175 /* Look at the pretty-printer list in the gdb module. */
176 return find_pretty_printer_from_gdb (value
);
179 /* Pretty-print a single value, via the printer object PRINTER.
180 If the function returns a string, a PyObject containing the string
181 is returned. If the function returns Py_NONE that means the pretty
182 printer returned the Python None as a value. Otherwise, if the
183 function returns a value, *OUT_VALUE is set to the value, and NULL
184 is returned. On error, *OUT_VALUE is set to NULL, NULL is
185 returned, with a python exception set. */
188 pretty_print_one_value (PyObject
*printer
, struct value
**out_value
)
195 if (!PyObject_HasAttr (printer
, gdbpy_to_string_cst
))
196 result
= gdbpy_ref
<>::new_reference (Py_None
);
199 result
.reset (PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
,
203 if (! gdbpy_is_string (result
.get ())
204 && ! gdbpy_is_lazy_string (result
.get ())
205 && result
!= Py_None
)
207 *out_value
= convert_value_from_python (result
.get ());
208 if (PyErr_Occurred ())
215 catch (const gdb_exception
&except
)
222 /* Return the display hint for the object printer, PRINTER. Return
223 NULL if there is no display_hint method, or if the method did not
224 return a string. On error, print stack trace and return NULL. On
225 success, return an xmalloc()d string. */
226 gdb::unique_xmalloc_ptr
<char>
227 gdbpy_get_display_hint (PyObject
*printer
)
229 gdb::unique_xmalloc_ptr
<char> result
;
231 if (! PyObject_HasAttr (printer
, gdbpy_display_hint_cst
))
234 gdbpy_ref
<> hint (PyObject_CallMethodObjArgs (printer
, gdbpy_display_hint_cst
,
238 if (gdbpy_is_string (hint
.get ()))
240 result
= python_string_to_host_string (hint
.get ());
242 gdbpy_print_stack ();
246 gdbpy_print_stack ();
251 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
254 print_stack_unless_memory_error (struct ui_file
*stream
)
256 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error
))
258 gdbpy_err_fetch fetched_error
;
259 gdb::unique_xmalloc_ptr
<char> msg
= fetched_error
.to_string ();
261 if (msg
== NULL
|| *msg
== '\0')
262 fprintf_filtered (stream
, _("<error reading variable>"));
264 fprintf_filtered (stream
, _("<error reading variable: %s>"),
268 gdbpy_print_stack ();
271 /* Helper for gdbpy_apply_val_pretty_printer which calls to_string and
272 formats the result. */
274 static enum string_repr_result
275 print_string_repr (PyObject
*printer
, const char *hint
,
276 struct ui_file
*stream
, int recurse
,
277 const struct value_print_options
*options
,
278 const struct language_defn
*language
,
279 struct gdbarch
*gdbarch
)
281 struct value
*replacement
= NULL
;
282 enum string_repr_result result
= string_repr_ok
;
284 gdbpy_ref
<> py_str
= pretty_print_one_value (printer
, &replacement
);
287 if (py_str
== Py_None
)
288 result
= string_repr_none
;
289 else if (gdbpy_is_lazy_string (py_str
.get ()))
294 gdb::unique_xmalloc_ptr
<char> encoding
;
295 struct value_print_options local_opts
= *options
;
297 gdbpy_extract_lazy_string (py_str
.get (), &addr
, &type
,
300 local_opts
.addressprint
= 0;
301 val_print_string (type
, encoding
.get (), addr
, (int) length
,
302 stream
, &local_opts
);
307 = python_string_to_target_python_string (py_str
.get ());
314 output
= PyBytes_AS_STRING (string
.get ());
315 length
= PyBytes_GET_SIZE (string
.get ());
316 type
= builtin_type (gdbarch
)->builtin_char
;
318 if (hint
&& !strcmp (hint
, "string"))
319 LA_PRINT_STRING (stream
, type
, (gdb_byte
*) output
,
320 length
, NULL
, 0, options
);
322 fputs_filtered (output
, stream
);
326 result
= string_repr_error
;
327 print_stack_unless_memory_error (stream
);
331 else if (replacement
)
333 struct value_print_options opts
= *options
;
335 opts
.addressprint
= 0;
336 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
340 result
= string_repr_error
;
341 print_stack_unless_memory_error (stream
);
347 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the
348 printer, if any exist. If is_py_none is true, then nothing has
349 been printed by to_string, and format output accordingly. */
351 print_children (PyObject
*printer
, const char *hint
,
352 struct ui_file
*stream
, int recurse
,
353 const struct value_print_options
*options
,
354 const struct language_defn
*language
,
357 int is_map
, is_array
, done_flag
, pretty
;
360 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
363 /* If we are printing a map or an array, we want some special
365 is_map
= hint
&& ! strcmp (hint
, "map");
366 is_array
= hint
&& ! strcmp (hint
, "array");
368 gdbpy_ref
<> children (PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
370 if (children
== NULL
)
372 print_stack_unless_memory_error (stream
);
376 gdbpy_ref
<> iter (PyObject_GetIter (children
.get ()));
379 print_stack_unless_memory_error (stream
);
383 /* Use the prettyformat_arrays option if we are printing an array,
384 and the pretty option otherwise. */
386 pretty
= options
->prettyformat_arrays
;
389 if (options
->prettyformat
== Val_prettyformat
)
392 pretty
= options
->prettyformat_structs
;
396 for (i
= 0; i
< options
->print_max
; ++i
)
401 gdbpy_ref
<> item (PyIter_Next (iter
.get ()));
404 if (PyErr_Occurred ())
405 print_stack_unless_memory_error (stream
);
406 /* Set a flag so we can know whether we printed all the
407 available elements. */
413 if (! PyTuple_Check (item
.get ()) || PyTuple_Size (item
.get ()) != 2)
415 PyErr_SetString (PyExc_TypeError
,
416 _("Result of children iterator not a tuple"
417 " of two elements."));
418 gdbpy_print_stack ();
421 if (! PyArg_ParseTuple (item
.get (), "sO", &name
, &py_v
))
423 /* The user won't necessarily get a stack trace here, so provide
425 if (gdbpy_print_python_errors_p ())
426 fprintf_unfiltered (gdb_stderr
,
427 _("Bad result from children iterator.\n"));
428 gdbpy_print_stack ();
432 /* Print initial "{". For other elements, there are three
434 1. Maps. Print a "," after each value element.
435 2. Arrays. Always print a ",".
436 3. Other. Always print a ",". */
440 fputs_filtered ("{", stream
);
442 fputs_filtered (" = {", stream
);
445 else if (! is_map
|| i
% 2 == 0)
446 fputs_filtered (pretty
? "," : ", ", stream
);
448 /* In summary mode, we just want to print "= {...}" if there is
450 if (options
->summary
)
452 /* This increment tricks the post-loop logic to print what
460 if (! is_map
|| i
% 2 == 0)
464 fputs_filtered ("\n", stream
);
465 print_spaces_filtered (2 + 2 * recurse
, stream
);
468 wrap_here (n_spaces (2 + 2 *recurse
));
471 if (is_map
&& i
% 2 == 0)
472 fputs_filtered ("[", stream
);
475 /* We print the index, not whatever the child method
476 returned as the name. */
477 if (options
->print_array_indexes
)
478 fprintf_filtered (stream
, "[%d] = ", i
);
482 fputs_filtered (name
, stream
);
483 fputs_filtered (" = ", stream
);
486 if (gdbpy_is_lazy_string (py_v
))
491 gdb::unique_xmalloc_ptr
<char> encoding
;
492 struct value_print_options local_opts
= *options
;
494 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
496 local_opts
.addressprint
= 0;
497 val_print_string (type
, encoding
.get (), addr
, (int) length
, stream
,
500 else if (gdbpy_is_string (py_v
))
502 gdb::unique_xmalloc_ptr
<char> output
;
504 output
= python_string_to_host_string (py_v
);
506 gdbpy_print_stack ();
508 fputs_filtered (output
.get (), stream
);
512 struct value
*value
= convert_value_from_python (py_v
);
516 gdbpy_print_stack ();
517 error (_("Error while executing Python code."));
521 /* When printing the key of a map we allow one additional
522 level of depth. This means the key will print before the
524 struct value_print_options opt
= *options
;
525 if (is_map
&& i
% 2 == 0
526 && opt
.max_depth
!= -1
527 && opt
.max_depth
< INT_MAX
)
529 common_val_print (value
, stream
, recurse
+ 1, &opt
, language
);
533 if (is_map
&& i
% 2 == 0)
534 fputs_filtered ("] = ", stream
);
543 fputs_filtered ("\n", stream
);
544 print_spaces_filtered (2 + 2 * recurse
, stream
);
546 fputs_filtered ("...", stream
);
550 fputs_filtered ("\n", stream
);
551 print_spaces_filtered (2 * recurse
, stream
);
553 fputs_filtered ("}", stream
);
558 gdbpy_apply_val_pretty_printer (const struct extension_language_defn
*extlang
,
560 LONGEST embedded_offset
, CORE_ADDR address
,
561 struct ui_file
*stream
, int recurse
,
563 const struct value_print_options
*options
,
564 const struct language_defn
*language
)
566 struct gdbarch
*gdbarch
= get_type_arch (type
);
568 enum string_repr_result print_result
;
570 if (value_lazy (val
))
571 value_fetch_lazy (val
);
573 /* No pretty-printer support for unavailable values. */
574 if (!value_bytes_available (val
, embedded_offset
, TYPE_LENGTH (type
)))
575 return EXT_LANG_RC_NOP
;
577 if (!gdb_python_initialized
)
578 return EXT_LANG_RC_NOP
;
580 gdbpy_enter
enter_py (gdbarch
, language
);
582 /* Instantiate the printer. */
583 value
= value_from_component (val
, type
, embedded_offset
);
585 gdbpy_ref
<> val_obj (value_to_value_object (value
));
588 print_stack_unless_memory_error (stream
);
589 return EXT_LANG_RC_ERROR
;
592 /* Find the constructor. */
593 gdbpy_ref
<> printer (find_pretty_printer (val_obj
.get ()));
596 print_stack_unless_memory_error (stream
);
597 return EXT_LANG_RC_ERROR
;
600 if (printer
== Py_None
)
601 return EXT_LANG_RC_NOP
;
603 if (val_print_check_max_depth (stream
, recurse
, options
, language
))
604 return EXT_LANG_RC_OK
;
606 /* If we are printing a map, we want some special formatting. */
607 gdb::unique_xmalloc_ptr
<char> hint (gdbpy_get_display_hint (printer
.get ()));
609 /* Print the section */
610 print_result
= print_string_repr (printer
.get (), hint
.get (), stream
,
611 recurse
, options
, language
, gdbarch
);
612 if (print_result
!= string_repr_error
)
613 print_children (printer
.get (), hint
.get (), stream
, recurse
, options
,
614 language
, print_result
== string_repr_none
);
616 if (PyErr_Occurred ())
617 print_stack_unless_memory_error (stream
);
618 return EXT_LANG_RC_OK
;
622 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
623 print object. It must have a 'to_string' method (but this is
624 checked by varobj, not here) which takes no arguments and
625 returns a string. The printer will return a value and in the case
626 of a Python string being returned, this function will return a
627 PyObject containing the string. For any other type, *REPLACEMENT is
628 set to the replacement value and this function returns NULL. On
629 error, *REPLACEMENT is set to NULL and this function also returns
632 apply_varobj_pretty_printer (PyObject
*printer_obj
,
633 struct value
**replacement
,
634 struct ui_file
*stream
)
637 gdbpy_ref
<> py_str
= pretty_print_one_value (printer_obj
, replacement
);
639 if (*replacement
== NULL
&& py_str
== NULL
)
640 print_stack_unless_memory_error (stream
);
645 /* Find a pretty-printer object for the varobj module. Returns a new
646 reference to the object if successful; returns NULL if not. VALUE
647 is the value for which a printer tests to determine if it
648 can pretty-print the value. */
650 gdbpy_get_varobj_pretty_printer (struct value
*value
)
654 value
= value_copy (value
);
656 catch (const gdb_exception
&except
)
658 GDB_PY_HANDLE_EXCEPTION (except
);
661 gdbpy_ref
<> val_obj (value_to_value_object (value
));
665 return find_pretty_printer (val_obj
.get ());
668 /* A Python function which wraps find_pretty_printer and instantiates
669 the resulting class. This accepts a Value argument and returns a
670 pretty printer instance, or None. This function is useful as an
671 argument to the MI command -var-set-visualizer. */
673 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
678 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
680 value
= value_object_to_value (val_obj
);
683 PyErr_SetString (PyExc_TypeError
,
684 _("Argument must be a gdb.Value."));
688 return find_pretty_printer (val_obj
).release ();