1 /* Python pretty-printing
3 Copyright (C) 2008-2023 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"
28 #include "cli/cli-style.h"
30 /* Return type of print_string_repr. */
32 enum gdbpy_string_repr_result
34 /* The string method returned None. */
36 /* The string method had an error. */
42 /* If non-null, points to options that are in effect while
44 const struct value_print_options
*gdbpy_current_print_options
;
46 /* Helper function for find_pretty_printer which iterates over a list,
47 calls each function and inspects output. This will return a
48 printer object if one recognizes VALUE. If no printer is found, it
49 will return None. On error, it will set the Python error and
53 search_pp_list (PyObject
*list
, PyObject
*value
)
55 Py_ssize_t pp_list_size
, list_index
;
57 pp_list_size
= PyList_Size (list
);
58 for (list_index
= 0; list_index
< pp_list_size
; list_index
++)
60 PyObject
*function
= PyList_GetItem (list
, list_index
);
64 /* Skip if disabled. */
65 if (PyObject_HasAttr (function
, gdbpy_enabled_cst
))
67 gdbpy_ref
<> attr (PyObject_GetAttr (function
, gdbpy_enabled_cst
));
72 cmp
= PyObject_IsTrue (attr
.get ());
80 gdbpy_ref
<> printer (PyObject_CallFunctionObjArgs (function
, value
,
84 else if (printer
!= Py_None
)
88 return gdbpy_ref
<>::new_reference (Py_None
);
91 /* Subroutine of find_pretty_printer to simplify it.
92 Look for a pretty-printer to print VALUE in all objfiles.
93 The result is NULL if there's an error and the search should be terminated.
94 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
95 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
98 find_pretty_printer_from_objfiles (PyObject
*value
)
100 for (objfile
*obj
: current_program_space
->objfiles ())
102 gdbpy_ref
<> objf
= objfile_to_objfile_object (obj
);
105 /* Ignore the error and continue. */
110 gdbpy_ref
<> pp_list (objfpy_get_printers (objf
.get (), NULL
));
111 gdbpy_ref
<> function (search_pp_list (pp_list
.get (), value
));
113 /* If there is an error in any objfile list, abort the search and exit. */
114 if (function
== NULL
)
117 if (function
!= Py_None
)
118 return function
.release ();
124 /* Subroutine of find_pretty_printer to simplify it.
125 Look for a pretty-printer to print VALUE in the current program space.
126 The result is NULL if there's an error and the search should be terminated.
127 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
128 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
131 find_pretty_printer_from_progspace (PyObject
*value
)
133 gdbpy_ref
<> obj
= pspace_to_pspace_object (current_program_space
);
137 gdbpy_ref
<> pp_list (pspy_get_printers (obj
.get (), NULL
));
138 return search_pp_list (pp_list
.get (), value
);
141 /* Subroutine of find_pretty_printer to simplify it.
142 Look for a pretty-printer to print VALUE in the gdb module.
143 The result is NULL if there's an error and the search should be terminated.
144 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
145 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
148 find_pretty_printer_from_gdb (PyObject
*value
)
150 /* Fetch the global pretty printer list. */
151 if (gdb_python_module
== NULL
152 || ! PyObject_HasAttrString (gdb_python_module
, "pretty_printers"))
153 return gdbpy_ref
<>::new_reference (Py_None
);
154 gdbpy_ref
<> pp_list (PyObject_GetAttrString (gdb_python_module
,
156 if (pp_list
== NULL
|| ! PyList_Check (pp_list
.get ()))
157 return gdbpy_ref
<>::new_reference (Py_None
);
159 return search_pp_list (pp_list
.get (), value
);
162 /* Find the pretty-printing constructor function for VALUE. If no
163 pretty-printer exists, return None. If one exists, return a new
164 reference. On error, set the Python error and return NULL. */
167 find_pretty_printer (PyObject
*value
)
169 /* Look at the pretty-printer list for each objfile
170 in the current program-space. */
171 gdbpy_ref
<> function (find_pretty_printer_from_objfiles (value
));
172 if (function
== NULL
|| function
!= Py_None
)
175 /* Look at the pretty-printer list for the current program-space. */
176 function
= find_pretty_printer_from_progspace (value
);
177 if (function
== NULL
|| function
!= Py_None
)
180 /* Look at the pretty-printer list in the gdb module. */
181 return find_pretty_printer_from_gdb (value
);
184 /* Pretty-print a single value, via the printer object PRINTER.
185 If the function returns a string, a PyObject containing the string
186 is returned. If the function returns Py_NONE that means the pretty
187 printer returned the Python None as a value. Otherwise, if the
188 function returns a value, *OUT_VALUE is set to the value, and NULL
189 is returned. On error, *OUT_VALUE is set to NULL, NULL is
190 returned, with a python exception set. */
193 pretty_print_one_value (PyObject
*printer
, struct value
**out_value
)
200 if (!PyObject_HasAttr (printer
, gdbpy_to_string_cst
))
201 result
= gdbpy_ref
<>::new_reference (Py_None
);
204 result
.reset (PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
,
208 if (! gdbpy_is_string (result
.get ())
209 && ! gdbpy_is_lazy_string (result
.get ())
210 && result
!= Py_None
)
212 *out_value
= convert_value_from_python (result
.get ());
213 if (PyErr_Occurred ())
220 catch (const gdb_exception
&except
)
227 /* Return the display hint for the object printer, PRINTER. Return
228 NULL if there is no display_hint method, or if the method did not
229 return a string. On error, print stack trace and return NULL. On
230 success, return an xmalloc()d string. */
231 gdb::unique_xmalloc_ptr
<char>
232 gdbpy_get_display_hint (PyObject
*printer
)
234 gdb::unique_xmalloc_ptr
<char> result
;
236 if (! PyObject_HasAttr (printer
, gdbpy_display_hint_cst
))
239 gdbpy_ref
<> hint (PyObject_CallMethodObjArgs (printer
, gdbpy_display_hint_cst
,
243 if (gdbpy_is_string (hint
.get ()))
245 result
= python_string_to_host_string (hint
.get ());
247 gdbpy_print_stack ();
251 gdbpy_print_stack ();
256 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
259 print_stack_unless_memory_error (struct ui_file
*stream
)
261 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error
))
263 gdbpy_err_fetch fetched_error
;
264 gdb::unique_xmalloc_ptr
<char> msg
= fetched_error
.to_string ();
266 if (msg
== NULL
|| *msg
== '\0')
267 fprintf_styled (stream
, metadata_style
.style (),
268 _("<error reading variable>"));
270 fprintf_styled (stream
, metadata_style
.style (),
271 _("<error reading variable: %s>"), msg
.get ());
274 gdbpy_print_stack ();
277 /* Helper for gdbpy_apply_val_pretty_printer which calls to_string and
278 formats the result. */
280 static enum gdbpy_string_repr_result
281 print_string_repr (PyObject
*printer
, const char *hint
,
282 struct ui_file
*stream
, int recurse
,
283 const struct value_print_options
*options
,
284 const struct language_defn
*language
,
285 struct gdbarch
*gdbarch
)
287 struct value
*replacement
= NULL
;
288 enum gdbpy_string_repr_result result
= string_repr_ok
;
290 gdbpy_ref
<> py_str
= pretty_print_one_value (printer
, &replacement
);
293 if (py_str
== Py_None
)
294 result
= string_repr_none
;
295 else if (gdbpy_is_lazy_string (py_str
.get ()))
300 gdb::unique_xmalloc_ptr
<char> encoding
;
301 struct value_print_options local_opts
= *options
;
303 gdbpy_extract_lazy_string (py_str
.get (), &addr
, &type
,
306 local_opts
.addressprint
= false;
307 val_print_string (type
, encoding
.get (), addr
, (int) length
,
308 stream
, &local_opts
);
313 = python_string_to_target_python_string (py_str
.get ());
320 output
= PyBytes_AS_STRING (string
.get ());
321 length
= PyBytes_GET_SIZE (string
.get ());
322 type
= builtin_type (gdbarch
)->builtin_char
;
324 if (hint
&& !strcmp (hint
, "string"))
325 language
->printstr (stream
, type
, (gdb_byte
*) output
,
326 length
, NULL
, 0, options
);
328 gdb_puts (output
, stream
);
332 result
= string_repr_error
;
333 print_stack_unless_memory_error (stream
);
337 else if (replacement
)
339 struct value_print_options opts
= *options
;
341 opts
.addressprint
= false;
342 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
346 result
= string_repr_error
;
347 print_stack_unless_memory_error (stream
);
353 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the
354 printer, if any exist. If is_py_none is true, then nothing has
355 been printed by to_string, and format output accordingly. */
357 print_children (PyObject
*printer
, const char *hint
,
358 struct ui_file
*stream
, int recurse
,
359 const struct value_print_options
*options
,
360 const struct language_defn
*language
,
363 int is_map
, is_array
, done_flag
, pretty
;
366 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
369 /* If we are printing a map or an array, we want some special
371 is_map
= hint
&& ! strcmp (hint
, "map");
372 is_array
= hint
&& ! strcmp (hint
, "array");
374 gdbpy_ref
<> children (PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
376 if (children
== NULL
)
378 print_stack_unless_memory_error (stream
);
382 gdbpy_ref
<> iter (PyObject_GetIter (children
.get ()));
385 print_stack_unless_memory_error (stream
);
389 /* Use the prettyformat_arrays option if we are printing an array,
390 and the pretty option otherwise. */
392 pretty
= options
->prettyformat_arrays
;
395 if (options
->prettyformat
== Val_prettyformat
)
398 pretty
= options
->prettyformat_structs
;
402 for (i
= 0; i
< options
->print_max
; ++i
)
407 gdbpy_ref
<> item (PyIter_Next (iter
.get ()));
410 if (PyErr_Occurred ())
411 print_stack_unless_memory_error (stream
);
412 /* Set a flag so we can know whether we printed all the
413 available elements. */
419 if (! PyTuple_Check (item
.get ()) || PyTuple_Size (item
.get ()) != 2)
421 PyErr_SetString (PyExc_TypeError
,
422 _("Result of children iterator not a tuple"
423 " of two elements."));
424 gdbpy_print_stack ();
427 if (! PyArg_ParseTuple (item
.get (), "sO", &name
, &py_v
))
429 /* The user won't necessarily get a stack trace here, so provide
431 if (gdbpy_print_python_errors_p ())
432 gdb_printf (gdb_stderr
,
433 _("Bad result from children iterator.\n"));
434 gdbpy_print_stack ();
438 /* Print initial "=" to separate print_string_repr output and
439 children. For other elements, there are three cases:
440 1. Maps. Print a "," after each value element.
441 2. Arrays. Always print a ",".
442 3. Other. Always print a ",". */
446 gdb_puts (" = ", stream
);
448 else if (! is_map
|| i
% 2 == 0)
449 gdb_puts (pretty
? "," : ", ", stream
);
451 /* Skip printing children if max_depth has been reached. This check
452 is performed after print_string_repr and the "=" separator so that
453 these steps are not skipped if the variable is located within the
455 if (val_print_check_max_depth (stream
, recurse
, options
, language
))
458 /* Print initial "{" to bookend children. */
459 gdb_puts ("{", stream
);
461 /* In summary mode, we just want to print "= {...}" if there is
463 if (options
->summary
)
465 /* This increment tricks the post-loop logic to print what
473 if (! is_map
|| i
% 2 == 0)
477 gdb_puts ("\n", stream
);
478 print_spaces (2 + 2 * recurse
, stream
);
481 stream
->wrap_here (2 + 2 *recurse
);
484 if (is_map
&& i
% 2 == 0)
485 gdb_puts ("[", stream
);
488 /* We print the index, not whatever the child method
489 returned as the name. */
490 if (options
->print_array_indexes
)
491 gdb_printf (stream
, "[%d] = ", i
);
495 gdb_puts (name
, stream
);
496 gdb_puts (" = ", stream
);
499 if (gdbpy_is_lazy_string (py_v
))
504 gdb::unique_xmalloc_ptr
<char> encoding
;
505 struct value_print_options local_opts
= *options
;
507 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
509 local_opts
.addressprint
= false;
510 val_print_string (type
, encoding
.get (), addr
, (int) length
, stream
,
513 else if (gdbpy_is_string (py_v
))
515 gdb::unique_xmalloc_ptr
<char> output
;
517 output
= python_string_to_host_string (py_v
);
519 gdbpy_print_stack ();
521 gdb_puts (output
.get (), stream
);
525 struct value
*value
= convert_value_from_python (py_v
);
529 gdbpy_print_stack ();
530 error (_("Error while executing Python code."));
534 /* When printing the key of a map we allow one additional
535 level of depth. This means the key will print before the
537 struct value_print_options opt
= *options
;
538 if (is_map
&& i
% 2 == 0
539 && opt
.max_depth
!= -1
540 && opt
.max_depth
< INT_MAX
)
542 common_val_print (value
, stream
, recurse
+ 1, &opt
, language
);
546 if (is_map
&& i
% 2 == 0)
547 gdb_puts ("] = ", stream
);
556 gdb_puts ("\n", stream
);
557 print_spaces (2 + 2 * recurse
, stream
);
559 gdb_puts ("...", stream
);
563 gdb_puts ("\n", stream
);
564 print_spaces (2 * recurse
, stream
);
566 gdb_puts ("}", stream
);
571 gdbpy_apply_val_pretty_printer (const struct extension_language_defn
*extlang
,
573 struct ui_file
*stream
, int recurse
,
574 const struct value_print_options
*options
,
575 const struct language_defn
*language
)
577 struct type
*type
= value_type (value
);
578 struct gdbarch
*gdbarch
= type
->arch ();
579 enum gdbpy_string_repr_result print_result
;
581 if (value_lazy (value
))
582 value_fetch_lazy (value
);
584 /* No pretty-printer support for unavailable values. */
585 if (!value_bytes_available (value
, 0, type
->length ()))
586 return EXT_LANG_RC_NOP
;
588 if (!gdb_python_initialized
)
589 return EXT_LANG_RC_NOP
;
591 gdbpy_enter
enter_py (gdbarch
, language
);
593 gdbpy_ref
<> val_obj (value_to_value_object_no_release (value
));
596 print_stack_unless_memory_error (stream
);
597 return EXT_LANG_RC_ERROR
;
600 /* Find the constructor. */
601 gdbpy_ref
<> printer (find_pretty_printer (val_obj
.get ()));
604 print_stack_unless_memory_error (stream
);
605 return EXT_LANG_RC_ERROR
;
608 if (printer
== Py_None
)
609 return EXT_LANG_RC_NOP
;
611 scoped_restore set_options
= make_scoped_restore (&gdbpy_current_print_options
,
614 /* If we are printing a map, we want some special formatting. */
615 gdb::unique_xmalloc_ptr
<char> hint (gdbpy_get_display_hint (printer
.get ()));
617 /* Print the section */
618 print_result
= print_string_repr (printer
.get (), hint
.get (), stream
,
619 recurse
, options
, language
, gdbarch
);
620 if (print_result
!= string_repr_error
)
621 print_children (printer
.get (), hint
.get (), stream
, recurse
, options
,
622 language
, print_result
== string_repr_none
);
624 if (PyErr_Occurred ())
625 print_stack_unless_memory_error (stream
);
626 return EXT_LANG_RC_OK
;
630 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
631 print object. It must have a 'to_string' method (but this is
632 checked by varobj, not here) which takes no arguments and
633 returns a string. The printer will return a value and in the case
634 of a Python string being returned, this function will return a
635 PyObject containing the string. For any other type, *REPLACEMENT is
636 set to the replacement value and this function returns NULL. On
637 error, *REPLACEMENT is set to NULL and this function also returns
640 apply_varobj_pretty_printer (PyObject
*printer_obj
,
641 struct value
**replacement
,
642 struct ui_file
*stream
,
643 const value_print_options
*opts
)
645 scoped_restore set_options
= make_scoped_restore (&gdbpy_current_print_options
,
649 gdbpy_ref
<> py_str
= pretty_print_one_value (printer_obj
, replacement
);
651 if (*replacement
== NULL
&& py_str
== NULL
)
652 print_stack_unless_memory_error (stream
);
657 /* Find a pretty-printer object for the varobj module. Returns a new
658 reference to the object if successful; returns NULL if not. VALUE
659 is the value for which a printer tests to determine if it
660 can pretty-print the value. */
662 gdbpy_get_varobj_pretty_printer (struct value
*value
)
666 value
= value_copy (value
);
668 catch (const gdb_exception
&except
)
670 GDB_PY_HANDLE_EXCEPTION (except
);
673 gdbpy_ref
<> val_obj (value_to_value_object (value
));
677 return find_pretty_printer (val_obj
.get ());
680 /* A Python function which wraps find_pretty_printer and instantiates
681 the resulting class. This accepts a Value argument and returns a
682 pretty printer instance, or None. This function is useful as an
683 argument to the MI command -var-set-visualizer. */
685 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
690 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
692 value
= value_object_to_value (val_obj
);
695 PyErr_SetString (PyExc_TypeError
,
696 _("Argument must be a gdb.Value."));
700 return find_pretty_printer (val_obj
).release ();
703 /* Helper function to set a boolean in a dictionary. */
705 set_boolean (PyObject
*dict
, const char *name
, bool val
)
707 gdbpy_ref
<> val_obj (PyBool_FromLong (val
));
708 if (val_obj
== nullptr)
710 return PyDict_SetItemString (dict
, name
, val_obj
.get ());
713 /* Helper function to set an integer in a dictionary. */
715 set_unsigned (PyObject
*dict
, const char *name
, unsigned int val
)
717 gdbpy_ref
<> val_obj
= gdb_py_object_from_ulongest (val
);
718 if (val_obj
== nullptr)
720 return PyDict_SetItemString (dict
, name
, val_obj
.get ());
723 /* Implement gdb.print_options. */
725 gdbpy_print_options (PyObject
*unused1
, PyObject
*unused2
)
727 gdbpy_ref
<> result (PyDict_New ());
728 if (result
== nullptr)
731 value_print_options opts
;
732 gdbpy_get_print_options (&opts
);
734 if (set_boolean (result
.get (), "raw",
736 || set_boolean (result
.get (), "pretty_arrays",
737 opts
.prettyformat_arrays
) < 0
738 || set_boolean (result
.get (), "pretty_structs",
739 opts
.prettyformat_structs
) < 0
740 || set_boolean (result
.get (), "array_indexes",
741 opts
.print_array_indexes
) < 0
742 || set_boolean (result
.get (), "symbols",
743 opts
.symbol_print
) < 0
744 || set_boolean (result
.get (), "unions",
746 || set_boolean (result
.get (), "address",
747 opts
.addressprint
) < 0
748 || set_boolean (result
.get (), "deref_refs",
750 || set_boolean (result
.get (), "actual_objects",
751 opts
.objectprint
) < 0
752 || set_boolean (result
.get (), "static_members",
753 opts
.static_field_print
) < 0
754 || set_boolean (result
.get (), "deref_refs",
756 || set_boolean (result
.get (), "nibbles",
757 opts
.nibblesprint
) < 0
758 || set_boolean (result
.get (), "summary",
760 || set_unsigned (result
.get (), "max_elements",
762 || set_unsigned (result
.get (), "max_depth",
764 || set_unsigned (result
.get (), "repeat_threshold",
765 opts
.repeat_count_threshold
) < 0)
768 if (opts
.format
!= 0)
770 char str
[2] = { (char) opts
.format
, 0 };
771 gdbpy_ref
<> fmtstr
= host_string_to_python_string (str
);
772 if (fmtstr
== nullptr)
774 if (PyDict_SetItemString (result
.get (), "format", fmtstr
.get ()) < 0)
778 return result
.release ();
781 /* Helper function that either finds the prevailing print options, or
782 calls get_user_print_options. */
784 gdbpy_get_print_options (value_print_options
*opts
)
786 if (gdbpy_current_print_options
!= nullptr)
787 *opts
= *gdbpy_current_print_options
;
789 get_user_print_options (opts
);