1 /* Python pretty-printing
3 Copyright (C) 2008-2014 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"
26 #include "extension-priv.h"
28 #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
;
52 PyObject
*function
, *printer
= NULL
;
54 pp_list_size
= PyList_Size (list
);
55 for (list_index
= 0; list_index
< pp_list_size
; list_index
++)
57 function
= PyList_GetItem (list
, list_index
);
61 /* Skip if disabled. */
62 if (PyObject_HasAttr (function
, gdbpy_enabled_cst
))
64 PyObject
*attr
= PyObject_GetAttr (function
, gdbpy_enabled_cst
);
69 cmp
= PyObject_IsTrue (attr
);
78 printer
= PyObject_CallFunctionObjArgs (function
, value
, NULL
);
81 else if (printer
!= Py_None
)
90 /* Subroutine of find_pretty_printer to simplify it.
91 Look for a pretty-printer to print VALUE in all objfiles.
92 The result is NULL if there's an error and the search should be terminated.
93 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
94 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
97 find_pretty_printer_from_objfiles (PyObject
*value
)
105 PyObject
*objf
= objfile_to_objfile_object (obj
);
108 /* Ignore the error and continue. */
113 pp_list
= objfpy_get_printers (objf
, NULL
);
114 function
= search_pp_list (pp_list
, value
);
115 Py_XDECREF (pp_list
);
117 /* If there is an error in any objfile list, abort the search and exit. */
121 if (function
!= Py_None
)
124 Py_DECREF (function
);
130 /* Subroutine of find_pretty_printer to simplify it.
131 Look for a pretty-printer to print VALUE in the current program space.
132 The result is NULL if there's an error and the search should be terminated.
133 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
134 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
137 find_pretty_printer_from_progspace (PyObject
*value
)
141 PyObject
*obj
= pspace_to_pspace_object (current_program_space
);
145 pp_list
= pspy_get_printers (obj
, NULL
);
146 function
= search_pp_list (pp_list
, value
);
147 Py_XDECREF (pp_list
);
151 /* Subroutine of find_pretty_printer to simplify it.
152 Look for a pretty-printer to print VALUE in the gdb module.
153 The result is NULL if there's an error and the search should be terminated.
154 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
155 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
158 find_pretty_printer_from_gdb (PyObject
*value
)
163 /* Fetch the global pretty printer list. */
164 if (gdb_python_module
== NULL
165 || ! PyObject_HasAttrString (gdb_python_module
, "pretty_printers"))
167 pp_list
= PyObject_GetAttrString (gdb_python_module
, "pretty_printers");
168 if (pp_list
== NULL
|| ! PyList_Check (pp_list
))
170 Py_XDECREF (pp_list
);
174 function
= search_pp_list (pp_list
, value
);
175 Py_XDECREF (pp_list
);
179 /* Find the pretty-printing constructor function for VALUE. If no
180 pretty-printer exists, return None. If one exists, return a new
181 reference. On error, set the Python error and return NULL. */
184 find_pretty_printer (PyObject
*value
)
188 /* Look at the pretty-printer list for each objfile
189 in the current program-space. */
190 function
= find_pretty_printer_from_objfiles (value
);
191 if (function
== NULL
|| function
!= Py_None
)
193 Py_DECREF (function
);
195 /* Look at the pretty-printer list for the current program-space. */
196 function
= find_pretty_printer_from_progspace (value
);
197 if (function
== NULL
|| function
!= Py_None
)
199 Py_DECREF (function
);
201 /* Look at the pretty-printer list in the gdb module. */
202 function
= find_pretty_printer_from_gdb (value
);
206 /* Pretty-print a single value, via the printer object PRINTER.
207 If the function returns a string, a PyObject containing the string
208 is returned. If the function returns Py_NONE that means the pretty
209 printer returned the Python None as a value. Otherwise, if the
210 function returns a value, *OUT_VALUE is set to the value, and NULL
211 is returned. On error, *OUT_VALUE is set to NULL, NULL is
212 returned, with a python exception set. */
215 pretty_print_one_value (PyObject
*printer
, struct value
**out_value
)
217 volatile struct gdb_exception except
;
218 PyObject
*result
= NULL
;
221 TRY_CATCH (except
, RETURN_MASK_ALL
)
223 result
= PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
, NULL
);
226 if (! gdbpy_is_string (result
) && ! gdbpy_is_lazy_string (result
)
227 && result
!= Py_None
)
229 *out_value
= convert_value_from_python (result
);
230 if (PyErr_Occurred ())
241 /* Return the display hint for the object printer, PRINTER. Return
242 NULL if there is no display_hint method, or if the method did not
243 return a string. On error, print stack trace and return NULL. On
244 success, return an xmalloc()d string. */
246 gdbpy_get_display_hint (PyObject
*printer
)
251 if (! PyObject_HasAttr (printer
, gdbpy_display_hint_cst
))
254 hint
= PyObject_CallMethodObjArgs (printer
, gdbpy_display_hint_cst
, NULL
);
257 if (gdbpy_is_string (hint
))
259 result
= python_string_to_host_string (hint
);
261 gdbpy_print_stack ();
266 gdbpy_print_stack ();
271 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
274 print_stack_unless_memory_error (struct ui_file
*stream
)
276 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error
))
278 struct cleanup
*cleanup
;
279 PyObject
*type
, *value
, *trace
;
282 PyErr_Fetch (&type
, &value
, &trace
);
283 cleanup
= make_cleanup_py_decref (type
);
284 make_cleanup_py_decref (value
);
285 make_cleanup_py_decref (trace
);
287 msg
= gdbpy_exception_to_string (type
, value
);
288 make_cleanup (xfree
, msg
);
290 if (msg
== NULL
|| *msg
== '\0')
291 fprintf_filtered (stream
, _("<error reading variable>"));
293 fprintf_filtered (stream
, _("<error reading variable: %s>"), msg
);
295 do_cleanups (cleanup
);
298 gdbpy_print_stack ();
301 /* Helper for gdbpy_apply_val_pretty_printer which calls to_string and
302 formats the result. */
304 static enum string_repr_result
305 print_string_repr (PyObject
*printer
, const char *hint
,
306 struct ui_file
*stream
, int recurse
,
307 const struct value_print_options
*options
,
308 const struct language_defn
*language
,
309 struct gdbarch
*gdbarch
)
311 struct value
*replacement
= NULL
;
312 PyObject
*py_str
= NULL
;
313 enum string_repr_result result
= string_repr_ok
;
315 py_str
= pretty_print_one_value (printer
, &replacement
);
318 struct cleanup
*cleanup
= make_cleanup_py_decref (py_str
);
320 if (py_str
== Py_None
)
321 result
= string_repr_none
;
322 else if (gdbpy_is_lazy_string (py_str
))
327 char *encoding
= NULL
;
328 struct value_print_options local_opts
= *options
;
330 make_cleanup (free_current_contents
, &encoding
);
331 gdbpy_extract_lazy_string (py_str
, &addr
, &type
,
334 local_opts
.addressprint
= 0;
335 val_print_string (type
, encoding
, addr
, (int) length
,
336 stream
, &local_opts
);
342 string
= python_string_to_target_python_string (py_str
);
349 make_cleanup_py_decref (string
);
351 output
= PyBytes_AS_STRING (string
);
352 length
= PyBytes_GET_SIZE (string
);
354 output
= PyString_AsString (string
);
355 length
= PyString_Size (string
);
357 type
= builtin_type (gdbarch
)->builtin_char
;
359 if (hint
&& !strcmp (hint
, "string"))
360 LA_PRINT_STRING (stream
, type
, (gdb_byte
*) output
,
361 length
, NULL
, 0, options
);
363 fputs_filtered (output
, stream
);
367 result
= string_repr_error
;
368 print_stack_unless_memory_error (stream
);
372 do_cleanups (cleanup
);
374 else if (replacement
)
376 struct value_print_options opts
= *options
;
378 opts
.addressprint
= 0;
379 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
383 result
= string_repr_error
;
384 print_stack_unless_memory_error (stream
);
392 py_restore_tstate (void *p
)
394 PyFrameObject
*frame
= p
;
395 PyThreadState
*tstate
= PyThreadState_GET ();
397 tstate
->frame
= frame
;
400 /* Create a dummy PyFrameObject, needed to work around
401 a Python-2.4 bug with generators. */
403 push_dummy_python_frame (void)
405 PyObject
*empty_string
, *null_tuple
, *globals
;
407 PyFrameObject
*frame
;
408 PyThreadState
*tstate
;
410 empty_string
= PyString_FromString ("");
414 null_tuple
= PyTuple_New (0);
417 Py_DECREF (empty_string
);
421 code
= PyCode_New (0, /* argcount */
425 empty_string
, /* code */
426 null_tuple
, /* consts */
427 null_tuple
, /* names */
428 null_tuple
, /* varnames */
429 #if PYTHON_API_VERSION >= 1010
430 null_tuple
, /* freevars */
431 null_tuple
, /* cellvars */
433 empty_string
, /* filename */
434 empty_string
, /* name */
436 empty_string
/* lnotab */
439 Py_DECREF (empty_string
);
440 Py_DECREF (null_tuple
);
445 globals
= PyDict_New ();
452 tstate
= PyThreadState_GET ();
454 frame
= PyFrame_New (tstate
, code
, globals
, NULL
);
462 tstate
->frame
= frame
;
463 make_cleanup (py_restore_tstate
, frame
->f_back
);
464 return (PyObject
*) frame
;
468 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the
469 printer, if any exist. If is_py_none is true, then nothing has
470 been printed by to_string, and format output accordingly. */
472 print_children (PyObject
*printer
, const char *hint
,
473 struct ui_file
*stream
, int recurse
,
474 const struct value_print_options
*options
,
475 const struct language_defn
*language
,
478 int is_map
, is_array
, done_flag
, pretty
;
480 PyObject
*children
, *iter
;
484 struct cleanup
*cleanups
;
486 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
489 /* If we are printing a map or an array, we want some special
491 is_map
= hint
&& ! strcmp (hint
, "map");
492 is_array
= hint
&& ! strcmp (hint
, "array");
494 children
= PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
498 print_stack_unless_memory_error (stream
);
502 cleanups
= make_cleanup_py_decref (children
);
504 iter
= PyObject_GetIter (children
);
507 print_stack_unless_memory_error (stream
);
510 make_cleanup_py_decref (iter
);
512 /* Use the prettyformat_arrays option if we are printing an array,
513 and the pretty option otherwise. */
515 pretty
= options
->prettyformat_arrays
;
518 if (options
->prettyformat
== Val_prettyformat
)
521 pretty
= options
->prettyformat_structs
;
524 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
525 where it insists on having a non-NULL tstate->frame when
526 a generator is called. */
528 frame
= push_dummy_python_frame ();
531 gdbpy_print_stack ();
534 make_cleanup_py_decref (frame
);
538 for (i
= 0; i
< options
->print_max
; ++i
)
540 PyObject
*py_v
, *item
= PyIter_Next (iter
);
542 struct cleanup
*inner_cleanup
;
546 if (PyErr_Occurred ())
547 print_stack_unless_memory_error (stream
);
548 /* Set a flag so we can know whether we printed all the
549 available elements. */
555 if (! PyArg_ParseTuple (item
, "sO", &name
, &py_v
))
557 gdbpy_print_stack ();
561 inner_cleanup
= make_cleanup_py_decref (item
);
563 /* Print initial "{". For other elements, there are three
565 1. Maps. Print a "," after each value element.
566 2. Arrays. Always print a ",".
567 3. Other. Always print a ",". */
571 fputs_filtered ("{", stream
);
573 fputs_filtered (" = {", stream
);
576 else if (! is_map
|| i
% 2 == 0)
577 fputs_filtered (pretty
? "," : ", ", stream
);
579 /* In summary mode, we just want to print "= {...}" if there is
581 if (options
->summary
)
583 /* This increment tricks the post-loop logic to print what
591 if (! is_map
|| i
% 2 == 0)
595 fputs_filtered ("\n", stream
);
596 print_spaces_filtered (2 + 2 * recurse
, stream
);
599 wrap_here (n_spaces (2 + 2 *recurse
));
602 if (is_map
&& i
% 2 == 0)
603 fputs_filtered ("[", stream
);
606 /* We print the index, not whatever the child method
607 returned as the name. */
608 if (options
->print_array_indexes
)
609 fprintf_filtered (stream
, "[%d] = ", i
);
613 fputs_filtered (name
, stream
);
614 fputs_filtered (" = ", stream
);
617 if (gdbpy_is_lazy_string (py_v
))
622 char *encoding
= NULL
;
623 struct value_print_options local_opts
= *options
;
625 make_cleanup (free_current_contents
, &encoding
);
626 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
628 local_opts
.addressprint
= 0;
629 val_print_string (type
, encoding
, addr
, (int) length
, stream
,
632 else if (gdbpy_is_string (py_v
))
636 output
= python_string_to_host_string (py_v
);
638 gdbpy_print_stack ();
641 fputs_filtered (output
, stream
);
647 struct value
*value
= convert_value_from_python (py_v
);
651 gdbpy_print_stack ();
652 error (_("Error while executing Python code."));
655 common_val_print (value
, stream
, recurse
+ 1, options
, language
);
658 if (is_map
&& i
% 2 == 0)
659 fputs_filtered ("] = ", stream
);
661 do_cleanups (inner_cleanup
);
670 fputs_filtered ("\n", stream
);
671 print_spaces_filtered (2 + 2 * recurse
, stream
);
673 fputs_filtered ("...", stream
);
677 fputs_filtered ("\n", stream
);
678 print_spaces_filtered (2 * recurse
, stream
);
680 fputs_filtered ("}", stream
);
684 do_cleanups (cleanups
);
688 gdbpy_apply_val_pretty_printer (const struct extension_language_defn
*extlang
,
689 struct type
*type
, const gdb_byte
*valaddr
,
690 int embedded_offset
, CORE_ADDR address
,
691 struct ui_file
*stream
, int recurse
,
692 const struct value
*val
,
693 const struct value_print_options
*options
,
694 const struct language_defn
*language
)
696 struct gdbarch
*gdbarch
= get_type_arch (type
);
697 PyObject
*printer
= NULL
;
698 PyObject
*val_obj
= NULL
;
701 struct cleanup
*cleanups
;
702 enum ext_lang_rc result
= EXT_LANG_RC_NOP
;
703 enum string_repr_result print_result
;
705 /* No pretty-printer support for unavailable values. */
706 if (!value_bytes_available (val
, embedded_offset
, TYPE_LENGTH (type
)))
707 return EXT_LANG_RC_NOP
;
709 if (!gdb_python_initialized
)
710 return EXT_LANG_RC_NOP
;
712 cleanups
= ensure_python_env (gdbarch
, language
);
714 /* Instantiate the printer. */
716 valaddr
+= embedded_offset
;
717 value
= value_from_contents_and_address (type
, valaddr
,
718 address
+ embedded_offset
);
720 set_value_component_location (value
, val
);
721 /* set_value_component_location resets the address, so we may
722 need to set it again. */
723 if (VALUE_LVAL (value
) != lval_internalvar
724 && VALUE_LVAL (value
) != lval_internalvar_component
725 && VALUE_LVAL (value
) != lval_computed
)
726 set_value_address (value
, address
+ embedded_offset
);
728 val_obj
= value_to_value_object (value
);
731 result
= EXT_LANG_RC_ERROR
;
735 /* Find the constructor. */
736 printer
= find_pretty_printer (val_obj
);
741 result
= EXT_LANG_RC_ERROR
;
745 make_cleanup_py_decref (printer
);
746 if (printer
== Py_None
)
748 result
= EXT_LANG_RC_NOP
;
752 /* If we are printing a map, we want some special formatting. */
753 hint
= gdbpy_get_display_hint (printer
);
754 make_cleanup (free_current_contents
, &hint
);
756 /* Print the section */
757 print_result
= print_string_repr (printer
, hint
, stream
, recurse
,
758 options
, language
, gdbarch
);
759 if (print_result
!= string_repr_error
)
760 print_children (printer
, hint
, stream
, recurse
, options
, language
,
761 print_result
== string_repr_none
);
763 result
= EXT_LANG_RC_OK
;
766 if (PyErr_Occurred ())
767 print_stack_unless_memory_error (stream
);
768 do_cleanups (cleanups
);
773 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
774 print object. It must have a 'to_string' method (but this is
775 checked by varobj, not here) which takes no arguments and
776 returns a string. The printer will return a value and in the case
777 of a Python string being returned, this function will return a
778 PyObject containing the string. For any other type, *REPLACEMENT is
779 set to the replacement value and this function returns NULL. On
780 error, *REPLACEMENT is set to NULL and this function also returns
783 apply_varobj_pretty_printer (PyObject
*printer_obj
,
784 struct value
**replacement
,
785 struct ui_file
*stream
)
787 PyObject
*py_str
= NULL
;
790 py_str
= pretty_print_one_value (printer_obj
, replacement
);
792 if (*replacement
== NULL
&& py_str
== NULL
)
793 print_stack_unless_memory_error (stream
);
798 /* Find a pretty-printer object for the varobj module. Returns a new
799 reference to the object if successful; returns NULL if not. VALUE
800 is the value for which a printer tests to determine if it
801 can pretty-print the value. */
803 gdbpy_get_varobj_pretty_printer (struct value
*value
)
806 PyObject
*pretty_printer
= NULL
;
807 volatile struct gdb_exception except
;
809 TRY_CATCH (except
, RETURN_MASK_ALL
)
811 value
= value_copy (value
);
813 GDB_PY_HANDLE_EXCEPTION (except
);
815 val_obj
= value_to_value_object (value
);
819 pretty_printer
= find_pretty_printer (val_obj
);
821 return pretty_printer
;
824 /* A Python function which wraps find_pretty_printer and instantiates
825 the resulting class. This accepts a Value argument and returns a
826 pretty printer instance, or None. This function is useful as an
827 argument to the MI command -var-set-visualizer. */
829 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
835 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
837 value
= value_object_to_value (val_obj
);
840 PyErr_SetString (PyExc_TypeError
,
841 _("Argument must be a gdb.Value."));
845 cons
= find_pretty_printer (val_obj
);