1 /* Python pretty-printing
3 Copyright (C) 2008-2017 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
, NULL
));
79 else if (printer
!= Py_None
)
80 return printer
.release ();
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
)
99 PyObject
*objf
= objfile_to_objfile_object (obj
);
102 /* Ignore the error and continue. */
107 gdbpy_ref
pp_list (objfpy_get_printers (objf
, NULL
));
108 gdbpy_ref
function (search_pp_list (pp_list
.get (), value
));
110 /* If there is an error in any objfile list, abort the search and exit. */
111 if (function
== NULL
)
114 if (function
!= Py_None
)
115 return function
.release ();
121 /* Subroutine of find_pretty_printer to simplify it.
122 Look for a pretty-printer to print VALUE in the current program space.
123 The result is NULL if there's an error and the search should be terminated.
124 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
125 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
128 find_pretty_printer_from_progspace (PyObject
*value
)
130 PyObject
*obj
= pspace_to_pspace_object (current_program_space
);
134 gdbpy_ref
pp_list (pspy_get_printers (obj
, NULL
));
135 return search_pp_list (pp_list
.get (), value
);
138 /* Subroutine of find_pretty_printer to simplify it.
139 Look for a pretty-printer to print VALUE in the gdb module.
140 The result is NULL if there's an error and the search should be terminated.
141 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
142 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
145 find_pretty_printer_from_gdb (PyObject
*value
)
147 /* Fetch the global pretty printer list. */
148 if (gdb_python_module
== NULL
149 || ! PyObject_HasAttrString (gdb_python_module
, "pretty_printers"))
151 gdbpy_ref
pp_list (PyObject_GetAttrString (gdb_python_module
,
153 if (pp_list
== NULL
|| ! PyList_Check (pp_list
.get ()))
156 return search_pp_list (pp_list
.get (), value
);
159 /* Find the pretty-printing constructor function for VALUE. If no
160 pretty-printer exists, return None. If one exists, return a new
161 reference. On error, set the Python error and return NULL. */
164 find_pretty_printer (PyObject
*value
)
166 /* Look at the pretty-printer list for each objfile
167 in the current program-space. */
168 gdbpy_ref
function (find_pretty_printer_from_objfiles (value
));
169 if (function
== NULL
|| function
!= Py_None
)
170 return function
.release ();
172 /* Look at the pretty-printer list for the current program-space. */
173 function
.reset (find_pretty_printer_from_progspace (value
));
174 if (function
== NULL
|| function
!= Py_None
)
175 return function
.release ();
177 /* Look at the pretty-printer list in the gdb module. */
178 return find_pretty_printer_from_gdb (value
);
181 /* Pretty-print a single value, via the printer object PRINTER.
182 If the function returns a string, a PyObject containing the string
183 is returned. If the function returns Py_NONE that means the pretty
184 printer returned the Python None as a value. Otherwise, if the
185 function returns a value, *OUT_VALUE is set to the value, and NULL
186 is returned. On error, *OUT_VALUE is set to NULL, NULL is
187 returned, with a python exception set. */
190 pretty_print_one_value (PyObject
*printer
, struct value
**out_value
)
192 PyObject
*result
= NULL
;
197 result
= PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
, NULL
);
200 if (! gdbpy_is_string (result
) && ! gdbpy_is_lazy_string (result
)
201 && result
!= Py_None
)
203 *out_value
= convert_value_from_python (result
);
204 if (PyErr_Occurred ())
211 CATCH (except
, RETURN_MASK_ALL
)
219 /* Return the display hint for the object printer, PRINTER. Return
220 NULL if there is no display_hint method, or if the method did not
221 return a string. On error, print stack trace and return NULL. On
222 success, return an xmalloc()d string. */
223 gdb::unique_xmalloc_ptr
<char>
224 gdbpy_get_display_hint (PyObject
*printer
)
226 gdb::unique_xmalloc_ptr
<char> result
;
228 if (! PyObject_HasAttr (printer
, gdbpy_display_hint_cst
))
231 gdbpy_ref
hint (PyObject_CallMethodObjArgs (printer
, gdbpy_display_hint_cst
,
235 if (gdbpy_is_string (hint
.get ()))
237 result
= python_string_to_host_string (hint
.get ());
239 gdbpy_print_stack ();
243 gdbpy_print_stack ();
248 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
251 print_stack_unless_memory_error (struct ui_file
*stream
)
253 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error
))
255 PyObject
*type
, *value
, *trace
;
257 PyErr_Fetch (&type
, &value
, &trace
);
259 gdbpy_ref
type_ref (type
);
260 gdbpy_ref
value_ref (value
);
261 gdbpy_ref
trace_ref (trace
);
263 gdb::unique_xmalloc_ptr
<char>
264 msg (gdbpy_exception_to_string (type
, value
));
266 if (msg
== NULL
|| *msg
== '\0')
267 fprintf_filtered (stream
, _("<error reading variable>"));
269 fprintf_filtered (stream
, _("<error reading variable: %s>"),
273 gdbpy_print_stack ();
276 /* Helper for gdbpy_apply_val_pretty_printer which calls to_string and
277 formats the result. */
279 static enum string_repr_result
280 print_string_repr (PyObject
*printer
, const char *hint
,
281 struct ui_file
*stream
, int recurse
,
282 const struct value_print_options
*options
,
283 const struct language_defn
*language
,
284 struct gdbarch
*gdbarch
)
286 struct value
*replacement
= NULL
;
287 enum string_repr_result result
= string_repr_ok
;
289 gdbpy_ref
py_str (pretty_print_one_value (printer
, &replacement
));
292 if (py_str
== Py_None
)
293 result
= string_repr_none
;
294 else if (gdbpy_is_lazy_string (py_str
.get ()))
299 gdb::unique_xmalloc_ptr
<char> encoding
;
300 struct value_print_options local_opts
= *options
;
302 gdbpy_extract_lazy_string (py_str
.get (), &addr
, &type
,
305 local_opts
.addressprint
= 0;
306 val_print_string (type
, encoding
.get (), addr
, (int) length
,
307 stream
, &local_opts
);
312 (python_string_to_target_python_string (py_str
.get ()));
320 output
= PyBytes_AS_STRING (string
.get ());
321 length
= PyBytes_GET_SIZE (string
.get ());
323 output
= PyString_AsString (string
.get ());
324 length
= PyString_Size (string
.get ());
326 type
= builtin_type (gdbarch
)->builtin_char
;
328 if (hint
&& !strcmp (hint
, "string"))
329 LA_PRINT_STRING (stream
, type
, (gdb_byte
*) output
,
330 length
, NULL
, 0, options
);
332 fputs_filtered (output
, stream
);
336 result
= string_repr_error
;
337 print_stack_unless_memory_error (stream
);
341 else if (replacement
)
343 struct value_print_options opts
= *options
;
345 opts
.addressprint
= 0;
346 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
350 result
= string_repr_error
;
351 print_stack_unless_memory_error (stream
);
359 /* Create a dummy PyFrameObject, needed to work around
360 a Python-2.4 bug with generators. */
361 class dummy_python_frame
365 dummy_python_frame ();
367 ~dummy_python_frame ()
370 m_tstate
->frame
= m_saved_frame
;
381 PyFrameObject
*m_saved_frame
;
383 PyThreadState
*m_tstate
;
386 dummy_python_frame::dummy_python_frame ()
388 m_saved_frame (NULL
),
392 PyFrameObject
*frame
;
394 gdbpy_ref
empty_string (PyString_FromString (""));
395 if (empty_string
== NULL
)
398 gdbpy_ref
null_tuple (PyTuple_New (0));
399 if (null_tuple
== NULL
)
402 code
= PyCode_New (0, /* argcount */
406 empty_string
.get (), /* code */
407 null_tuple
.get (), /* consts */
408 null_tuple
.get (), /* names */
409 null_tuple
.get (), /* varnames */
410 #if PYTHON_API_VERSION >= 1010
411 null_tuple
.get (), /* freevars */
412 null_tuple
.get (), /* cellvars */
414 empty_string
.get (), /* filename */
415 empty_string
.get (), /* name */
417 empty_string
.get () /* lnotab */
421 gdbpy_ref
code_holder ((PyObject
*) code
);
423 gdbpy_ref
globals (PyDict_New ());
427 m_tstate
= PyThreadState_GET ();
428 frame
= PyFrame_New (m_tstate
, code
, globals
.get (), NULL
);
432 m_frame
.reset ((PyObject
*) frame
);
433 m_tstate
->frame
= frame
;
434 m_saved_frame
= frame
->f_back
;
439 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the
440 printer, if any exist. If is_py_none is true, then nothing has
441 been printed by to_string, and format output accordingly. */
443 print_children (PyObject
*printer
, const char *hint
,
444 struct ui_file
*stream
, int recurse
,
445 const struct value_print_options
*options
,
446 const struct language_defn
*language
,
449 int is_map
, is_array
, done_flag
, pretty
;
452 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
455 /* If we are printing a map or an array, we want some special
457 is_map
= hint
&& ! strcmp (hint
, "map");
458 is_array
= hint
&& ! strcmp (hint
, "array");
460 gdbpy_ref
children (PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
462 if (children
== NULL
)
464 print_stack_unless_memory_error (stream
);
468 gdbpy_ref
iter (PyObject_GetIter (children
.get ()));
471 print_stack_unless_memory_error (stream
);
475 /* Use the prettyformat_arrays option if we are printing an array,
476 and the pretty option otherwise. */
478 pretty
= options
->prettyformat_arrays
;
481 if (options
->prettyformat
== Val_prettyformat
)
484 pretty
= options
->prettyformat_structs
;
487 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
488 where it insists on having a non-NULL tstate->frame when
489 a generator is called. */
491 dummy_python_frame frame
;
494 gdbpy_print_stack ();
500 for (i
= 0; i
< options
->print_max
; ++i
)
505 gdbpy_ref
item (PyIter_Next (iter
.get ()));
508 if (PyErr_Occurred ())
509 print_stack_unless_memory_error (stream
);
510 /* Set a flag so we can know whether we printed all the
511 available elements. */
517 if (! PyTuple_Check (item
.get ()) || PyTuple_Size (item
.get ()) != 2)
519 PyErr_SetString (PyExc_TypeError
,
520 _("Result of children iterator not a tuple"
521 " of two elements."));
522 gdbpy_print_stack ();
525 if (! PyArg_ParseTuple (item
.get (), "sO", &name
, &py_v
))
527 /* The user won't necessarily get a stack trace here, so provide
529 if (gdbpy_print_python_errors_p ())
530 fprintf_unfiltered (gdb_stderr
,
531 _("Bad result from children iterator.\n"));
532 gdbpy_print_stack ();
536 /* Print initial "{". For other elements, there are three
538 1. Maps. Print a "," after each value element.
539 2. Arrays. Always print a ",".
540 3. Other. Always print a ",". */
544 fputs_filtered ("{", stream
);
546 fputs_filtered (" = {", stream
);
549 else if (! is_map
|| i
% 2 == 0)
550 fputs_filtered (pretty
? "," : ", ", stream
);
552 /* In summary mode, we just want to print "= {...}" if there is
554 if (options
->summary
)
556 /* This increment tricks the post-loop logic to print what
564 if (! is_map
|| i
% 2 == 0)
568 fputs_filtered ("\n", stream
);
569 print_spaces_filtered (2 + 2 * recurse
, stream
);
572 wrap_here (n_spaces (2 + 2 *recurse
));
575 if (is_map
&& i
% 2 == 0)
576 fputs_filtered ("[", stream
);
579 /* We print the index, not whatever the child method
580 returned as the name. */
581 if (options
->print_array_indexes
)
582 fprintf_filtered (stream
, "[%d] = ", i
);
586 fputs_filtered (name
, stream
);
587 fputs_filtered (" = ", stream
);
590 if (gdbpy_is_lazy_string (py_v
))
595 gdb::unique_xmalloc_ptr
<char> encoding
;
596 struct value_print_options local_opts
= *options
;
598 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
600 local_opts
.addressprint
= 0;
601 val_print_string (type
, encoding
.get (), addr
, (int) length
, stream
,
604 else if (gdbpy_is_string (py_v
))
606 gdb::unique_xmalloc_ptr
<char> output
;
608 output
= python_string_to_host_string (py_v
);
610 gdbpy_print_stack ();
612 fputs_filtered (output
.get (), stream
);
616 struct value
*value
= convert_value_from_python (py_v
);
620 gdbpy_print_stack ();
621 error (_("Error while executing Python code."));
624 common_val_print (value
, stream
, recurse
+ 1, options
, language
);
627 if (is_map
&& i
% 2 == 0)
628 fputs_filtered ("] = ", stream
);
637 fputs_filtered ("\n", stream
);
638 print_spaces_filtered (2 + 2 * recurse
, stream
);
640 fputs_filtered ("...", stream
);
644 fputs_filtered ("\n", stream
);
645 print_spaces_filtered (2 * recurse
, stream
);
647 fputs_filtered ("}", stream
);
652 gdbpy_apply_val_pretty_printer (const struct extension_language_defn
*extlang
,
654 LONGEST embedded_offset
, CORE_ADDR address
,
655 struct ui_file
*stream
, int recurse
,
657 const struct value_print_options
*options
,
658 const struct language_defn
*language
)
660 struct gdbarch
*gdbarch
= get_type_arch (type
);
662 enum string_repr_result print_result
;
663 const gdb_byte
*valaddr
= value_contents_for_printing (val
);
665 /* No pretty-printer support for unavailable values. */
666 if (!value_bytes_available (val
, embedded_offset
, TYPE_LENGTH (type
)))
667 return EXT_LANG_RC_NOP
;
669 if (!gdb_python_initialized
)
670 return EXT_LANG_RC_NOP
;
672 gdbpy_enter
enter_py (gdbarch
, language
);
674 /* Instantiate the printer. */
675 value
= value_from_component (val
, type
, embedded_offset
);
677 gdbpy_ref
val_obj (value_to_value_object (value
));
680 print_stack_unless_memory_error (stream
);
681 return EXT_LANG_RC_ERROR
;
684 /* Find the constructor. */
685 gdbpy_ref
printer (find_pretty_printer (val_obj
.get ()));
688 print_stack_unless_memory_error (stream
);
689 return EXT_LANG_RC_ERROR
;
692 if (printer
== Py_None
)
693 return EXT_LANG_RC_NOP
;
695 /* If we are printing a map, we want some special formatting. */
696 gdb::unique_xmalloc_ptr
<char> hint (gdbpy_get_display_hint (printer
.get ()));
698 /* Print the section */
699 print_result
= print_string_repr (printer
.get (), hint
.get (), stream
,
700 recurse
, options
, language
, gdbarch
);
701 if (print_result
!= string_repr_error
)
702 print_children (printer
.get (), hint
.get (), stream
, recurse
, options
,
703 language
, print_result
== string_repr_none
);
705 if (PyErr_Occurred ())
706 print_stack_unless_memory_error (stream
);
707 return EXT_LANG_RC_OK
;
711 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
712 print object. It must have a 'to_string' method (but this is
713 checked by varobj, not here) which takes no arguments and
714 returns a string. The printer will return a value and in the case
715 of a Python string being returned, this function will return a
716 PyObject containing the string. For any other type, *REPLACEMENT is
717 set to the replacement value and this function returns NULL. On
718 error, *REPLACEMENT is set to NULL and this function also returns
721 apply_varobj_pretty_printer (PyObject
*printer_obj
,
722 struct value
**replacement
,
723 struct ui_file
*stream
)
725 PyObject
*py_str
= NULL
;
728 py_str
= pretty_print_one_value (printer_obj
, replacement
);
730 if (*replacement
== NULL
&& py_str
== NULL
)
731 print_stack_unless_memory_error (stream
);
736 /* Find a pretty-printer object for the varobj module. Returns a new
737 reference to the object if successful; returns NULL if not. VALUE
738 is the value for which a printer tests to determine if it
739 can pretty-print the value. */
741 gdbpy_get_varobj_pretty_printer (struct value
*value
)
745 value
= value_copy (value
);
747 CATCH (except
, RETURN_MASK_ALL
)
749 GDB_PY_HANDLE_EXCEPTION (except
);
753 gdbpy_ref
val_obj (value_to_value_object (value
));
757 return find_pretty_printer (val_obj
.get ());
760 /* A Python function which wraps find_pretty_printer and instantiates
761 the resulting class. This accepts a Value argument and returns a
762 pretty printer instance, or None. This function is useful as an
763 argument to the MI command -var-set-visualizer. */
765 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
771 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
773 value
= value_object_to_value (val_obj
);
776 PyErr_SetString (PyExc_TypeError
,
777 _("Argument must be a gdb.Value."));
781 cons
= find_pretty_printer (val_obj
);