1 /* Python pretty-printing
3 Copyright (C) 2008-2013 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/>. */
21 #include "exceptions.h"
30 #include "python-internal.h"
32 /* Return type of print_string_repr. */
34 enum string_repr_result
36 /* The string method returned None. */
38 /* The string method had an error. */
44 /* Helper function for find_pretty_printer which iterates over a list,
45 calls each function and inspects output. This will return a
46 printer object if one recognizes VALUE. If no printer is found, it
47 will return None. On error, it will set the Python error and
51 search_pp_list (PyObject
*list
, PyObject
*value
)
53 Py_ssize_t pp_list_size
, list_index
;
54 PyObject
*function
, *printer
= NULL
;
56 pp_list_size
= PyList_Size (list
);
57 for (list_index
= 0; list_index
< pp_list_size
; list_index
++)
59 function
= PyList_GetItem (list
, list_index
);
63 /* Skip if disabled. */
64 if (PyObject_HasAttr (function
, gdbpy_enabled_cst
))
66 PyObject
*attr
= PyObject_GetAttr (function
, gdbpy_enabled_cst
);
71 cmp
= PyObject_IsTrue (attr
);
80 printer
= PyObject_CallFunctionObjArgs (function
, value
, NULL
);
83 else if (printer
!= Py_None
)
92 /* Subroutine of find_pretty_printer to simplify it.
93 Look for a pretty-printer to print VALUE in all objfiles.
94 The result is NULL if there's an error and the search should be terminated.
95 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
96 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
99 find_pretty_printer_from_objfiles (PyObject
*value
)
107 PyObject
*objf
= objfile_to_objfile_object (obj
);
110 /* Ignore the error and continue. */
115 pp_list
= objfpy_get_printers (objf
, NULL
);
116 function
= search_pp_list (pp_list
, value
);
117 Py_XDECREF (pp_list
);
119 /* If there is an error in any objfile list, abort the search and exit. */
123 if (function
!= Py_None
)
126 Py_DECREF (function
);
132 /* Subroutine of find_pretty_printer to simplify it.
133 Look for a pretty-printer to print VALUE in the current program space.
134 The result is NULL if there's an error and the search should be terminated.
135 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
136 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
139 find_pretty_printer_from_progspace (PyObject
*value
)
143 PyObject
*obj
= pspace_to_pspace_object (current_program_space
);
147 pp_list
= pspy_get_printers (obj
, NULL
);
148 function
= search_pp_list (pp_list
, value
);
149 Py_XDECREF (pp_list
);
153 /* Subroutine of find_pretty_printer to simplify it.
154 Look for a pretty-printer to print VALUE in the gdb module.
155 The result is NULL if there's an error and the search should be terminated.
156 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
157 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
160 find_pretty_printer_from_gdb (PyObject
*value
)
165 /* Fetch the global pretty printer list. */
166 if (gdb_python_module
== NULL
167 || ! PyObject_HasAttrString (gdb_python_module
, "pretty_printers"))
169 pp_list
= PyObject_GetAttrString (gdb_python_module
, "pretty_printers");
170 if (pp_list
== NULL
|| ! PyList_Check (pp_list
))
172 Py_XDECREF (pp_list
);
176 function
= search_pp_list (pp_list
, value
);
177 Py_XDECREF (pp_list
);
181 /* Find the pretty-printing constructor function for VALUE. If no
182 pretty-printer exists, return None. If one exists, return a new
183 reference. On error, set the Python error and return NULL. */
186 find_pretty_printer (PyObject
*value
)
190 /* Look at the pretty-printer list for each objfile
191 in the current program-space. */
192 function
= find_pretty_printer_from_objfiles (value
);
193 if (function
== NULL
|| function
!= Py_None
)
195 Py_DECREF (function
);
197 /* Look at the pretty-printer list for the current program-space. */
198 function
= find_pretty_printer_from_progspace (value
);
199 if (function
== NULL
|| function
!= Py_None
)
201 Py_DECREF (function
);
203 /* Look at the pretty-printer list in the gdb module. */
204 function
= find_pretty_printer_from_gdb (value
);
208 /* Pretty-print a single value, via the printer object PRINTER.
209 If the function returns a string, a PyObject containing the string
210 is returned. If the function returns Py_NONE that means the pretty
211 printer returned the Python None as a value. Otherwise, if the
212 function returns a value, *OUT_VALUE is set to the value, and NULL
213 is returned. On error, *OUT_VALUE is set to NULL, NULL is
214 returned, with a python exception set. */
217 pretty_print_one_value (PyObject
*printer
, struct value
**out_value
)
219 volatile struct gdb_exception except
;
220 PyObject
*result
= NULL
;
223 TRY_CATCH (except
, RETURN_MASK_ALL
)
225 result
= PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
, NULL
);
228 if (! gdbpy_is_string (result
) && ! gdbpy_is_lazy_string (result
)
229 && result
!= Py_None
)
231 *out_value
= convert_value_from_python (result
);
232 if (PyErr_Occurred ())
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. */
248 gdbpy_get_display_hint (PyObject
*printer
)
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
;
284 PyErr_Fetch (&type
, &value
, &trace
);
285 cleanup
= make_cleanup_py_decref (type
);
286 make_cleanup_py_decref (value
);
287 make_cleanup_py_decref (trace
);
289 msg
= gdbpy_exception_to_string (type
, value
);
290 make_cleanup (xfree
, msg
);
292 if (msg
== NULL
|| *msg
== '\0')
293 fprintf_filtered (stream
, _("<error reading variable>"));
295 fprintf_filtered (stream
, _("<error reading variable: %s>"), msg
);
297 do_cleanups (cleanup
);
300 gdbpy_print_stack ();
303 /* Helper for 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
= 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 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 (! PyArg_ParseTuple (item
, "sO", &name
, &py_v
))
559 gdbpy_print_stack ();
563 inner_cleanup
= make_cleanup_py_decref (item
);
565 /* Print initial "{". For other elements, there are three
567 1. Maps. Print a "," after each value element.
568 2. Arrays. Always print a ",".
569 3. Other. Always print a ",". */
573 fputs_filtered ("{", stream
);
575 fputs_filtered (" = {", stream
);
578 else if (! is_map
|| i
% 2 == 0)
579 fputs_filtered (pretty
? "," : ", ", stream
);
581 /* In summary mode, we just want to print "= {...}" if there is
583 if (options
->summary
)
585 /* This increment tricks the post-loop logic to print what
593 if (! is_map
|| i
% 2 == 0)
597 fputs_filtered ("\n", stream
);
598 print_spaces_filtered (2 + 2 * recurse
, stream
);
601 wrap_here (n_spaces (2 + 2 *recurse
));
604 if (is_map
&& i
% 2 == 0)
605 fputs_filtered ("[", stream
);
608 /* We print the index, not whatever the child method
609 returned as the name. */
610 if (options
->print_array_indexes
)
611 fprintf_filtered (stream
, "[%d] = ", i
);
615 fputs_filtered (name
, stream
);
616 fputs_filtered (" = ", stream
);
619 if (gdbpy_is_lazy_string (py_v
))
624 char *encoding
= NULL
;
625 struct value_print_options local_opts
= *options
;
627 make_cleanup (free_current_contents
, &encoding
);
628 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
630 local_opts
.addressprint
= 0;
631 val_print_string (type
, encoding
, addr
, (int) length
, stream
,
634 else if (gdbpy_is_string (py_v
))
638 output
= python_string_to_host_string (py_v
);
640 gdbpy_print_stack ();
643 fputs_filtered (output
, stream
);
649 struct value
*value
= convert_value_from_python (py_v
);
653 gdbpy_print_stack ();
654 error (_("Error while executing Python code."));
657 common_val_print (value
, stream
, recurse
+ 1, options
, language
);
660 if (is_map
&& i
% 2 == 0)
661 fputs_filtered ("] = ", stream
);
663 do_cleanups (inner_cleanup
);
672 fputs_filtered ("\n", stream
);
673 print_spaces_filtered (2 + 2 * recurse
, stream
);
675 fputs_filtered ("...", stream
);
679 fputs_filtered ("\n", stream
);
680 print_spaces_filtered (2 * recurse
, stream
);
682 fputs_filtered ("}", stream
);
686 do_cleanups (cleanups
);
690 apply_val_pretty_printer (struct type
*type
, const gdb_byte
*valaddr
,
691 int embedded_offset
, CORE_ADDR address
,
692 struct ui_file
*stream
, int recurse
,
693 const struct value
*val
,
694 const struct value_print_options
*options
,
695 const struct language_defn
*language
)
697 struct gdbarch
*gdbarch
= get_type_arch (type
);
698 PyObject
*printer
= NULL
;
699 PyObject
*val_obj
= NULL
;
702 struct cleanup
*cleanups
;
704 enum string_repr_result print_result
;
706 /* No pretty-printer support for unavailable values. */
707 if (!value_bytes_available (val
, embedded_offset
, TYPE_LENGTH (type
)))
710 if (!gdb_python_initialized
)
713 cleanups
= ensure_python_env (gdbarch
, language
);
715 /* Instantiate the printer. */
717 valaddr
+= embedded_offset
;
718 value
= value_from_contents_and_address (type
, valaddr
,
719 address
+ embedded_offset
);
721 set_value_component_location (value
, val
);
722 /* set_value_component_location resets the address, so we may
723 need to set it again. */
724 if (VALUE_LVAL (value
) != lval_internalvar
725 && VALUE_LVAL (value
) != lval_internalvar_component
726 && VALUE_LVAL (value
) != lval_computed
)
727 set_value_address (value
, address
+ embedded_offset
);
729 val_obj
= value_to_value_object (value
);
733 /* Find the constructor. */
734 printer
= find_pretty_printer (val_obj
);
740 make_cleanup_py_decref (printer
);
741 if (printer
== Py_None
)
744 /* If we are printing a map, we want some special formatting. */
745 hint
= gdbpy_get_display_hint (printer
);
746 make_cleanup (free_current_contents
, &hint
);
748 /* Print the section */
749 print_result
= print_string_repr (printer
, hint
, stream
, recurse
,
750 options
, language
, gdbarch
);
751 if (print_result
!= string_repr_error
)
752 print_children (printer
, hint
, stream
, recurse
, options
, language
,
753 print_result
== string_repr_none
);
759 if (PyErr_Occurred ())
760 print_stack_unless_memory_error (stream
);
761 do_cleanups (cleanups
);
766 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
767 print object. It must have a 'to_string' method (but this is
768 checked by varobj, not here) which takes no arguments and
769 returns a string. The printer will return a value and in the case
770 of a Python string being returned, this function will return a
771 PyObject containing the string. For any other type, *REPLACEMENT is
772 set to the replacement value and this function returns NULL. On
773 error, *REPLACEMENT is set to NULL and this function also returns
776 apply_varobj_pretty_printer (PyObject
*printer_obj
,
777 struct value
**replacement
,
778 struct ui_file
*stream
)
780 PyObject
*py_str
= NULL
;
783 py_str
= pretty_print_one_value (printer_obj
, replacement
);
785 if (*replacement
== NULL
&& py_str
== NULL
)
786 print_stack_unless_memory_error (stream
);
791 /* Find a pretty-printer object for the varobj module. Returns a new
792 reference to the object if successful; returns NULL if not. VALUE
793 is the value for which a printer tests to determine if it
794 can pretty-print the value. */
796 gdbpy_get_varobj_pretty_printer (struct value
*value
)
799 PyObject
*pretty_printer
= NULL
;
800 volatile struct gdb_exception except
;
802 TRY_CATCH (except
, RETURN_MASK_ALL
)
804 value
= value_copy (value
);
806 GDB_PY_HANDLE_EXCEPTION (except
);
808 val_obj
= value_to_value_object (value
);
812 pretty_printer
= find_pretty_printer (val_obj
);
814 return pretty_printer
;
817 /* A Python function which wraps find_pretty_printer and instantiates
818 the resulting class. This accepts a Value argument and returns a
819 pretty printer instance, or None. This function is useful as an
820 argument to the MI command -var-set-visualizer. */
822 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
828 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
830 value
= value_object_to_value (val_obj
);
833 PyErr_SetString (PyExc_TypeError
,
834 _("Argument must be a gdb.Value."));
838 cons
= find_pretty_printer (val_obj
);
842 #else /* HAVE_PYTHON */
845 apply_val_pretty_printer (struct type
*type
, const gdb_byte
*valaddr
,
846 int embedded_offset
, CORE_ADDR address
,
847 struct ui_file
*stream
, int recurse
,
848 const struct value
*val
,
849 const struct value_print_options
*options
,
850 const struct language_defn
*language
)
855 #endif /* HAVE_PYTHON */