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"
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
)
100 gdbpy_ref
<> objf
= objfile_to_objfile_object (obj
);
103 /* Ignore the error and continue. */
108 gdbpy_ref
<> pp_list (objfpy_get_printers (objf
.get (), NULL
));
109 gdbpy_ref
<> function (search_pp_list (pp_list
.get (), value
));
111 /* If there is an error in any objfile list, abort the search and exit. */
112 if (function
== NULL
)
115 if (function
!= Py_None
)
116 return function
.release ();
122 /* Subroutine of find_pretty_printer to simplify it.
123 Look for a pretty-printer to print VALUE in the current program space.
124 The result is NULL if there's an error and the search should be terminated.
125 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
126 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
129 find_pretty_printer_from_progspace (PyObject
*value
)
131 gdbpy_ref
<> obj
= pspace_to_pspace_object (current_program_space
);
135 gdbpy_ref
<> pp_list (pspy_get_printers (obj
.get (), NULL
));
136 return search_pp_list (pp_list
.get (), value
);
139 /* Subroutine of find_pretty_printer to simplify it.
140 Look for a pretty-printer to print VALUE in the gdb module.
141 The result is NULL if there's an error and the search should be terminated.
142 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
143 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
146 find_pretty_printer_from_gdb (PyObject
*value
)
148 /* Fetch the global pretty printer list. */
149 if (gdb_python_module
== NULL
150 || ! PyObject_HasAttrString (gdb_python_module
, "pretty_printers"))
151 return gdbpy_ref
<>::new_reference (Py_None
);
152 gdbpy_ref
<> pp_list (PyObject_GetAttrString (gdb_python_module
,
154 if (pp_list
== NULL
|| ! PyList_Check (pp_list
.get ()))
155 return gdbpy_ref
<>::new_reference (Py_None
);
157 return search_pp_list (pp_list
.get (), value
);
160 /* Find the pretty-printing constructor function for VALUE. If no
161 pretty-printer exists, return None. If one exists, return a new
162 reference. On error, set the Python error and return NULL. */
165 find_pretty_printer (PyObject
*value
)
167 /* Look at the pretty-printer list for each objfile
168 in the current program-space. */
169 gdbpy_ref
<> function (find_pretty_printer_from_objfiles (value
));
170 if (function
== NULL
|| function
!= Py_None
)
173 /* Look at the pretty-printer list for the current program-space. */
174 function
= find_pretty_printer_from_progspace (value
);
175 if (function
== NULL
|| function
!= Py_None
)
178 /* Look at the pretty-printer list in the gdb module. */
179 return find_pretty_printer_from_gdb (value
);
182 /* Pretty-print a single value, via the printer object PRINTER.
183 If the function returns a string, a PyObject containing the string
184 is returned. If the function returns Py_NONE that means the pretty
185 printer returned the Python None as a value. Otherwise, if the
186 function returns a value, *OUT_VALUE is set to the value, and NULL
187 is returned. On error, *OUT_VALUE is set to NULL, NULL is
188 returned, with a python exception set. */
191 pretty_print_one_value (PyObject
*printer
, struct value
**out_value
)
198 if (!PyObject_HasAttr (printer
, gdbpy_to_string_cst
))
199 result
= gdbpy_ref
<>::new_reference (Py_None
);
202 result
.reset (PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
,
206 if (! gdbpy_is_string (result
.get ())
207 && ! gdbpy_is_lazy_string (result
.get ())
208 && result
!= Py_None
)
210 *out_value
= convert_value_from_python (result
.get ());
211 if (PyErr_Occurred ())
218 CATCH (except
, RETURN_MASK_ALL
)
226 /* Return the display hint for the object printer, PRINTER. Return
227 NULL if there is no display_hint method, or if the method did not
228 return a string. On error, print stack trace and return NULL. On
229 success, return an xmalloc()d string. */
230 gdb::unique_xmalloc_ptr
<char>
231 gdbpy_get_display_hint (PyObject
*printer
)
233 gdb::unique_xmalloc_ptr
<char> result
;
235 if (! PyObject_HasAttr (printer
, gdbpy_display_hint_cst
))
238 gdbpy_ref
<> hint (PyObject_CallMethodObjArgs (printer
, gdbpy_display_hint_cst
,
242 if (gdbpy_is_string (hint
.get ()))
244 result
= python_string_to_host_string (hint
.get ());
246 gdbpy_print_stack ();
250 gdbpy_print_stack ();
255 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
258 print_stack_unless_memory_error (struct ui_file
*stream
)
260 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error
))
262 gdbpy_err_fetch fetched_error
;
263 gdb::unique_xmalloc_ptr
<char> msg
= fetched_error
.to_string ();
265 if (msg
== NULL
|| *msg
== '\0')
266 fprintf_filtered (stream
, _("<error reading variable>"));
268 fprintf_filtered (stream
, _("<error reading variable: %s>"),
272 gdbpy_print_stack ();
275 /* Helper for gdbpy_apply_val_pretty_printer which calls to_string and
276 formats the result. */
278 static enum string_repr_result
279 print_string_repr (PyObject
*printer
, const char *hint
,
280 struct ui_file
*stream
, int recurse
,
281 const struct value_print_options
*options
,
282 const struct language_defn
*language
,
283 struct gdbarch
*gdbarch
)
285 struct value
*replacement
= NULL
;
286 enum string_repr_result result
= string_repr_ok
;
288 gdbpy_ref
<> py_str
= pretty_print_one_value (printer
, &replacement
);
291 if (py_str
== Py_None
)
292 result
= string_repr_none
;
293 else if (gdbpy_is_lazy_string (py_str
.get ()))
298 gdb::unique_xmalloc_ptr
<char> encoding
;
299 struct value_print_options local_opts
= *options
;
301 gdbpy_extract_lazy_string (py_str
.get (), &addr
, &type
,
304 local_opts
.addressprint
= 0;
305 val_print_string (type
, encoding
.get (), addr
, (int) length
,
306 stream
, &local_opts
);
311 = python_string_to_target_python_string (py_str
.get ());
319 output
= PyBytes_AS_STRING (string
.get ());
320 length
= PyBytes_GET_SIZE (string
.get ());
322 output
= PyString_AsString (string
.get ());
323 length
= PyString_Size (string
.get ());
325 type
= builtin_type (gdbarch
)->builtin_char
;
327 if (hint
&& !strcmp (hint
, "string"))
328 LA_PRINT_STRING (stream
, type
, (gdb_byte
*) output
,
329 length
, NULL
, 0, options
);
331 fputs_filtered (output
, stream
);
335 result
= string_repr_error
;
336 print_stack_unless_memory_error (stream
);
340 else if (replacement
)
342 struct value_print_options opts
= *options
;
344 opts
.addressprint
= 0;
345 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
349 result
= string_repr_error
;
350 print_stack_unless_memory_error (stream
);
358 /* Create a dummy PyFrameObject, needed to work around
359 a Python-2.4 bug with generators. */
360 class dummy_python_frame
364 dummy_python_frame ();
366 ~dummy_python_frame ()
369 m_tstate
->frame
= m_saved_frame
;
380 PyFrameObject
*m_saved_frame
;
382 PyThreadState
*m_tstate
;
385 dummy_python_frame::dummy_python_frame ()
387 m_saved_frame (NULL
),
391 PyFrameObject
*frame
;
393 gdbpy_ref
<> empty_string (PyString_FromString (""));
394 if (empty_string
== NULL
)
397 gdbpy_ref
<> null_tuple (PyTuple_New (0));
398 if (null_tuple
== NULL
)
401 code
= PyCode_New (0, /* argcount */
405 empty_string
.get (), /* code */
406 null_tuple
.get (), /* consts */
407 null_tuple
.get (), /* names */
408 null_tuple
.get (), /* varnames */
409 #if PYTHON_API_VERSION >= 1010
410 null_tuple
.get (), /* freevars */
411 null_tuple
.get (), /* cellvars */
413 empty_string
.get (), /* filename */
414 empty_string
.get (), /* name */
416 empty_string
.get () /* lnotab */
420 gdbpy_ref
<> code_holder ((PyObject
*) code
);
422 gdbpy_ref
<> globals (PyDict_New ());
426 m_tstate
= PyThreadState_GET ();
427 frame
= PyFrame_New (m_tstate
, code
, globals
.get (), NULL
);
431 m_frame
.reset ((PyObject
*) frame
);
432 m_tstate
->frame
= frame
;
433 m_saved_frame
= frame
->f_back
;
438 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the
439 printer, if any exist. If is_py_none is true, then nothing has
440 been printed by to_string, and format output accordingly. */
442 print_children (PyObject
*printer
, const char *hint
,
443 struct ui_file
*stream
, int recurse
,
444 const struct value_print_options
*options
,
445 const struct language_defn
*language
,
448 int is_map
, is_array
, done_flag
, pretty
;
451 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
454 /* If we are printing a map or an array, we want some special
456 is_map
= hint
&& ! strcmp (hint
, "map");
457 is_array
= hint
&& ! strcmp (hint
, "array");
459 gdbpy_ref
<> children (PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
461 if (children
== NULL
)
463 print_stack_unless_memory_error (stream
);
467 gdbpy_ref
<> iter (PyObject_GetIter (children
.get ()));
470 print_stack_unless_memory_error (stream
);
474 /* Use the prettyformat_arrays option if we are printing an array,
475 and the pretty option otherwise. */
477 pretty
= options
->prettyformat_arrays
;
480 if (options
->prettyformat
== Val_prettyformat
)
483 pretty
= options
->prettyformat_structs
;
486 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
487 where it insists on having a non-NULL tstate->frame when
488 a generator is called. */
490 dummy_python_frame frame
;
493 gdbpy_print_stack ();
499 for (i
= 0; i
< options
->print_max
; ++i
)
504 gdbpy_ref
<> item (PyIter_Next (iter
.get ()));
507 if (PyErr_Occurred ())
508 print_stack_unless_memory_error (stream
);
509 /* Set a flag so we can know whether we printed all the
510 available elements. */
516 if (! PyTuple_Check (item
.get ()) || PyTuple_Size (item
.get ()) != 2)
518 PyErr_SetString (PyExc_TypeError
,
519 _("Result of children iterator not a tuple"
520 " of two elements."));
521 gdbpy_print_stack ();
524 if (! PyArg_ParseTuple (item
.get (), "sO", &name
, &py_v
))
526 /* The user won't necessarily get a stack trace here, so provide
528 if (gdbpy_print_python_errors_p ())
529 fprintf_unfiltered (gdb_stderr
,
530 _("Bad result from children iterator.\n"));
531 gdbpy_print_stack ();
535 /* Print initial "{". For other elements, there are three
537 1. Maps. Print a "," after each value element.
538 2. Arrays. Always print a ",".
539 3. Other. Always print a ",". */
543 fputs_filtered ("{", stream
);
545 fputs_filtered (" = {", stream
);
548 else if (! is_map
|| i
% 2 == 0)
549 fputs_filtered (pretty
? "," : ", ", stream
);
551 /* In summary mode, we just want to print "= {...}" if there is
553 if (options
->summary
)
555 /* This increment tricks the post-loop logic to print what
563 if (! is_map
|| i
% 2 == 0)
567 fputs_filtered ("\n", stream
);
568 print_spaces_filtered (2 + 2 * recurse
, stream
);
571 wrap_here (n_spaces (2 + 2 *recurse
));
574 if (is_map
&& i
% 2 == 0)
575 fputs_filtered ("[", stream
);
578 /* We print the index, not whatever the child method
579 returned as the name. */
580 if (options
->print_array_indexes
)
581 fprintf_filtered (stream
, "[%d] = ", i
);
585 fputs_filtered (name
, stream
);
586 fputs_filtered (" = ", stream
);
589 if (gdbpy_is_lazy_string (py_v
))
594 gdb::unique_xmalloc_ptr
<char> encoding
;
595 struct value_print_options local_opts
= *options
;
597 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
599 local_opts
.addressprint
= 0;
600 val_print_string (type
, encoding
.get (), addr
, (int) length
, stream
,
603 else if (gdbpy_is_string (py_v
))
605 gdb::unique_xmalloc_ptr
<char> output
;
607 output
= python_string_to_host_string (py_v
);
609 gdbpy_print_stack ();
611 fputs_filtered (output
.get (), stream
);
615 struct value
*value
= convert_value_from_python (py_v
);
619 gdbpy_print_stack ();
620 error (_("Error while executing Python code."));
623 common_val_print (value
, stream
, recurse
+ 1, options
, language
);
626 if (is_map
&& i
% 2 == 0)
627 fputs_filtered ("] = ", stream
);
636 fputs_filtered ("\n", stream
);
637 print_spaces_filtered (2 + 2 * recurse
, stream
);
639 fputs_filtered ("...", stream
);
643 fputs_filtered ("\n", stream
);
644 print_spaces_filtered (2 * recurse
, stream
);
646 fputs_filtered ("}", stream
);
651 gdbpy_apply_val_pretty_printer (const struct extension_language_defn
*extlang
,
653 LONGEST embedded_offset
, CORE_ADDR address
,
654 struct ui_file
*stream
, int recurse
,
656 const struct value_print_options
*options
,
657 const struct language_defn
*language
)
659 struct gdbarch
*gdbarch
= get_type_arch (type
);
661 enum string_repr_result print_result
;
663 if (value_lazy (val
))
664 value_fetch_lazy (val
);
666 /* No pretty-printer support for unavailable values. */
667 if (!value_bytes_available (val
, embedded_offset
, TYPE_LENGTH (type
)))
668 return EXT_LANG_RC_NOP
;
670 if (!gdb_python_initialized
)
671 return EXT_LANG_RC_NOP
;
673 gdbpy_enter
enter_py (gdbarch
, language
);
675 /* Instantiate the printer. */
676 value
= value_from_component (val
, type
, embedded_offset
);
678 gdbpy_ref
<> val_obj (value_to_value_object (value
));
681 print_stack_unless_memory_error (stream
);
682 return EXT_LANG_RC_ERROR
;
685 /* Find the constructor. */
686 gdbpy_ref
<> printer (find_pretty_printer (val_obj
.get ()));
689 print_stack_unless_memory_error (stream
);
690 return EXT_LANG_RC_ERROR
;
693 if (printer
== Py_None
)
694 return EXT_LANG_RC_NOP
;
696 /* If we are printing a map, we want some special formatting. */
697 gdb::unique_xmalloc_ptr
<char> hint (gdbpy_get_display_hint (printer
.get ()));
699 /* Print the section */
700 print_result
= print_string_repr (printer
.get (), hint
.get (), stream
,
701 recurse
, options
, language
, gdbarch
);
702 if (print_result
!= string_repr_error
)
703 print_children (printer
.get (), hint
.get (), stream
, recurse
, options
,
704 language
, print_result
== string_repr_none
);
706 if (PyErr_Occurred ())
707 print_stack_unless_memory_error (stream
);
708 return EXT_LANG_RC_OK
;
712 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
713 print object. It must have a 'to_string' method (but this is
714 checked by varobj, not here) which takes no arguments and
715 returns a string. The printer will return a value and in the case
716 of a Python string being returned, this function will return a
717 PyObject containing the string. For any other type, *REPLACEMENT is
718 set to the replacement value and this function returns NULL. On
719 error, *REPLACEMENT is set to NULL and this function also returns
722 apply_varobj_pretty_printer (PyObject
*printer_obj
,
723 struct value
**replacement
,
724 struct ui_file
*stream
)
727 gdbpy_ref
<> py_str
= pretty_print_one_value (printer_obj
, replacement
);
729 if (*replacement
== NULL
&& py_str
== NULL
)
730 print_stack_unless_memory_error (stream
);
735 /* Find a pretty-printer object for the varobj module. Returns a new
736 reference to the object if successful; returns NULL if not. VALUE
737 is the value for which a printer tests to determine if it
738 can pretty-print the value. */
740 gdbpy_get_varobj_pretty_printer (struct value
*value
)
744 value
= value_copy (value
);
746 CATCH (except
, RETURN_MASK_ALL
)
748 GDB_PY_HANDLE_EXCEPTION (except
);
752 gdbpy_ref
<> val_obj (value_to_value_object (value
));
756 return find_pretty_printer (val_obj
.get ());
759 /* A Python function which wraps find_pretty_printer and instantiates
760 the resulting class. This accepts a Value argument and returns a
761 pretty printer instance, or None. This function is useful as an
762 argument to the MI command -var-set-visualizer. */
764 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
769 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
771 value
= value_object_to_value (val_obj
);
774 PyErr_SetString (PyExc_TypeError
,
775 _("Argument must be a gdb.Value."));
779 return find_pretty_printer (val_obj
).release ();