1 /* Python pretty-printing
3 Copyright (C) 2008-2021 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 string_repr_result
34 /* The string method returned None. */
36 /* The string method had an error. */
42 /* Helper function for find_pretty_printer which iterates over a list,
43 calls each function and inspects output. This will return a
44 printer object if one recognizes VALUE. If no printer is found, it
45 will return None. On error, it will set the Python error and
49 search_pp_list (PyObject *list, PyObject *value)
51 Py_ssize_t pp_list_size, list_index;
53 pp_list_size = PyList_Size (list);
54 for (list_index = 0; list_index < pp_list_size; list_index++)
56 PyObject *function = PyList_GetItem (list, list_index);
60 /* Skip if disabled. */
61 if (PyObject_HasAttr (function, gdbpy_enabled_cst))
63 gdbpy_ref<> attr (PyObject_GetAttr (function, gdbpy_enabled_cst));
68 cmp = PyObject_IsTrue (attr.get ());
76 gdbpy_ref<> printer (PyObject_CallFunctionObjArgs (function, value,
80 else if (printer != Py_None)
84 return gdbpy_ref<>::new_reference (Py_None);
87 /* Subroutine of find_pretty_printer to simplify it.
88 Look for a pretty-printer to print VALUE in all objfiles.
89 The result is NULL if there's an error and the search should be terminated.
90 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
91 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
94 find_pretty_printer_from_objfiles (PyObject *value)
96 for (objfile *obj : current_program_space->objfiles ())
98 gdbpy_ref<> objf = objfile_to_objfile_object (obj);
101 /* Ignore the error and continue. */
106 gdbpy_ref<> pp_list (objfpy_get_printers (objf.get (), NULL));
107 gdbpy_ref<> function (search_pp_list (pp_list.get (), value));
109 /* If there is an error in any objfile list, abort the search and exit. */
110 if (function == NULL)
113 if (function != Py_None)
114 return function.release ();
120 /* Subroutine of find_pretty_printer to simplify it.
121 Look for a pretty-printer to print VALUE in the current program space.
122 The result is NULL if there's an error and the search should be terminated.
123 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
124 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
127 find_pretty_printer_from_progspace (PyObject *value)
129 gdbpy_ref<> obj = pspace_to_pspace_object (current_program_space);
133 gdbpy_ref<> pp_list (pspy_get_printers (obj.get (), NULL));
134 return search_pp_list (pp_list.get (), value);
137 /* Subroutine of find_pretty_printer to simplify it.
138 Look for a pretty-printer to print VALUE in the gdb module.
139 The result is NULL if there's an error and the search should be terminated.
140 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
141 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
144 find_pretty_printer_from_gdb (PyObject *value)
146 /* Fetch the global pretty printer list. */
147 if (gdb_python_module == NULL
148 || ! PyObject_HasAttrString (gdb_python_module, "pretty_printers"))
149 return gdbpy_ref<>::new_reference (Py_None);
150 gdbpy_ref<> pp_list (PyObject_GetAttrString (gdb_python_module,
152 if (pp_list == NULL || ! PyList_Check (pp_list.get ()))
153 return gdbpy_ref<>::new_reference (Py_None);
155 return search_pp_list (pp_list.get (), value);
158 /* Find the pretty-printing constructor function for VALUE. If no
159 pretty-printer exists, return None. If one exists, return a new
160 reference. On error, set the Python error and return NULL. */
163 find_pretty_printer (PyObject *value)
165 /* Look at the pretty-printer list for each objfile
166 in the current program-space. */
167 gdbpy_ref<> function (find_pretty_printer_from_objfiles (value));
168 if (function == NULL || function != Py_None)
171 /* Look at the pretty-printer list for the current program-space. */
172 function = find_pretty_printer_from_progspace (value);
173 if (function == NULL || function != Py_None)
176 /* Look at the pretty-printer list in the gdb module. */
177 return find_pretty_printer_from_gdb (value);
180 /* Pretty-print a single value, via the printer object PRINTER.
181 If the function returns a string, a PyObject containing the string
182 is returned. If the function returns Py_NONE that means the pretty
183 printer returned the Python None as a value. Otherwise, if the
184 function returns a value, *OUT_VALUE is set to the value, and NULL
185 is returned. On error, *OUT_VALUE is set to NULL, NULL is
186 returned, with a python exception set. */
189 pretty_print_one_value (PyObject *printer, struct value **out_value)
196 if (!PyObject_HasAttr (printer, gdbpy_to_string_cst))
197 result = gdbpy_ref<>::new_reference (Py_None);
200 result.reset (PyObject_CallMethodObjArgs (printer, gdbpy_to_string_cst,
204 if (! gdbpy_is_string (result.get ())
205 && ! gdbpy_is_lazy_string (result.get ())
206 && result != Py_None)
208 *out_value = convert_value_from_python (result.get ());
209 if (PyErr_Occurred ())
216 catch (const gdb_exception &except)
223 /* Return the display hint for the object printer, PRINTER. Return
224 NULL if there is no display_hint method, or if the method did not
225 return a string. On error, print stack trace and return NULL. On
226 success, return an xmalloc()d string. */
227 gdb::unique_xmalloc_ptr<char>
228 gdbpy_get_display_hint (PyObject *printer)
230 gdb::unique_xmalloc_ptr<char> result;
232 if (! PyObject_HasAttr (printer, gdbpy_display_hint_cst))
235 gdbpy_ref<> hint (PyObject_CallMethodObjArgs (printer, gdbpy_display_hint_cst,
239 if (gdbpy_is_string (hint.get ()))
241 result = python_string_to_host_string (hint.get ());
243 gdbpy_print_stack ();
247 gdbpy_print_stack ();
252 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
255 print_stack_unless_memory_error (struct ui_file *stream)
257 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error))
259 gdbpy_err_fetch fetched_error;
260 gdb::unique_xmalloc_ptr<char> msg = fetched_error.to_string ();
262 if (msg == NULL || *msg == '\0')
263 fprintf_styled (stream, metadata_style.style (),
264 _("<error reading variable>"));
266 fprintf_styled (stream, metadata_style.style (),
267 _("<error reading variable: %s>"), msg.get ());
270 gdbpy_print_stack ();
273 /* Helper for gdbpy_apply_val_pretty_printer which calls to_string and
274 formats the result. */
276 static enum string_repr_result
277 print_string_repr (PyObject *printer, const char *hint,
278 struct ui_file *stream, int recurse,
279 const struct value_print_options *options,
280 const struct language_defn *language,
281 struct gdbarch *gdbarch)
283 struct value *replacement = NULL;
284 enum string_repr_result result = string_repr_ok;
286 gdbpy_ref<> py_str = pretty_print_one_value (printer, &replacement);
289 if (py_str == Py_None)
290 result = string_repr_none;
291 else if (gdbpy_is_lazy_string (py_str.get ()))
296 gdb::unique_xmalloc_ptr<char> encoding;
297 struct value_print_options local_opts = *options;
299 gdbpy_extract_lazy_string (py_str.get (), &addr, &type,
302 local_opts.addressprint = 0;
303 val_print_string (type, encoding.get (), addr, (int) length,
304 stream, &local_opts);
309 = python_string_to_target_python_string (py_str.get ());
316 output = PyBytes_AS_STRING (string.get ());
317 length = PyBytes_GET_SIZE (string.get ());
318 type = builtin_type (gdbarch)->builtin_char;
320 if (hint && !strcmp (hint, "string"))
321 language->printstr (stream, type, (gdb_byte *) output,
322 length, NULL, 0, options);
324 fputs_filtered (output, stream);
328 result = string_repr_error;
329 print_stack_unless_memory_error (stream);
333 else if (replacement)
335 struct value_print_options opts = *options;
337 opts.addressprint = 0;
338 common_val_print (replacement, stream, recurse, &opts, language);
342 result = string_repr_error;
343 print_stack_unless_memory_error (stream);
349 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the
350 printer, if any exist. If is_py_none is true, then nothing has
351 been printed by to_string, and format output accordingly. */
353 print_children (PyObject *printer, const char *hint,
354 struct ui_file *stream, int recurse,
355 const struct value_print_options *options,
356 const struct language_defn *language,
359 int is_map, is_array, done_flag, pretty;
362 if (! PyObject_HasAttr (printer, gdbpy_children_cst))
365 /* If we are printing a map or an array, we want some special
367 is_map = hint && ! strcmp (hint, "map");
368 is_array = hint && ! strcmp (hint, "array");
370 gdbpy_ref<> children (PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
372 if (children == NULL)
374 print_stack_unless_memory_error (stream);
378 gdbpy_ref<> iter (PyObject_GetIter (children.get ()));
381 print_stack_unless_memory_error (stream);
385 /* Use the prettyformat_arrays option if we are printing an array,
386 and the pretty option otherwise. */
388 pretty = options->prettyformat_arrays;
391 if (options->prettyformat == Val_prettyformat)
394 pretty = options->prettyformat_structs;
398 for (i = 0; i < options->print_max; ++i)
403 gdbpy_ref<> item (PyIter_Next (iter.get ()));
406 if (PyErr_Occurred ())
407 print_stack_unless_memory_error (stream);
408 /* Set a flag so we can know whether we printed all the
409 available elements. */
415 if (! PyTuple_Check (item.get ()) || PyTuple_Size (item.get ()) != 2)
417 PyErr_SetString (PyExc_TypeError,
418 _("Result of children iterator not a tuple"
419 " of two elements."));
420 gdbpy_print_stack ();
423 if (! PyArg_ParseTuple (item.get (), "sO", &name, &py_v))
425 /* The user won't necessarily get a stack trace here, so provide
427 if (gdbpy_print_python_errors_p ())
428 fprintf_unfiltered (gdb_stderr,
429 _("Bad result from children iterator.\n"));
430 gdbpy_print_stack ();
434 /* Print initial "=" to separate print_string_repr output and
435 children. For other elements, there are three cases:
436 1. Maps. Print a "," after each value element.
437 2. Arrays. Always print a ",".
438 3. Other. Always print a ",". */
442 fputs_filtered (" = ", stream);
444 else if (! is_map || i % 2 == 0)
445 fputs_filtered (pretty ? "," : ", ", stream);
447 /* Skip printing children if max_depth has been reached. This check
448 is performed after print_string_repr and the "=" separator so that
449 these steps are not skipped if the variable is located within the
451 if (val_print_check_max_depth (stream, recurse, options, language))
454 /* Print initial "{" to bookend children. */
455 fputs_filtered ("{", stream);
457 /* In summary mode, we just want to print "= {...}" if there is
459 if (options->summary)
461 /* This increment tricks the post-loop logic to print what
469 if (! is_map || i % 2 == 0)
473 fputs_filtered ("\n", stream);
474 print_spaces_filtered (2 + 2 * recurse, stream);
477 wrap_here (n_spaces (2 + 2 *recurse));
480 if (is_map && i % 2 == 0)
481 fputs_filtered ("[", stream);
484 /* We print the index, not whatever the child method
485 returned as the name. */
486 if (options->print_array_indexes)
487 fprintf_filtered (stream, "[%d] = ", i);
491 fputs_filtered (name, stream);
492 fputs_filtered (" = ", stream);
495 if (gdbpy_is_lazy_string (py_v))
500 gdb::unique_xmalloc_ptr<char> encoding;
501 struct value_print_options local_opts = *options;
503 gdbpy_extract_lazy_string (py_v, &addr, &type, &length, &encoding);
505 local_opts.addressprint = 0;
506 val_print_string (type, encoding.get (), addr, (int) length, stream,
509 else if (gdbpy_is_string (py_v))
511 gdb::unique_xmalloc_ptr<char> output;
513 output = python_string_to_host_string (py_v);
515 gdbpy_print_stack ();
517 fputs_filtered (output.get (), stream);
521 struct value *value = convert_value_from_python (py_v);
525 gdbpy_print_stack ();
526 error (_("Error while executing Python code."));
530 /* When printing the key of a map we allow one additional
531 level of depth. This means the key will print before the
533 struct value_print_options opt = *options;
534 if (is_map && i % 2 == 0
535 && opt.max_depth != -1
536 && opt.max_depth < INT_MAX)
538 common_val_print (value, stream, recurse + 1, &opt, language);
542 if (is_map && i % 2 == 0)
543 fputs_filtered ("] = ", stream);
552 fputs_filtered ("\n", stream);
553 print_spaces_filtered (2 + 2 * recurse, stream);
555 fputs_filtered ("...", stream);
559 fputs_filtered ("\n", stream);
560 print_spaces_filtered (2 * recurse, stream);
562 fputs_filtered ("}", stream);
567 gdbpy_apply_val_pretty_printer (const struct extension_language_defn *extlang,
569 struct ui_file *stream, int recurse,
570 const struct value_print_options *options,
571 const struct language_defn *language)
573 struct type *type = value_type (value);
574 struct gdbarch *gdbarch = type->arch ();
575 enum string_repr_result print_result;
577 if (value_lazy (value))
578 value_fetch_lazy (value);
580 /* No pretty-printer support for unavailable values. */
581 if (!value_bytes_available (value, 0, TYPE_LENGTH (type)))
582 return EXT_LANG_RC_NOP;
584 if (!gdb_python_initialized)
585 return EXT_LANG_RC_NOP;
587 gdbpy_enter enter_py (gdbarch, language);
589 gdbpy_ref<> val_obj (value_to_value_object_no_release (value));
592 print_stack_unless_memory_error (stream);
593 return EXT_LANG_RC_ERROR;
596 /* Find the constructor. */
597 gdbpy_ref<> printer (find_pretty_printer (val_obj.get ()));
600 print_stack_unless_memory_error (stream);
601 return EXT_LANG_RC_ERROR;
604 if (printer == Py_None)
605 return EXT_LANG_RC_NOP;
607 /* If we are printing a map, we want some special formatting. */
608 gdb::unique_xmalloc_ptr<char> hint (gdbpy_get_display_hint (printer.get ()));
610 /* Print the section */
611 print_result = print_string_repr (printer.get (), hint.get (), stream,
612 recurse, options, language, gdbarch);
613 if (print_result != string_repr_error)
614 print_children (printer.get (), hint.get (), stream, recurse, options,
615 language, print_result == string_repr_none);
617 if (PyErr_Occurred ())
618 print_stack_unless_memory_error (stream);
619 return EXT_LANG_RC_OK;
623 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
624 print object. It must have a 'to_string' method (but this is
625 checked by varobj, not here) which takes no arguments and
626 returns a string. The printer will return a value and in the case
627 of a Python string being returned, this function will return a
628 PyObject containing the string. For any other type, *REPLACEMENT is
629 set to the replacement value and this function returns NULL. On
630 error, *REPLACEMENT is set to NULL and this function also returns
633 apply_varobj_pretty_printer (PyObject *printer_obj,
634 struct value **replacement,
635 struct ui_file *stream)
638 gdbpy_ref<> py_str = pretty_print_one_value (printer_obj, replacement);
640 if (*replacement == NULL && py_str == NULL)
641 print_stack_unless_memory_error (stream);
646 /* Find a pretty-printer object for the varobj module. Returns a new
647 reference to the object if successful; returns NULL if not. VALUE
648 is the value for which a printer tests to determine if it
649 can pretty-print the value. */
651 gdbpy_get_varobj_pretty_printer (struct value *value)
655 value = value_copy (value);
657 catch (const gdb_exception &except)
659 GDB_PY_HANDLE_EXCEPTION (except);
662 gdbpy_ref<> val_obj (value_to_value_object (value));
666 return find_pretty_printer (val_obj.get ());
669 /* A Python function which wraps find_pretty_printer and instantiates
670 the resulting class. This accepts a Value argument and returns a
671 pretty printer instance, or None. This function is useful as an
672 argument to the MI command -var-set-visualizer. */
674 gdbpy_default_visualizer (PyObject *self, PyObject *args)
679 if (! PyArg_ParseTuple (args, "O", &val_obj))
681 value = value_object_to_value (val_obj);
684 PyErr_SetString (PyExc_TypeError,
685 _("Argument must be a gdb.Value."));
689 return find_pretty_printer (val_obj).release ();