1 /* Python pretty-printing
3 Copyright (C) 2008-2015 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 volatile struct gdb_exception except
;
217 PyObject
*result
= NULL
;
220 TRY_CATCH (except
, RETURN_MASK_ALL
)
222 result
= PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
, NULL
);
225 if (! gdbpy_is_string (result
) && ! gdbpy_is_lazy_string (result
)
226 && result
!= Py_None
)
228 *out_value
= convert_value_from_python (result
);
229 if (PyErr_Occurred ())
240 /* Return the display hint for the object printer, PRINTER. Return
241 NULL if there is no display_hint method, or if the method did not
242 return a string. On error, print stack trace and return NULL. On
243 success, return an xmalloc()d string. */
245 gdbpy_get_display_hint (PyObject
*printer
)
250 if (! PyObject_HasAttr (printer
, gdbpy_display_hint_cst
))
253 hint
= PyObject_CallMethodObjArgs (printer
, gdbpy_display_hint_cst
, NULL
);
256 if (gdbpy_is_string (hint
))
258 result
= python_string_to_host_string (hint
);
260 gdbpy_print_stack ();
265 gdbpy_print_stack ();
270 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
273 print_stack_unless_memory_error (struct ui_file
*stream
)
275 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error
))
277 struct cleanup
*cleanup
;
278 PyObject
*type
, *value
, *trace
;
281 PyErr_Fetch (&type
, &value
, &trace
);
282 cleanup
= make_cleanup_py_decref (type
);
283 make_cleanup_py_decref (value
);
284 make_cleanup_py_decref (trace
);
286 msg
= gdbpy_exception_to_string (type
, value
);
287 make_cleanup (xfree
, msg
);
289 if (msg
== NULL
|| *msg
== '\0')
290 fprintf_filtered (stream
, _("<error reading variable>"));
292 fprintf_filtered (stream
, _("<error reading variable: %s>"), msg
);
294 do_cleanups (cleanup
);
297 gdbpy_print_stack ();
300 /* Helper for gdbpy_apply_val_pretty_printer which calls to_string and
301 formats the result. */
303 static enum string_repr_result
304 print_string_repr (PyObject
*printer
, const char *hint
,
305 struct ui_file
*stream
, int recurse
,
306 const struct value_print_options
*options
,
307 const struct language_defn
*language
,
308 struct gdbarch
*gdbarch
)
310 struct value
*replacement
= NULL
;
311 PyObject
*py_str
= NULL
;
312 enum string_repr_result result
= string_repr_ok
;
314 py_str
= pretty_print_one_value (printer
, &replacement
);
317 struct cleanup
*cleanup
= make_cleanup_py_decref (py_str
);
319 if (py_str
== Py_None
)
320 result
= string_repr_none
;
321 else if (gdbpy_is_lazy_string (py_str
))
326 char *encoding
= NULL
;
327 struct value_print_options local_opts
= *options
;
329 make_cleanup (free_current_contents
, &encoding
);
330 gdbpy_extract_lazy_string (py_str
, &addr
, &type
,
333 local_opts
.addressprint
= 0;
334 val_print_string (type
, encoding
, addr
, (int) length
,
335 stream
, &local_opts
);
341 string
= python_string_to_target_python_string (py_str
);
348 make_cleanup_py_decref (string
);
350 output
= PyBytes_AS_STRING (string
);
351 length
= PyBytes_GET_SIZE (string
);
353 output
= PyString_AsString (string
);
354 length
= PyString_Size (string
);
356 type
= builtin_type (gdbarch
)->builtin_char
;
358 if (hint
&& !strcmp (hint
, "string"))
359 LA_PRINT_STRING (stream
, type
, (gdb_byte
*) output
,
360 length
, NULL
, 0, options
);
362 fputs_filtered (output
, stream
);
366 result
= string_repr_error
;
367 print_stack_unless_memory_error (stream
);
371 do_cleanups (cleanup
);
373 else if (replacement
)
375 struct value_print_options opts
= *options
;
377 opts
.addressprint
= 0;
378 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
382 result
= string_repr_error
;
383 print_stack_unless_memory_error (stream
);
391 py_restore_tstate (void *p
)
393 PyFrameObject
*frame
= p
;
394 PyThreadState
*tstate
= PyThreadState_GET ();
396 tstate
->frame
= frame
;
399 /* Create a dummy PyFrameObject, needed to work around
400 a Python-2.4 bug with generators. */
402 push_dummy_python_frame (void)
404 PyObject
*empty_string
, *null_tuple
, *globals
;
406 PyFrameObject
*frame
;
407 PyThreadState
*tstate
;
409 empty_string
= PyString_FromString ("");
413 null_tuple
= PyTuple_New (0);
416 Py_DECREF (empty_string
);
420 code
= PyCode_New (0, /* argcount */
424 empty_string
, /* code */
425 null_tuple
, /* consts */
426 null_tuple
, /* names */
427 null_tuple
, /* varnames */
428 #if PYTHON_API_VERSION >= 1010
429 null_tuple
, /* freevars */
430 null_tuple
, /* cellvars */
432 empty_string
, /* filename */
433 empty_string
, /* name */
435 empty_string
/* lnotab */
438 Py_DECREF (empty_string
);
439 Py_DECREF (null_tuple
);
444 globals
= PyDict_New ();
451 tstate
= PyThreadState_GET ();
453 frame
= PyFrame_New (tstate
, code
, globals
, NULL
);
461 tstate
->frame
= frame
;
462 make_cleanup (py_restore_tstate
, frame
->f_back
);
463 return (PyObject
*) frame
;
467 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the
468 printer, if any exist. If is_py_none is true, then nothing has
469 been printed by to_string, and format output accordingly. */
471 print_children (PyObject
*printer
, const char *hint
,
472 struct ui_file
*stream
, int recurse
,
473 const struct value_print_options
*options
,
474 const struct language_defn
*language
,
477 int is_map
, is_array
, done_flag
, pretty
;
479 PyObject
*children
, *iter
;
483 struct cleanup
*cleanups
;
485 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
488 /* If we are printing a map or an array, we want some special
490 is_map
= hint
&& ! strcmp (hint
, "map");
491 is_array
= hint
&& ! strcmp (hint
, "array");
493 children
= PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
497 print_stack_unless_memory_error (stream
);
501 cleanups
= make_cleanup_py_decref (children
);
503 iter
= PyObject_GetIter (children
);
506 print_stack_unless_memory_error (stream
);
509 make_cleanup_py_decref (iter
);
511 /* Use the prettyformat_arrays option if we are printing an array,
512 and the pretty option otherwise. */
514 pretty
= options
->prettyformat_arrays
;
517 if (options
->prettyformat
== Val_prettyformat
)
520 pretty
= options
->prettyformat_structs
;
523 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
524 where it insists on having a non-NULL tstate->frame when
525 a generator is called. */
527 frame
= push_dummy_python_frame ();
530 gdbpy_print_stack ();
533 make_cleanup_py_decref (frame
);
537 for (i
= 0; i
< options
->print_max
; ++i
)
539 PyObject
*py_v
, *item
= PyIter_Next (iter
);
541 struct cleanup
*inner_cleanup
;
545 if (PyErr_Occurred ())
546 print_stack_unless_memory_error (stream
);
547 /* Set a flag so we can know whether we printed all the
548 available elements. */
554 if (! PyArg_ParseTuple (item
, "sO", &name
, &py_v
))
556 gdbpy_print_stack ();
560 inner_cleanup
= make_cleanup_py_decref (item
);
562 /* Print initial "{". For other elements, there are three
564 1. Maps. Print a "," after each value element.
565 2. Arrays. Always print a ",".
566 3. Other. Always print a ",". */
570 fputs_filtered ("{", stream
);
572 fputs_filtered (" = {", stream
);
575 else if (! is_map
|| i
% 2 == 0)
576 fputs_filtered (pretty
? "," : ", ", stream
);
578 /* In summary mode, we just want to print "= {...}" if there is
580 if (options
->summary
)
582 /* This increment tricks the post-loop logic to print what
590 if (! is_map
|| i
% 2 == 0)
594 fputs_filtered ("\n", stream
);
595 print_spaces_filtered (2 + 2 * recurse
, stream
);
598 wrap_here (n_spaces (2 + 2 *recurse
));
601 if (is_map
&& i
% 2 == 0)
602 fputs_filtered ("[", stream
);
605 /* We print the index, not whatever the child method
606 returned as the name. */
607 if (options
->print_array_indexes
)
608 fprintf_filtered (stream
, "[%d] = ", i
);
612 fputs_filtered (name
, stream
);
613 fputs_filtered (" = ", stream
);
616 if (gdbpy_is_lazy_string (py_v
))
621 char *encoding
= NULL
;
622 struct value_print_options local_opts
= *options
;
624 make_cleanup (free_current_contents
, &encoding
);
625 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
627 local_opts
.addressprint
= 0;
628 val_print_string (type
, encoding
, addr
, (int) length
, stream
,
631 else if (gdbpy_is_string (py_v
))
635 output
= python_string_to_host_string (py_v
);
637 gdbpy_print_stack ();
640 fputs_filtered (output
, stream
);
646 struct value
*value
= convert_value_from_python (py_v
);
650 gdbpy_print_stack ();
651 error (_("Error while executing Python code."));
654 common_val_print (value
, stream
, recurse
+ 1, options
, language
);
657 if (is_map
&& i
% 2 == 0)
658 fputs_filtered ("] = ", stream
);
660 do_cleanups (inner_cleanup
);
669 fputs_filtered ("\n", stream
);
670 print_spaces_filtered (2 + 2 * recurse
, stream
);
672 fputs_filtered ("...", stream
);
676 fputs_filtered ("\n", stream
);
677 print_spaces_filtered (2 * recurse
, stream
);
679 fputs_filtered ("}", stream
);
683 do_cleanups (cleanups
);
687 gdbpy_apply_val_pretty_printer (const struct extension_language_defn
*extlang
,
688 struct type
*type
, const gdb_byte
*valaddr
,
689 int embedded_offset
, CORE_ADDR address
,
690 struct ui_file
*stream
, int recurse
,
691 const struct value
*val
,
692 const struct value_print_options
*options
,
693 const struct language_defn
*language
)
695 struct gdbarch
*gdbarch
= get_type_arch (type
);
696 PyObject
*printer
= NULL
;
697 PyObject
*val_obj
= NULL
;
700 struct cleanup
*cleanups
;
701 enum ext_lang_rc result
= EXT_LANG_RC_NOP
;
702 enum string_repr_result print_result
;
704 /* No pretty-printer support for unavailable values. */
705 if (!value_bytes_available (val
, embedded_offset
, TYPE_LENGTH (type
)))
706 return EXT_LANG_RC_NOP
;
708 if (!gdb_python_initialized
)
709 return EXT_LANG_RC_NOP
;
711 cleanups
= ensure_python_env (gdbarch
, language
);
713 /* Instantiate the printer. */
715 valaddr
+= embedded_offset
;
716 value
= value_from_contents_and_address (type
, valaddr
,
717 address
+ embedded_offset
);
719 set_value_component_location (value
, val
);
720 /* set_value_component_location resets the address, so we may
721 need to set it again. */
722 if (VALUE_LVAL (value
) != lval_internalvar
723 && VALUE_LVAL (value
) != lval_internalvar_component
724 && VALUE_LVAL (value
) != lval_computed
)
725 set_value_address (value
, address
+ embedded_offset
);
727 val_obj
= value_to_value_object (value
);
730 result
= EXT_LANG_RC_ERROR
;
734 /* Find the constructor. */
735 printer
= find_pretty_printer (val_obj
);
740 result
= EXT_LANG_RC_ERROR
;
744 make_cleanup_py_decref (printer
);
745 if (printer
== Py_None
)
747 result
= EXT_LANG_RC_NOP
;
751 /* If we are printing a map, we want some special formatting. */
752 hint
= gdbpy_get_display_hint (printer
);
753 make_cleanup (free_current_contents
, &hint
);
755 /* Print the section */
756 print_result
= print_string_repr (printer
, hint
, stream
, recurse
,
757 options
, language
, gdbarch
);
758 if (print_result
!= string_repr_error
)
759 print_children (printer
, hint
, stream
, recurse
, options
, language
,
760 print_result
== string_repr_none
);
762 result
= EXT_LANG_RC_OK
;
765 if (PyErr_Occurred ())
766 print_stack_unless_memory_error (stream
);
767 do_cleanups (cleanups
);
772 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
773 print object. It must have a 'to_string' method (but this is
774 checked by varobj, not here) which takes no arguments and
775 returns a string. The printer will return a value and in the case
776 of a Python string being returned, this function will return a
777 PyObject containing the string. For any other type, *REPLACEMENT is
778 set to the replacement value and this function returns NULL. On
779 error, *REPLACEMENT is set to NULL and this function also returns
782 apply_varobj_pretty_printer (PyObject
*printer_obj
,
783 struct value
**replacement
,
784 struct ui_file
*stream
)
786 PyObject
*py_str
= NULL
;
789 py_str
= pretty_print_one_value (printer_obj
, replacement
);
791 if (*replacement
== NULL
&& py_str
== NULL
)
792 print_stack_unless_memory_error (stream
);
797 /* Find a pretty-printer object for the varobj module. Returns a new
798 reference to the object if successful; returns NULL if not. VALUE
799 is the value for which a printer tests to determine if it
800 can pretty-print the value. */
802 gdbpy_get_varobj_pretty_printer (struct value
*value
)
805 PyObject
*pretty_printer
= NULL
;
806 volatile struct gdb_exception except
;
808 TRY_CATCH (except
, RETURN_MASK_ALL
)
810 value
= value_copy (value
);
812 GDB_PY_HANDLE_EXCEPTION (except
);
814 val_obj
= value_to_value_object (value
);
818 pretty_printer
= find_pretty_printer (val_obj
);
820 return pretty_printer
;
823 /* A Python function which wraps find_pretty_printer and instantiates
824 the resulting class. This accepts a Value argument and returns a
825 pretty printer instance, or None. This function is useful as an
826 argument to the MI command -var-set-visualizer. */
828 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
834 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
836 value
= value_object_to_value (val_obj
);
839 PyErr_SetString (PyExc_TypeError
,
840 _("Argument must be a gdb.Value."));
844 cons
= find_pretty_printer (val_obj
);