1 /* Python pretty-printing
3 Copyright (C) 2008-2016 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"
29 /* Return type of print_string_repr. */
31 enum string_repr_result
33 /* The string method returned None. */
35 /* The string method had an error. */
41 /* Helper function for find_pretty_printer which iterates over a list,
42 calls each function and inspects output. This will return a
43 printer object if one recognizes VALUE. If no printer is found, it
44 will return None. On error, it will set the Python error and
48 search_pp_list (PyObject
*list
, PyObject
*value
)
50 Py_ssize_t pp_list_size
, list_index
;
51 PyObject
*function
, *printer
= NULL
;
53 pp_list_size
= PyList_Size (list
);
54 for (list_index
= 0; list_index
< pp_list_size
; list_index
++)
56 function
= PyList_GetItem (list
, list_index
);
60 /* Skip if disabled. */
61 if (PyObject_HasAttr (function
, gdbpy_enabled_cst
))
63 PyObject
*attr
= PyObject_GetAttr (function
, gdbpy_enabled_cst
);
68 cmp
= PyObject_IsTrue (attr
);
77 printer
= PyObject_CallFunctionObjArgs (function
, value
, NULL
);
80 else if (printer
!= Py_None
)
89 /* Subroutine of find_pretty_printer to simplify it.
90 Look for a pretty-printer to print VALUE in all objfiles.
91 The result is NULL if there's an error and the search should be terminated.
92 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
93 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
96 find_pretty_printer_from_objfiles (PyObject
*value
)
104 PyObject
*objf
= objfile_to_objfile_object (obj
);
107 /* Ignore the error and continue. */
112 pp_list
= objfpy_get_printers (objf
, NULL
);
113 function
= search_pp_list (pp_list
, value
);
114 Py_XDECREF (pp_list
);
116 /* If there is an error in any objfile list, abort the search and exit. */
120 if (function
!= Py_None
)
123 Py_DECREF (function
);
129 /* Subroutine of find_pretty_printer to simplify it.
130 Look for a pretty-printer to print VALUE in the current program space.
131 The result is NULL if there's an error and the search should be terminated.
132 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
133 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
136 find_pretty_printer_from_progspace (PyObject
*value
)
140 PyObject
*obj
= pspace_to_pspace_object (current_program_space
);
144 pp_list
= pspy_get_printers (obj
, NULL
);
145 function
= search_pp_list (pp_list
, value
);
146 Py_XDECREF (pp_list
);
150 /* Subroutine of find_pretty_printer to simplify it.
151 Look for a pretty-printer to print VALUE in the gdb module.
152 The result is NULL if there's an error and the search should be terminated.
153 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
154 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
157 find_pretty_printer_from_gdb (PyObject
*value
)
162 /* Fetch the global pretty printer list. */
163 if (gdb_python_module
== NULL
164 || ! PyObject_HasAttrString (gdb_python_module
, "pretty_printers"))
166 pp_list
= PyObject_GetAttrString (gdb_python_module
, "pretty_printers");
167 if (pp_list
== NULL
|| ! PyList_Check (pp_list
))
169 Py_XDECREF (pp_list
);
173 function
= search_pp_list (pp_list
, value
);
174 Py_XDECREF (pp_list
);
178 /* Find the pretty-printing constructor function for VALUE. If no
179 pretty-printer exists, return None. If one exists, return a new
180 reference. On error, set the Python error and return NULL. */
183 find_pretty_printer (PyObject
*value
)
187 /* Look at the pretty-printer list for each objfile
188 in the current program-space. */
189 function
= find_pretty_printer_from_objfiles (value
);
190 if (function
== NULL
|| function
!= Py_None
)
192 Py_DECREF (function
);
194 /* Look at the pretty-printer list for the current program-space. */
195 function
= find_pretty_printer_from_progspace (value
);
196 if (function
== NULL
|| function
!= Py_None
)
198 Py_DECREF (function
);
200 /* Look at the pretty-printer list in the gdb module. */
201 function
= find_pretty_printer_from_gdb (value
);
205 /* Pretty-print a single value, via the printer object PRINTER.
206 If the function returns a string, a PyObject containing the string
207 is returned. If the function returns Py_NONE that means the pretty
208 printer returned the Python None as a value. Otherwise, if the
209 function returns a value, *OUT_VALUE is set to the value, and NULL
210 is returned. On error, *OUT_VALUE is set to NULL, NULL is
211 returned, with a python exception set. */
214 pretty_print_one_value (PyObject
*printer
, struct value
**out_value
)
216 PyObject
*result
= NULL
;
221 result
= PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
, NULL
);
224 if (! gdbpy_is_string (result
) && ! gdbpy_is_lazy_string (result
)
225 && result
!= Py_None
)
227 *out_value
= convert_value_from_python (result
);
228 if (PyErr_Occurred ())
235 CATCH (except
, RETURN_MASK_ALL
)
243 /* Return the display hint for the object printer, PRINTER. Return
244 NULL if there is no display_hint method, or if the method did not
245 return a string. On error, print stack trace and return NULL. On
246 success, return an xmalloc()d string. */
247 gdb::unique_xmalloc_ptr
<char>
248 gdbpy_get_display_hint (PyObject
*printer
)
251 gdb::unique_xmalloc_ptr
<char> result
;
253 if (! PyObject_HasAttr (printer
, gdbpy_display_hint_cst
))
256 hint
= PyObject_CallMethodObjArgs (printer
, gdbpy_display_hint_cst
, NULL
);
259 if (gdbpy_is_string (hint
))
261 result
= python_string_to_host_string (hint
);
263 gdbpy_print_stack ();
268 gdbpy_print_stack ();
273 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
276 print_stack_unless_memory_error (struct ui_file
*stream
)
278 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error
))
280 struct cleanup
*cleanup
;
281 PyObject
*type
, *value
, *trace
;
283 PyErr_Fetch (&type
, &value
, &trace
);
284 cleanup
= make_cleanup_py_decref (type
);
285 make_cleanup_py_decref (value
);
286 make_cleanup_py_decref (trace
);
288 gdb::unique_xmalloc_ptr
<char>
289 msg (gdbpy_exception_to_string (type
, value
));
291 if (msg
== NULL
|| *msg
== '\0')
292 fprintf_filtered (stream
, _("<error reading variable>"));
294 fprintf_filtered (stream
, _("<error reading variable: %s>"),
297 do_cleanups (cleanup
);
300 gdbpy_print_stack ();
303 /* Helper for gdbpy_apply_val_pretty_printer which calls to_string and
304 formats the result. */
306 static enum string_repr_result
307 print_string_repr (PyObject
*printer
, const char *hint
,
308 struct ui_file
*stream
, int recurse
,
309 const struct value_print_options
*options
,
310 const struct language_defn
*language
,
311 struct gdbarch
*gdbarch
)
313 struct value
*replacement
= NULL
;
314 PyObject
*py_str
= NULL
;
315 enum string_repr_result result
= string_repr_ok
;
317 py_str
= pretty_print_one_value (printer
, &replacement
);
320 struct cleanup
*cleanup
= make_cleanup_py_decref (py_str
);
322 if (py_str
== Py_None
)
323 result
= string_repr_none
;
324 else if (gdbpy_is_lazy_string (py_str
))
329 char *encoding
= NULL
;
330 struct value_print_options local_opts
= *options
;
332 make_cleanup (free_current_contents
, &encoding
);
333 gdbpy_extract_lazy_string (py_str
, &addr
, &type
,
336 local_opts
.addressprint
= 0;
337 val_print_string (type
, encoding
, addr
, (int) length
,
338 stream
, &local_opts
);
344 string
= python_string_to_target_python_string (py_str
);
351 make_cleanup_py_decref (string
);
353 output
= PyBytes_AS_STRING (string
);
354 length
= PyBytes_GET_SIZE (string
);
356 output
= PyString_AsString (string
);
357 length
= PyString_Size (string
);
359 type
= builtin_type (gdbarch
)->builtin_char
;
361 if (hint
&& !strcmp (hint
, "string"))
362 LA_PRINT_STRING (stream
, type
, (gdb_byte
*) output
,
363 length
, NULL
, 0, options
);
365 fputs_filtered (output
, stream
);
369 result
= string_repr_error
;
370 print_stack_unless_memory_error (stream
);
374 do_cleanups (cleanup
);
376 else if (replacement
)
378 struct value_print_options opts
= *options
;
380 opts
.addressprint
= 0;
381 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
385 result
= string_repr_error
;
386 print_stack_unless_memory_error (stream
);
394 py_restore_tstate (void *p
)
396 PyFrameObject
*frame
= (PyFrameObject
*) p
;
397 PyThreadState
*tstate
= PyThreadState_GET ();
399 tstate
->frame
= frame
;
402 /* Create a dummy PyFrameObject, needed to work around
403 a Python-2.4 bug with generators. */
405 push_dummy_python_frame (void)
407 PyObject
*empty_string
, *null_tuple
, *globals
;
409 PyFrameObject
*frame
;
410 PyThreadState
*tstate
;
412 empty_string
= PyString_FromString ("");
416 null_tuple
= PyTuple_New (0);
419 Py_DECREF (empty_string
);
423 code
= PyCode_New (0, /* argcount */
427 empty_string
, /* code */
428 null_tuple
, /* consts */
429 null_tuple
, /* names */
430 null_tuple
, /* varnames */
431 #if PYTHON_API_VERSION >= 1010
432 null_tuple
, /* freevars */
433 null_tuple
, /* cellvars */
435 empty_string
, /* filename */
436 empty_string
, /* name */
438 empty_string
/* lnotab */
441 Py_DECREF (empty_string
);
442 Py_DECREF (null_tuple
);
447 globals
= PyDict_New ();
454 tstate
= PyThreadState_GET ();
456 frame
= PyFrame_New (tstate
, code
, globals
, NULL
);
464 tstate
->frame
= frame
;
465 make_cleanup (py_restore_tstate
, frame
->f_back
);
466 return (PyObject
*) frame
;
470 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the
471 printer, if any exist. If is_py_none is true, then nothing has
472 been printed by to_string, and format output accordingly. */
474 print_children (PyObject
*printer
, const char *hint
,
475 struct ui_file
*stream
, int recurse
,
476 const struct value_print_options
*options
,
477 const struct language_defn
*language
,
480 int is_map
, is_array
, done_flag
, pretty
;
482 PyObject
*children
, *iter
;
486 struct cleanup
*cleanups
;
488 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
491 /* If we are printing a map or an array, we want some special
493 is_map
= hint
&& ! strcmp (hint
, "map");
494 is_array
= hint
&& ! strcmp (hint
, "array");
496 children
= PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
500 print_stack_unless_memory_error (stream
);
504 cleanups
= make_cleanup_py_decref (children
);
506 iter
= PyObject_GetIter (children
);
509 print_stack_unless_memory_error (stream
);
512 make_cleanup_py_decref (iter
);
514 /* Use the prettyformat_arrays option if we are printing an array,
515 and the pretty option otherwise. */
517 pretty
= options
->prettyformat_arrays
;
520 if (options
->prettyformat
== Val_prettyformat
)
523 pretty
= options
->prettyformat_structs
;
526 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
527 where it insists on having a non-NULL tstate->frame when
528 a generator is called. */
530 frame
= push_dummy_python_frame ();
533 gdbpy_print_stack ();
536 make_cleanup_py_decref (frame
);
540 for (i
= 0; i
< options
->print_max
; ++i
)
542 PyObject
*py_v
, *item
= PyIter_Next (iter
);
544 struct cleanup
*inner_cleanup
;
548 if (PyErr_Occurred ())
549 print_stack_unless_memory_error (stream
);
550 /* Set a flag so we can know whether we printed all the
551 available elements. */
557 if (! PyTuple_Check (item
) || PyTuple_Size (item
) != 2)
559 PyErr_SetString (PyExc_TypeError
,
560 _("Result of children iterator not a tuple"
561 " of two elements."));
562 gdbpy_print_stack ();
566 if (! PyArg_ParseTuple (item
, "sO", &name
, &py_v
))
568 /* The user won't necessarily get a stack trace here, so provide
570 if (gdbpy_print_python_errors_p ())
571 fprintf_unfiltered (gdb_stderr
,
572 _("Bad result from children iterator.\n"));
573 gdbpy_print_stack ();
577 inner_cleanup
= make_cleanup_py_decref (item
);
579 /* Print initial "{". For other elements, there are three
581 1. Maps. Print a "," after each value element.
582 2. Arrays. Always print a ",".
583 3. Other. Always print a ",". */
587 fputs_filtered ("{", stream
);
589 fputs_filtered (" = {", stream
);
592 else if (! is_map
|| i
% 2 == 0)
593 fputs_filtered (pretty
? "," : ", ", stream
);
595 /* In summary mode, we just want to print "= {...}" if there is
597 if (options
->summary
)
599 /* This increment tricks the post-loop logic to print what
607 if (! is_map
|| i
% 2 == 0)
611 fputs_filtered ("\n", stream
);
612 print_spaces_filtered (2 + 2 * recurse
, stream
);
615 wrap_here (n_spaces (2 + 2 *recurse
));
618 if (is_map
&& i
% 2 == 0)
619 fputs_filtered ("[", stream
);
622 /* We print the index, not whatever the child method
623 returned as the name. */
624 if (options
->print_array_indexes
)
625 fprintf_filtered (stream
, "[%d] = ", i
);
629 fputs_filtered (name
, stream
);
630 fputs_filtered (" = ", stream
);
633 if (gdbpy_is_lazy_string (py_v
))
638 char *encoding
= NULL
;
639 struct value_print_options local_opts
= *options
;
641 make_cleanup (free_current_contents
, &encoding
);
642 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
644 local_opts
.addressprint
= 0;
645 val_print_string (type
, encoding
, addr
, (int) length
, stream
,
648 else if (gdbpy_is_string (py_v
))
650 gdb::unique_xmalloc_ptr
<char> output
;
652 output
= python_string_to_host_string (py_v
);
654 gdbpy_print_stack ();
656 fputs_filtered (output
.get (), stream
);
660 struct value
*value
= convert_value_from_python (py_v
);
664 gdbpy_print_stack ();
665 error (_("Error while executing Python code."));
668 common_val_print (value
, stream
, recurse
+ 1, options
, language
);
671 if (is_map
&& i
% 2 == 0)
672 fputs_filtered ("] = ", stream
);
674 do_cleanups (inner_cleanup
);
683 fputs_filtered ("\n", stream
);
684 print_spaces_filtered (2 + 2 * recurse
, stream
);
686 fputs_filtered ("...", stream
);
690 fputs_filtered ("\n", stream
);
691 print_spaces_filtered (2 * recurse
, stream
);
693 fputs_filtered ("}", stream
);
697 do_cleanups (cleanups
);
701 gdbpy_apply_val_pretty_printer (const struct extension_language_defn
*extlang
,
703 LONGEST embedded_offset
, CORE_ADDR address
,
704 struct ui_file
*stream
, int recurse
,
706 const struct value_print_options
*options
,
707 const struct language_defn
*language
)
709 struct gdbarch
*gdbarch
= get_type_arch (type
);
710 PyObject
*printer
= NULL
;
711 PyObject
*val_obj
= NULL
;
713 gdb::unique_xmalloc_ptr
<char> hint
;
714 struct cleanup
*cleanups
;
715 enum ext_lang_rc result
= EXT_LANG_RC_NOP
;
716 enum string_repr_result print_result
;
717 const gdb_byte
*valaddr
= value_contents_for_printing (val
);
719 /* No pretty-printer support for unavailable values. */
720 if (!value_bytes_available (val
, embedded_offset
, TYPE_LENGTH (type
)))
721 return EXT_LANG_RC_NOP
;
723 if (!gdb_python_initialized
)
724 return EXT_LANG_RC_NOP
;
726 cleanups
= ensure_python_env (gdbarch
, language
);
728 /* Instantiate the printer. */
729 value
= value_from_contents_and_address (type
, valaddr
+ embedded_offset
,
730 address
+ embedded_offset
);
732 set_value_component_location (value
, val
);
733 /* set_value_component_location resets the address, so we may
734 need to set it again. */
735 if (VALUE_LVAL (value
) != lval_internalvar
736 && VALUE_LVAL (value
) != lval_internalvar_component
737 && VALUE_LVAL (value
) != lval_computed
)
738 set_value_address (value
, address
+ embedded_offset
);
740 val_obj
= value_to_value_object (value
);
743 result
= EXT_LANG_RC_ERROR
;
747 /* Find the constructor. */
748 printer
= find_pretty_printer (val_obj
);
753 result
= EXT_LANG_RC_ERROR
;
757 make_cleanup_py_decref (printer
);
758 if (printer
== Py_None
)
760 result
= EXT_LANG_RC_NOP
;
764 /* If we are printing a map, we want some special formatting. */
765 hint
= gdbpy_get_display_hint (printer
);
767 /* Print the section */
768 print_result
= print_string_repr (printer
, hint
.get (), stream
, recurse
,
769 options
, language
, gdbarch
);
770 if (print_result
!= string_repr_error
)
771 print_children (printer
, hint
.get (), stream
, recurse
, options
, language
,
772 print_result
== string_repr_none
);
774 result
= EXT_LANG_RC_OK
;
777 if (PyErr_Occurred ())
778 print_stack_unless_memory_error (stream
);
779 do_cleanups (cleanups
);
784 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
785 print object. It must have a 'to_string' method (but this is
786 checked by varobj, not here) which takes no arguments and
787 returns a string. The printer will return a value and in the case
788 of a Python string being returned, this function will return a
789 PyObject containing the string. For any other type, *REPLACEMENT is
790 set to the replacement value and this function returns NULL. On
791 error, *REPLACEMENT is set to NULL and this function also returns
794 apply_varobj_pretty_printer (PyObject
*printer_obj
,
795 struct value
**replacement
,
796 struct ui_file
*stream
)
798 PyObject
*py_str
= NULL
;
801 py_str
= pretty_print_one_value (printer_obj
, replacement
);
803 if (*replacement
== NULL
&& py_str
== NULL
)
804 print_stack_unless_memory_error (stream
);
809 /* Find a pretty-printer object for the varobj module. Returns a new
810 reference to the object if successful; returns NULL if not. VALUE
811 is the value for which a printer tests to determine if it
812 can pretty-print the value. */
814 gdbpy_get_varobj_pretty_printer (struct value
*value
)
817 PyObject
*pretty_printer
= NULL
;
821 value
= value_copy (value
);
823 CATCH (except
, RETURN_MASK_ALL
)
825 GDB_PY_HANDLE_EXCEPTION (except
);
829 val_obj
= value_to_value_object (value
);
833 pretty_printer
= find_pretty_printer (val_obj
);
835 return pretty_printer
;
838 /* A Python function which wraps find_pretty_printer and instantiates
839 the resulting class. This accepts a Value argument and returns a
840 pretty printer instance, or None. This function is useful as an
841 argument to the MI command -var-set-visualizer. */
843 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
849 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
851 value
= value_object_to_value (val_obj
);
854 PyErr_SetString (PyExc_TypeError
,
855 _("Argument must be a gdb.Value."));
859 cons
= find_pretty_printer (val_obj
);