1 /* Python pretty-printing
3 Copyright (C) 2008-2024 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/>. */
24 #include "extension-priv.h"
26 #include "python-internal.h"
27 #include "cli/cli-style.h"
29 extern PyTypeObject printer_object_type
;
31 /* Return type of print_string_repr. */
33 enum gdbpy_string_repr_result
35 /* The string method returned None. */
37 /* The string method had an error. */
43 /* If non-null, points to options that are in effect while
45 const struct value_print_options
*gdbpy_current_print_options
;
47 /* Helper function for find_pretty_printer which iterates over a list,
48 calls each function and inspects output. This will return a
49 printer object if one recognizes VALUE. If no printer is found, it
50 will return None. On error, it will set the Python error and
54 search_pp_list (PyObject
*list
, PyObject
*value
)
56 Py_ssize_t pp_list_size
, list_index
;
58 pp_list_size
= PyList_Size (list
);
59 for (list_index
= 0; list_index
< pp_list_size
; list_index
++)
61 PyObject
*function
= PyList_GetItem (list
, list_index
);
65 /* Skip if disabled. */
66 if (PyObject_HasAttr (function
, gdbpy_enabled_cst
))
68 gdbpy_ref
<> attr (PyObject_GetAttr (function
, gdbpy_enabled_cst
));
73 cmp
= PyObject_IsTrue (attr
.get ());
81 gdbpy_ref
<> printer (PyObject_CallFunctionObjArgs (function
, value
,
85 else if (printer
!= Py_None
)
89 return gdbpy_ref
<>::new_reference (Py_None
);
92 /* Subroutine of find_pretty_printer to simplify it.
93 Look for a pretty-printer to print VALUE in all objfiles.
94 The result is NULL if there's an error and the search should be terminated.
95 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
96 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
99 find_pretty_printer_from_objfiles (PyObject
*value
)
101 for (objfile
*obj
: current_program_space
->objfiles ())
103 gdbpy_ref
<> objf
= objfile_to_objfile_object (obj
);
106 /* Ignore the error and continue. */
111 gdbpy_ref
<> pp_list (objfpy_get_printers (objf
.get (), NULL
));
112 gdbpy_ref
<> function (search_pp_list (pp_list
.get (), value
));
114 /* If there is an error in any objfile list, abort the search and exit. */
115 if (function
== NULL
)
118 if (function
!= Py_None
)
119 return function
.release ();
125 /* Subroutine of find_pretty_printer to simplify it.
126 Look for a pretty-printer to print VALUE in the current program space.
127 The result is NULL if there's an error and the search should be terminated.
128 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
129 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
132 find_pretty_printer_from_progspace (PyObject
*value
)
134 gdbpy_ref
<> obj
= pspace_to_pspace_object (current_program_space
);
138 gdbpy_ref
<> pp_list (pspy_get_printers (obj
.get (), NULL
));
139 return search_pp_list (pp_list
.get (), value
);
142 /* Subroutine of find_pretty_printer to simplify it.
143 Look for a pretty-printer to print VALUE in the gdb module.
144 The result is NULL if there's an error and the search should be terminated.
145 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
146 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
149 find_pretty_printer_from_gdb (PyObject
*value
)
151 /* Fetch the global pretty printer list. */
152 if (gdb_python_module
== NULL
153 || ! PyObject_HasAttrString (gdb_python_module
, "pretty_printers"))
154 return gdbpy_ref
<>::new_reference (Py_None
);
155 gdbpy_ref
<> pp_list (PyObject_GetAttrString (gdb_python_module
,
157 if (pp_list
== NULL
|| ! PyList_Check (pp_list
.get ()))
158 return gdbpy_ref
<>::new_reference (Py_None
);
160 return search_pp_list (pp_list
.get (), value
);
163 /* Find the pretty-printing constructor function for VALUE. If no
164 pretty-printer exists, return None. If one exists, return a new
165 reference. On error, set the Python error and return NULL. */
168 find_pretty_printer (PyObject
*value
)
170 /* Look at the pretty-printer list for each objfile
171 in the current program-space. */
172 gdbpy_ref
<> function (find_pretty_printer_from_objfiles (value
));
173 if (function
== NULL
|| function
!= Py_None
)
176 /* Look at the pretty-printer list for the current program-space. */
177 function
= find_pretty_printer_from_progspace (value
);
178 if (function
== NULL
|| function
!= Py_None
)
181 /* Look at the pretty-printer list in the gdb module. */
182 return find_pretty_printer_from_gdb (value
);
185 /* Pretty-print a single value, via the printer object PRINTER.
186 If the function returns a string, a PyObject containing the string
187 is returned. If the function returns Py_NONE that means the pretty
188 printer returned the Python None as a value. Otherwise, if the
189 function returns a value, *OUT_VALUE is set to the value, and NULL
190 is returned. On error, *OUT_VALUE is set to NULL, NULL is
191 returned, with a python exception set. */
194 pretty_print_one_value (PyObject
*printer
, struct value
**out_value
)
201 if (!PyObject_HasAttr (printer
, gdbpy_to_string_cst
))
202 result
= gdbpy_ref
<>::new_reference (Py_None
);
205 result
.reset (PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
,
209 if (! gdbpy_is_string (result
.get ())
210 && ! gdbpy_is_lazy_string (result
.get ())
211 && result
!= Py_None
)
213 *out_value
= convert_value_from_python (result
.get ());
214 if (PyErr_Occurred ())
221 catch (const gdb_exception
&except
)
228 /* Return the display hint for the object printer, PRINTER. Return
229 NULL if there is no display_hint method, or if the method did not
230 return a string. On error, print stack trace and return NULL. On
231 success, return an xmalloc()d string. */
232 gdb::unique_xmalloc_ptr
<char>
233 gdbpy_get_display_hint (PyObject
*printer
)
235 gdb::unique_xmalloc_ptr
<char> result
;
237 if (! PyObject_HasAttr (printer
, gdbpy_display_hint_cst
))
240 gdbpy_ref
<> hint (PyObject_CallMethodObjArgs (printer
, gdbpy_display_hint_cst
,
244 if (gdbpy_is_string (hint
.get ()))
246 result
= python_string_to_host_string (hint
.get ());
248 gdbpy_print_stack ();
252 gdbpy_print_stack ();
257 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
260 print_stack_unless_memory_error (struct ui_file
*stream
)
262 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error
))
264 gdbpy_err_fetch fetched_error
;
265 gdb::unique_xmalloc_ptr
<char> msg
= fetched_error
.to_string ();
267 if (msg
== NULL
|| *msg
== '\0')
268 fprintf_styled (stream
, metadata_style
.style (),
269 _("<error reading variable>"));
271 fprintf_styled (stream
, metadata_style
.style (),
272 _("<error reading variable: %s>"), msg
.get ());
275 gdbpy_print_stack ();
278 /* Helper for gdbpy_apply_val_pretty_printer which calls to_string and
279 formats the result. */
281 static enum gdbpy_string_repr_result
282 print_string_repr (PyObject
*printer
, const char *hint
,
283 struct ui_file
*stream
, int recurse
,
284 const struct value_print_options
*options
,
285 const struct language_defn
*language
,
286 struct gdbarch
*gdbarch
)
288 struct value
*replacement
= NULL
;
289 enum gdbpy_string_repr_result result
= string_repr_ok
;
291 gdbpy_ref
<> py_str
= pretty_print_one_value (printer
, &replacement
);
294 if (py_str
== Py_None
)
295 result
= string_repr_none
;
296 else if (gdbpy_is_lazy_string (py_str
.get ()))
301 gdb::unique_xmalloc_ptr
<char> encoding
;
302 struct value_print_options local_opts
= *options
;
304 gdbpy_extract_lazy_string (py_str
.get (), &addr
, &type
,
307 local_opts
.addressprint
= false;
308 val_print_string (type
, encoding
.get (), addr
, (int) length
,
309 stream
, &local_opts
);
314 = python_string_to_target_python_string (py_str
.get ());
321 output
= PyBytes_AS_STRING (string
.get ());
322 length
= PyBytes_GET_SIZE (string
.get ());
323 type
= builtin_type (gdbarch
)->builtin_char
;
325 if (hint
&& !strcmp (hint
, "string"))
326 language
->printstr (stream
, type
, (gdb_byte
*) output
,
327 length
, NULL
, 0, options
);
329 gdb_puts (output
, stream
);
333 result
= string_repr_error
;
334 print_stack_unless_memory_error (stream
);
338 else if (replacement
)
340 struct value_print_options opts
= *options
;
342 opts
.addressprint
= false;
343 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
347 result
= string_repr_error
;
348 print_stack_unless_memory_error (stream
);
354 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the
355 printer, if any exist. If is_py_none is true, then nothing has
356 been printed by to_string, and format output accordingly. */
358 print_children (PyObject
*printer
, const char *hint
,
359 struct ui_file
*stream
, int recurse
,
360 const struct value_print_options
*options
,
361 const struct language_defn
*language
,
364 int is_map
, is_array
, done_flag
, pretty
;
367 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
370 /* If we are printing a map or an array, we want some special
372 is_map
= hint
&& ! strcmp (hint
, "map");
373 is_array
= hint
&& ! strcmp (hint
, "array");
375 gdbpy_ref
<> children (PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
377 if (children
== NULL
)
379 print_stack_unless_memory_error (stream
);
383 gdbpy_ref
<> iter (PyObject_GetIter (children
.get ()));
386 print_stack_unless_memory_error (stream
);
390 /* Use the prettyformat_arrays option if we are printing an array,
391 and the pretty option otherwise. */
393 pretty
= options
->prettyformat_arrays
;
396 if (options
->prettyformat
== Val_prettyformat
)
399 pretty
= options
->prettyformat_structs
;
403 for (i
= 0; i
< options
->print_max
; ++i
)
408 gdbpy_ref
<> item (PyIter_Next (iter
.get ()));
411 if (PyErr_Occurred ())
412 print_stack_unless_memory_error (stream
);
413 /* Set a flag so we can know whether we printed all the
414 available elements. */
420 if (! PyTuple_Check (item
.get ()) || PyTuple_Size (item
.get ()) != 2)
422 PyErr_SetString (PyExc_TypeError
,
423 _("Result of children iterator not a tuple"
424 " of two elements."));
425 gdbpy_print_stack ();
428 if (! PyArg_ParseTuple (item
.get (), "sO", &name
, &py_v
))
430 /* The user won't necessarily get a stack trace here, so provide
432 if (gdbpy_print_python_errors_p ())
433 gdb_printf (gdb_stderr
,
434 _("Bad result from children iterator.\n"));
435 gdbpy_print_stack ();
439 /* Print initial "=" to separate print_string_repr output and
440 children. For other elements, there are three cases:
441 1. Maps. Print a "," after each value element.
442 2. Arrays. Always print a ",".
443 3. Other. Always print a ",". */
447 gdb_puts (" = ", stream
);
449 else if (! is_map
|| i
% 2 == 0)
450 gdb_puts (pretty
? "," : ", ", stream
);
452 /* Skip printing children if max_depth has been reached. This check
453 is performed after print_string_repr and the "=" separator so that
454 these steps are not skipped if the variable is located within the
456 if (val_print_check_max_depth (stream
, recurse
, options
, language
))
459 /* Print initial "{" to bookend children. */
460 gdb_puts ("{", stream
);
462 /* In summary mode, we just want to print "= {...}" if there is
464 if (options
->summary
)
466 /* This increment tricks the post-loop logic to print what
474 if (! is_map
|| i
% 2 == 0)
478 gdb_puts ("\n", stream
);
479 print_spaces (2 + 2 * recurse
, stream
);
482 stream
->wrap_here (2 + 2 *recurse
);
485 if (is_map
&& i
% 2 == 0)
486 gdb_puts ("[", stream
);
489 /* We print the index, not whatever the child method
490 returned as the name. */
491 if (options
->print_array_indexes
)
492 gdb_printf (stream
, "[%d] = ", i
);
496 gdb_puts (name
, stream
);
497 gdb_puts (" = ", stream
);
500 if (gdbpy_is_lazy_string (py_v
))
505 gdb::unique_xmalloc_ptr
<char> encoding
;
506 struct value_print_options local_opts
= *options
;
508 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
510 local_opts
.addressprint
= false;
511 val_print_string (type
, encoding
.get (), addr
, (int) length
, stream
,
514 else if (gdbpy_is_string (py_v
))
516 gdb::unique_xmalloc_ptr
<char> output
;
518 output
= python_string_to_host_string (py_v
);
520 gdbpy_print_stack ();
522 gdb_puts (output
.get (), stream
);
526 struct value
*value
= convert_value_from_python (py_v
);
530 gdbpy_print_stack ();
531 error (_("Error while executing Python code."));
535 /* When printing the key of a map we allow one additional
536 level of depth. This means the key will print before the
538 struct value_print_options opt
= *options
;
539 if (is_map
&& i
% 2 == 0
540 && opt
.max_depth
!= -1
541 && opt
.max_depth
< INT_MAX
)
543 common_val_print (value
, stream
, recurse
+ 1, &opt
, language
);
547 if (is_map
&& i
% 2 == 0)
548 gdb_puts ("] = ", stream
);
557 gdb_puts ("\n", stream
);
558 print_spaces (2 + 2 * recurse
, stream
);
560 gdb_puts ("...", stream
);
564 gdb_puts ("\n", stream
);
565 print_spaces (2 * recurse
, stream
);
567 gdb_puts ("}", stream
);
572 gdbpy_apply_val_pretty_printer (const struct extension_language_defn
*extlang
,
574 struct ui_file
*stream
, int recurse
,
575 const struct value_print_options
*options
,
576 const struct language_defn
*language
)
578 struct type
*type
= value
->type ();
579 struct gdbarch
*gdbarch
= type
->arch ();
580 enum gdbpy_string_repr_result print_result
;
583 value
->fetch_lazy ();
585 /* No pretty-printer support for unavailable values. */
586 if (!value
->bytes_available (0, type
->length ()))
587 return EXT_LANG_RC_NOP
;
589 if (!gdb_python_initialized
)
590 return EXT_LANG_RC_NOP
;
592 gdbpy_enter
enter_py (gdbarch
, language
);
594 gdbpy_ref
<> val_obj (value_to_value_object (value
));
597 print_stack_unless_memory_error (stream
);
598 return EXT_LANG_RC_ERROR
;
601 /* Find the constructor. */
602 gdbpy_ref
<> printer (find_pretty_printer (val_obj
.get ()));
605 print_stack_unless_memory_error (stream
);
606 return EXT_LANG_RC_ERROR
;
609 if (printer
== Py_None
)
610 return EXT_LANG_RC_NOP
;
612 scoped_restore set_options
= make_scoped_restore (&gdbpy_current_print_options
,
615 /* If we are printing a map, we want some special formatting. */
616 gdb::unique_xmalloc_ptr
<char> hint (gdbpy_get_display_hint (printer
.get ()));
618 /* Print the section */
619 print_result
= print_string_repr (printer
.get (), hint
.get (), stream
,
620 recurse
, options
, language
, gdbarch
);
621 if (print_result
!= string_repr_error
)
622 print_children (printer
.get (), hint
.get (), stream
, recurse
, options
,
623 language
, print_result
== string_repr_none
);
625 if (PyErr_Occurred ())
626 print_stack_unless_memory_error (stream
);
627 return EXT_LANG_RC_OK
;
631 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
632 print object. It must have a 'to_string' method (but this is
633 checked by varobj, not here) which takes no arguments and
634 returns a string. The printer will return a value and in the case
635 of a Python string being returned, this function will return a
636 PyObject containing the string. For any other type, *REPLACEMENT is
637 set to the replacement value and this function returns NULL. On
638 error, *REPLACEMENT is set to NULL and this function also returns
641 apply_varobj_pretty_printer (PyObject
*printer_obj
,
642 struct value
**replacement
,
643 struct ui_file
*stream
,
644 const value_print_options
*opts
)
646 scoped_restore set_options
= make_scoped_restore (&gdbpy_current_print_options
,
650 gdbpy_ref
<> py_str
= pretty_print_one_value (printer_obj
, replacement
);
652 if (*replacement
== NULL
&& py_str
== NULL
)
653 print_stack_unless_memory_error (stream
);
658 /* Find a pretty-printer object for the varobj module. Returns a new
659 reference to the object if successful; returns NULL if not. VALUE
660 is the value for which a printer tests to determine if it
661 can pretty-print the value. */
663 gdbpy_get_varobj_pretty_printer (struct value
*value
)
665 gdbpy_ref
<> val_obj (value_to_value_object (value
));
669 return find_pretty_printer (val_obj
.get ());
672 /* A Python function which wraps find_pretty_printer and instantiates
673 the resulting class. This accepts a Value argument and returns a
674 pretty printer instance, or None. This function is useful as an
675 argument to the MI command -var-set-visualizer. */
677 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
682 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
684 value
= value_object_to_value (val_obj
);
687 PyErr_SetString (PyExc_TypeError
,
688 _("Argument must be a gdb.Value."));
692 return find_pretty_printer (val_obj
).release ();
695 /* Helper function to set a boolean in a dictionary. */
697 set_boolean (PyObject
*dict
, const char *name
, bool val
)
699 gdbpy_ref
<> val_obj (PyBool_FromLong (val
));
700 if (val_obj
== nullptr)
702 return PyDict_SetItemString (dict
, name
, val_obj
.get ());
705 /* Helper function to set an integer in a dictionary. */
707 set_unsigned (PyObject
*dict
, const char *name
, unsigned int val
)
709 gdbpy_ref
<> val_obj
= gdb_py_object_from_ulongest (val
);
710 if (val_obj
== nullptr)
712 return PyDict_SetItemString (dict
, name
, val_obj
.get ());
715 /* Implement gdb.print_options. */
717 gdbpy_print_options (PyObject
*unused1
, PyObject
*unused2
)
719 gdbpy_ref
<> result (PyDict_New ());
720 if (result
== nullptr)
723 value_print_options opts
;
724 gdbpy_get_print_options (&opts
);
726 if (set_boolean (result
.get (), "raw",
728 || set_boolean (result
.get (), "pretty_arrays",
729 opts
.prettyformat_arrays
) < 0
730 || set_boolean (result
.get (), "pretty_structs",
731 opts
.prettyformat_structs
) < 0
732 || set_boolean (result
.get (), "array_indexes",
733 opts
.print_array_indexes
) < 0
734 || set_boolean (result
.get (), "symbols",
735 opts
.symbol_print
) < 0
736 || set_boolean (result
.get (), "unions",
738 || set_boolean (result
.get (), "address",
739 opts
.addressprint
) < 0
740 || set_boolean (result
.get (), "deref_refs",
742 || set_boolean (result
.get (), "actual_objects",
743 opts
.objectprint
) < 0
744 || set_boolean (result
.get (), "static_members",
745 opts
.static_field_print
) < 0
746 || set_boolean (result
.get (), "deref_refs",
748 || set_boolean (result
.get (), "nibbles",
749 opts
.nibblesprint
) < 0
750 || set_boolean (result
.get (), "summary",
752 || set_unsigned (result
.get (), "max_elements",
754 || set_unsigned (result
.get (), "max_depth",
756 || set_unsigned (result
.get (), "repeat_threshold",
757 opts
.repeat_count_threshold
) < 0)
760 if (opts
.format
!= 0)
762 char str
[2] = { (char) opts
.format
, 0 };
763 gdbpy_ref
<> fmtstr
= host_string_to_python_string (str
);
764 if (fmtstr
== nullptr)
766 if (PyDict_SetItemString (result
.get (), "format", fmtstr
.get ()) < 0)
770 return result
.release ();
773 /* Helper function that either finds the prevailing print options, or
774 calls get_user_print_options. */
776 gdbpy_get_print_options (value_print_options
*opts
)
778 if (gdbpy_current_print_options
!= nullptr)
779 *opts
= *gdbpy_current_print_options
;
781 get_user_print_options (opts
);
784 /* A ValuePrinter is just a "tag", so it has no state other than that
785 required by Python. */
786 struct printer_object
791 /* The ValuePrinter type object. */
792 PyTypeObject printer_object_type
=
794 PyVarObject_HEAD_INIT (NULL
, 0)
795 "gdb.ValuePrinter", /*tp_name*/
796 sizeof (printer_object
), /*tp_basicsize*/
805 0, /*tp_as_sequence*/
813 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
814 "GDB value printer object", /* tp_doc */
817 0, /* tp_richcompare */
818 0, /* tp_weaklistoffset */
826 0, /* tp_descr_get */
827 0, /* tp_descr_set */
828 0, /* tp_dictoffset */
831 PyType_GenericNew
, /* tp_new */
834 /* Set up the ValuePrinter type. */
837 gdbpy_initialize_prettyprint ()
839 return gdbpy_type_ready (&printer_object_type
);
842 GDBPY_INITIALIZE_FILE (gdbpy_initialize_prettyprint
);