1 /* Python pretty-printing
3 Copyright (C) 2008-2012 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
);
79 printer
= PyObject_CallFunctionObjArgs (function
, value
, NULL
);
82 else if (printer
!= Py_None
)
91 /* Subroutine of find_pretty_printer to simplify it.
92 Look for a pretty-printer to print VALUE in all objfiles.
93 The result is NULL if there's an error and the search should be terminated.
94 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
95 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
98 find_pretty_printer_from_objfiles (PyObject
*value
)
106 PyObject
*objf
= objfile_to_objfile_object (obj
);
109 /* Ignore the error and continue. */
114 pp_list
= objfpy_get_printers (objf
, NULL
);
115 function
= search_pp_list (pp_list
, value
);
116 Py_XDECREF (pp_list
);
118 /* If there is an error in any objfile list, abort the search and exit. */
122 if (function
!= Py_None
)
125 Py_DECREF (function
);
131 /* Subroutine of find_pretty_printer to simplify it.
132 Look for a pretty-printer to print VALUE in the current program space.
133 The result is NULL if there's an error and the search should be terminated.
134 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
135 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
138 find_pretty_printer_from_progspace (PyObject
*value
)
142 PyObject
*obj
= pspace_to_pspace_object (current_program_space
);
146 pp_list
= pspy_get_printers (obj
, NULL
);
147 function
= search_pp_list (pp_list
, value
);
148 Py_XDECREF (pp_list
);
152 /* Subroutine of find_pretty_printer to simplify it.
153 Look for a pretty-printer to print VALUE in the gdb module.
154 The result is NULL if there's an error and the search should be terminated.
155 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
156 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
159 find_pretty_printer_from_gdb (PyObject
*value
)
164 /* Fetch the global pretty printer list. */
165 if (! PyObject_HasAttrString (gdb_module
, "pretty_printers"))
167 pp_list
= PyObject_GetAttrString (gdb_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 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
);
350 output
= PyString_AsString (string
);
351 length
= PyString_Size (string
);
352 type
= builtin_type (gdbarch
)->builtin_char
;
354 if (hint
&& !strcmp (hint
, "string"))
355 LA_PRINT_STRING (stream
, type
, output
, length
, NULL
,
358 fputs_filtered (output
, stream
);
362 result
= string_repr_error
;
363 print_stack_unless_memory_error (stream
);
367 do_cleanups (cleanup
);
369 else if (replacement
)
371 struct value_print_options opts
= *options
;
373 opts
.addressprint
= 0;
374 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
378 result
= string_repr_error
;
379 print_stack_unless_memory_error (stream
);
386 py_restore_tstate (void *p
)
388 PyFrameObject
*frame
= p
;
389 PyThreadState
*tstate
= PyThreadState_GET ();
391 tstate
->frame
= frame
;
394 /* Create a dummy PyFrameObject, needed to work around
395 a Python-2.4 bug with generators. */
397 push_dummy_python_frame (void)
399 PyObject
*empty_string
, *null_tuple
, *globals
;
401 PyFrameObject
*frame
;
402 PyThreadState
*tstate
;
404 empty_string
= PyString_FromString ("");
408 null_tuple
= PyTuple_New (0);
411 Py_DECREF (empty_string
);
415 code
= PyCode_New (0, /* argcount */
419 empty_string
, /* code */
420 null_tuple
, /* consts */
421 null_tuple
, /* names */
422 null_tuple
, /* varnames */
423 #if PYTHON_API_VERSION >= 1010
424 null_tuple
, /* freevars */
425 null_tuple
, /* cellvars */
427 empty_string
, /* filename */
428 empty_string
, /* name */
430 empty_string
/* lnotab */
433 Py_DECREF (empty_string
);
434 Py_DECREF (null_tuple
);
439 globals
= PyDict_New ();
446 tstate
= PyThreadState_GET ();
448 frame
= PyFrame_New (tstate
, code
, globals
, NULL
);
456 tstate
->frame
= frame
;
457 make_cleanup (py_restore_tstate
, frame
->f_back
);
458 return (PyObject
*) frame
;
461 /* Helper for apply_val_pretty_printer that formats children of the
462 printer, if any exist. If is_py_none is true, then nothing has
463 been printed by to_string, and format output accordingly. */
465 print_children (PyObject
*printer
, const char *hint
,
466 struct ui_file
*stream
, int recurse
,
467 const struct value_print_options
*options
,
468 const struct language_defn
*language
,
471 int is_map
, is_array
, done_flag
, pretty
;
473 PyObject
*children
, *iter
, *frame
;
474 struct cleanup
*cleanups
;
476 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
479 /* If we are printing a map or an array, we want some special
481 is_map
= hint
&& ! strcmp (hint
, "map");
482 is_array
= hint
&& ! strcmp (hint
, "array");
484 children
= PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
488 print_stack_unless_memory_error (stream
);
492 cleanups
= make_cleanup_py_decref (children
);
494 iter
= PyObject_GetIter (children
);
497 print_stack_unless_memory_error (stream
);
500 make_cleanup_py_decref (iter
);
502 /* Use the prettyprint_arrays option if we are printing an array,
503 and the pretty option otherwise. */
505 pretty
= options
->prettyprint_arrays
;
508 if (options
->pretty
== Val_prettyprint
)
511 pretty
= options
->prettyprint_structs
;
514 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
515 where it insists on having a non-NULL tstate->frame when
516 a generator is called. */
517 frame
= push_dummy_python_frame ();
520 gdbpy_print_stack ();
523 make_cleanup_py_decref (frame
);
526 for (i
= 0; i
< options
->print_max
; ++i
)
528 PyObject
*py_v
, *item
= PyIter_Next (iter
);
530 struct cleanup
*inner_cleanup
;
534 if (PyErr_Occurred ())
535 print_stack_unless_memory_error (stream
);
536 /* Set a flag so we can know whether we printed all the
537 available elements. */
543 if (! PyArg_ParseTuple (item
, "sO", &name
, &py_v
))
545 gdbpy_print_stack ();
549 inner_cleanup
= make_cleanup_py_decref (item
);
551 /* Print initial "{". For other elements, there are three
553 1. Maps. Print a "," after each value element.
554 2. Arrays. Always print a ",".
555 3. Other. Always print a ",". */
559 fputs_filtered ("{", stream
);
561 fputs_filtered (" = {", stream
);
564 else if (! is_map
|| i
% 2 == 0)
565 fputs_filtered (pretty
? "," : ", ", stream
);
567 /* In summary mode, we just want to print "= {...}" if there is
569 if (options
->summary
)
571 /* This increment tricks the post-loop logic to print what
579 if (! is_map
|| i
% 2 == 0)
583 fputs_filtered ("\n", stream
);
584 print_spaces_filtered (2 + 2 * recurse
, stream
);
587 wrap_here (n_spaces (2 + 2 *recurse
));
590 if (is_map
&& i
% 2 == 0)
591 fputs_filtered ("[", stream
);
594 /* We print the index, not whatever the child method
595 returned as the name. */
596 if (options
->print_array_indexes
)
597 fprintf_filtered (stream
, "[%d] = ", i
);
601 fputs_filtered (name
, stream
);
602 fputs_filtered (" = ", stream
);
605 if (gdbpy_is_lazy_string (py_v
))
610 char *encoding
= NULL
;
611 struct value_print_options local_opts
= *options
;
613 make_cleanup (free_current_contents
, &encoding
);
614 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
616 local_opts
.addressprint
= 0;
617 val_print_string (type
, encoding
, addr
, (int) length
, stream
,
620 do_cleanups (inner_cleanup
);
622 else if (gdbpy_is_string (py_v
))
626 output
= python_string_to_host_string (py_v
);
628 gdbpy_print_stack ();
631 fputs_filtered (output
, stream
);
637 struct value
*value
= convert_value_from_python (py_v
);
641 gdbpy_print_stack ();
642 error (_("Error while executing Python code."));
645 common_val_print (value
, stream
, recurse
+ 1, options
, language
);
648 if (is_map
&& i
% 2 == 0)
649 fputs_filtered ("] = ", stream
);
651 do_cleanups (inner_cleanup
);
660 fputs_filtered ("\n", stream
);
661 print_spaces_filtered (2 + 2 * recurse
, stream
);
663 fputs_filtered ("...", stream
);
667 fputs_filtered ("\n", stream
);
668 print_spaces_filtered (2 * recurse
, stream
);
670 fputs_filtered ("}", stream
);
674 do_cleanups (cleanups
);
678 apply_val_pretty_printer (struct type
*type
, const gdb_byte
*valaddr
,
679 int embedded_offset
, CORE_ADDR address
,
680 struct ui_file
*stream
, int recurse
,
681 const struct value
*val
,
682 const struct value_print_options
*options
,
683 const struct language_defn
*language
)
685 struct gdbarch
*gdbarch
= get_type_arch (type
);
686 PyObject
*printer
= NULL
;
687 PyObject
*val_obj
= NULL
;
690 struct cleanup
*cleanups
;
692 enum string_repr_result print_result
;
694 /* No pretty-printer support for unavailable values. */
695 if (!value_bytes_available (val
, embedded_offset
, TYPE_LENGTH (type
)))
698 cleanups
= ensure_python_env (gdbarch
, language
);
700 /* Instantiate the printer. */
702 valaddr
+= embedded_offset
;
703 value
= value_from_contents_and_address (type
, valaddr
,
704 address
+ embedded_offset
);
706 set_value_component_location (value
, val
);
707 /* set_value_component_location resets the address, so we may
708 need to set it again. */
709 if (VALUE_LVAL (value
) != lval_internalvar
710 && VALUE_LVAL (value
) != lval_internalvar_component
711 && VALUE_LVAL (value
) != lval_computed
)
712 set_value_address (value
, address
+ embedded_offset
);
714 val_obj
= value_to_value_object (value
);
718 /* Find the constructor. */
719 printer
= find_pretty_printer (val_obj
);
721 make_cleanup_py_decref (printer
);
722 if (! printer
|| printer
== Py_None
)
725 /* If we are printing a map, we want some special formatting. */
726 hint
= gdbpy_get_display_hint (printer
);
727 make_cleanup (free_current_contents
, &hint
);
729 /* Print the section */
730 print_result
= print_string_repr (printer
, hint
, stream
, recurse
,
731 options
, language
, gdbarch
);
732 if (print_result
!= string_repr_error
)
733 print_children (printer
, hint
, stream
, recurse
, options
, language
,
734 print_result
== string_repr_none
);
740 if (PyErr_Occurred ())
741 print_stack_unless_memory_error (stream
);
742 do_cleanups (cleanups
);
747 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
748 print object. It must have a 'to_string' method (but this is
749 checked by varobj, not here) which takes no arguments and
750 returns a string. The printer will return a value and in the case
751 of a Python string being returned, this function will return a
752 PyObject containing the string. For any other type, *REPLACEMENT is
753 set to the replacement value and this function returns NULL. On
754 error, *REPLACEMENT is set to NULL and this function also returns
757 apply_varobj_pretty_printer (PyObject
*printer_obj
,
758 struct value
**replacement
,
759 struct ui_file
*stream
)
761 PyObject
*py_str
= NULL
;
764 py_str
= pretty_print_one_value (printer_obj
, replacement
);
766 if (*replacement
== NULL
&& py_str
== NULL
)
767 print_stack_unless_memory_error (stream
);
772 /* Find a pretty-printer object for the varobj module. Returns a new
773 reference to the object if successful; returns NULL if not. VALUE
774 is the value for which a printer tests to determine if it
775 can pretty-print the value. */
777 gdbpy_get_varobj_pretty_printer (struct value
*value
)
780 PyObject
*pretty_printer
= NULL
;
781 volatile struct gdb_exception except
;
783 TRY_CATCH (except
, RETURN_MASK_ALL
)
785 value
= value_copy (value
);
787 GDB_PY_HANDLE_EXCEPTION (except
);
789 val_obj
= value_to_value_object (value
);
793 pretty_printer
= find_pretty_printer (val_obj
);
795 return pretty_printer
;
798 /* A Python function which wraps find_pretty_printer and instantiates
799 the resulting class. This accepts a Value argument and returns a
800 pretty printer instance, or None. This function is useful as an
801 argument to the MI command -var-set-visualizer. */
803 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
809 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
811 value
= value_object_to_value (val_obj
);
814 PyErr_SetString (PyExc_TypeError
,
815 _("Argument must be a gdb.Value."));
819 cons
= find_pretty_printer (val_obj
);
823 #else /* HAVE_PYTHON */
826 apply_val_pretty_printer (struct type
*type
, const gdb_byte
*valaddr
,
827 int embedded_offset
, CORE_ADDR address
,
828 struct ui_file
*stream
, int recurse
,
829 const struct value
*val
,
830 const struct value_print_options
*options
,
831 const struct language_defn
*language
)
836 #endif /* HAVE_PYTHON */