1 /* Python pretty-printing
3 Copyright (C) 2008, 2009, 2010 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 /* Helper function for find_pretty_printer which iterates over a list,
33 calls each function and inspects output. This will return a
34 printer object if one recognizes VALUE. If no printer is found, it
35 will return None. On error, it will set the Python error and
39 search_pp_list (PyObject
*list
, PyObject
*value
)
41 Py_ssize_t pp_list_size
, list_index
;
42 PyObject
*function
, *printer
= NULL
;
44 pp_list_size
= PyList_Size (list
);
45 for (list_index
= 0; list_index
< pp_list_size
; list_index
++)
47 function
= PyList_GetItem (list
, list_index
);
51 /* Skip if disabled. */
52 if (PyObject_HasAttr (function
, gdbpy_enabled_cst
)
53 && ! PyObject_IsTrue (PyObject_GetAttr (function
, gdbpy_enabled_cst
)))
56 printer
= PyObject_CallFunctionObjArgs (function
, value
, NULL
);
59 else if (printer
!= Py_None
)
68 /* Subroutine of find_pretty_printer to simplify it.
69 Look for a pretty-printer to print VALUE in all objfiles.
70 The result is NULL if there's an error and the search should be terminated.
71 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
72 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
75 find_pretty_printer_from_objfiles (PyObject
*value
)
83 PyObject
*objf
= objfile_to_objfile_object (obj
);
86 /* Ignore the error and continue. */
91 pp_list
= objfpy_get_printers (objf
, NULL
);
92 function
= search_pp_list (pp_list
, value
);
95 /* If there is an error in any objfile list, abort the search and exit. */
99 if (function
!= Py_None
)
102 Py_DECREF (function
);
108 /* Subroutine of find_pretty_printer to simplify it.
109 Look for a pretty-printer to print VALUE in the current program space.
110 The result is NULL if there's an error and the search should be terminated.
111 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
112 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
115 find_pretty_printer_from_progspace (PyObject
*value
)
119 PyObject
*obj
= pspace_to_pspace_object (current_program_space
);
123 pp_list
= pspy_get_printers (obj
, NULL
);
124 function
= search_pp_list (pp_list
, value
);
125 Py_XDECREF (pp_list
);
129 /* Subroutine of find_pretty_printer to simplify it.
130 Look for a pretty-printer to print VALUE in the gdb module.
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_gdb (PyObject
*value
)
141 /* Fetch the global pretty printer dictionary. */
142 if (! PyObject_HasAttrString (gdb_module
, "pretty_printers"))
144 pp_list
= PyObject_GetAttrString (gdb_module
, "pretty_printers");
145 if (pp_list
== NULL
|| ! PyList_Check (pp_list
))
147 Py_XDECREF (pp_list
);
151 function
= search_pp_list (pp_list
, value
);
152 Py_XDECREF (pp_list
);
156 /* Find the pretty-printing constructor function for VALUE. If no
157 pretty-printer exists, return None. If one exists, return a new
158 reference. On error, set the Python error and return NULL. */
161 find_pretty_printer (PyObject
*value
)
165 /* Look at the pretty-printer dictionary for each objfile
166 in the current program-space. */
167 function
= find_pretty_printer_from_objfiles (value
);
168 if (function
== NULL
|| function
!= Py_None
)
170 Py_DECREF (function
);
172 /* Look at the pretty-printer dictionary for the current program-space. */
173 function
= find_pretty_printer_from_progspace (value
);
174 if (function
== NULL
|| function
!= Py_None
)
176 Py_DECREF (function
);
178 /* Look at the pretty-printer dictionary in the gdb module. */
179 function
= find_pretty_printer_from_gdb (value
);
183 /* Pretty-print a single value, via the printer object PRINTER.
184 If the function returns a string, a PyObject containing the string
185 is returned. If the function returns Py_NONE that means the pretty
186 printer returned the Python None as a value. Otherwise, if the
187 function returns a value, *OUT_VALUE is set to the value, and NULL
188 is returned. On error, *OUT_VALUE is set to NULL, and NULL is
192 pretty_print_one_value (PyObject
*printer
, struct value
**out_value
)
194 volatile struct gdb_exception except
;
195 PyObject
*result
= NULL
;
198 TRY_CATCH (except
, RETURN_MASK_ALL
)
200 result
= PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
, NULL
);
203 if (! gdbpy_is_string (result
) && ! gdbpy_is_lazy_string (result
)
204 && result
!= Py_None
)
206 *out_value
= convert_value_from_python (result
);
207 if (PyErr_Occurred ())
218 /* Return the display hint for the object printer, PRINTER. Return
219 NULL if there is no display_hint method, or if the method did not
220 return a string. On error, print stack trace and return NULL. On
221 success, return an xmalloc()d string. */
223 gdbpy_get_display_hint (PyObject
*printer
)
228 if (! PyObject_HasAttr (printer
, gdbpy_display_hint_cst
))
231 hint
= PyObject_CallMethodObjArgs (printer
, gdbpy_display_hint_cst
, NULL
);
232 if (gdbpy_is_string (hint
))
233 result
= python_string_to_host_string (hint
);
237 gdbpy_print_stack ();
242 /* Helper for apply_val_pretty_printer which calls to_string and
243 formats the result. If the value returnd is Py_None, nothing is
244 printed and the function returns a 1; in all other cases data is
245 printed as given by the pretty printer and the function returns 0.
248 print_string_repr (PyObject
*printer
, const char *hint
,
249 struct ui_file
*stream
, int recurse
,
250 const struct value_print_options
*options
,
251 const struct language_defn
*language
,
252 struct gdbarch
*gdbarch
)
254 struct value
*replacement
= NULL
;
255 PyObject
*py_str
= NULL
;
258 py_str
= pretty_print_one_value (printer
, &replacement
);
261 if (py_str
== Py_None
)
265 gdb_byte
*output
= NULL
;
268 char *encoding
= NULL
;
269 PyObject
*string
= NULL
;
272 is_lazy
= gdbpy_is_lazy_string (py_str
);
274 output
= gdbpy_extract_lazy_string (py_str
, &type
, &length
, &encoding
);
277 string
= python_string_to_target_python_string (py_str
);
280 output
= PyString_AsString (string
);
281 length
= PyString_Size (string
);
282 type
= builtin_type (gdbarch
)->builtin_char
;
285 gdbpy_print_stack ();
291 if (is_lazy
|| (hint
&& !strcmp (hint
, "string")))
292 LA_PRINT_STRING (stream
, type
, output
, length
, encoding
,
295 fputs_filtered (output
, stream
);
298 gdbpy_print_stack ();
309 else if (replacement
)
311 struct value_print_options opts
= *options
;
313 opts
.addressprint
= 0;
314 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
317 gdbpy_print_stack ();
323 py_restore_tstate (void *p
)
325 PyFrameObject
*frame
= p
;
326 PyThreadState
*tstate
= PyThreadState_GET ();
328 tstate
->frame
= frame
;
331 /* Create a dummy PyFrameObject, needed to work around
332 a Python-2.4 bug with generators. */
334 push_dummy_python_frame ()
336 PyObject
*empty_string
, *null_tuple
, *globals
;
338 PyFrameObject
*frame
;
339 PyThreadState
*tstate
;
341 empty_string
= PyString_FromString ("");
345 null_tuple
= PyTuple_New (0);
348 Py_DECREF (empty_string
);
352 code
= PyCode_New (0, /* argcount */
356 empty_string
, /* code */
357 null_tuple
, /* consts */
358 null_tuple
, /* names */
359 null_tuple
, /* varnames */
360 #if PYTHON_API_VERSION >= 1010
361 null_tuple
, /* freevars */
362 null_tuple
, /* cellvars */
364 empty_string
, /* filename */
365 empty_string
, /* name */
367 empty_string
/* lnotab */
370 Py_DECREF (empty_string
);
371 Py_DECREF (null_tuple
);
376 globals
= PyDict_New ();
383 tstate
= PyThreadState_GET ();
385 frame
= PyFrame_New (tstate
, code
, globals
, NULL
);
393 tstate
->frame
= frame
;
394 make_cleanup (py_restore_tstate
, frame
->f_back
);
395 return (PyObject
*) frame
;
398 /* Helper for apply_val_pretty_printer that formats children of the
399 printer, if any exist. If is_py_none is true, then nothing has
400 been printed by to_string, and format output accordingly. */
402 print_children (PyObject
*printer
, const char *hint
,
403 struct ui_file
*stream
, int recurse
,
404 const struct value_print_options
*options
,
405 const struct language_defn
*language
,
408 int is_map
, is_array
, done_flag
, pretty
;
410 PyObject
*children
, *iter
, *frame
;
411 struct cleanup
*cleanups
;
413 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
416 /* If we are printing a map or an array, we want some special
418 is_map
= hint
&& ! strcmp (hint
, "map");
419 is_array
= hint
&& ! strcmp (hint
, "array");
421 children
= PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
425 gdbpy_print_stack ();
429 cleanups
= make_cleanup_py_decref (children
);
431 iter
= PyObject_GetIter (children
);
434 gdbpy_print_stack ();
437 make_cleanup_py_decref (iter
);
439 /* Use the prettyprint_arrays option if we are printing an array,
440 and the pretty option otherwise. */
441 pretty
= is_array
? options
->prettyprint_arrays
: options
->pretty
;
443 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
444 where it insists on having a non-NULL tstate->frame when
445 a generator is called. */
446 frame
= push_dummy_python_frame ();
449 gdbpy_print_stack ();
452 make_cleanup_py_decref (frame
);
455 for (i
= 0; i
< options
->print_max
; ++i
)
457 PyObject
*py_v
, *item
= PyIter_Next (iter
);
459 struct cleanup
*inner_cleanup
;
463 if (PyErr_Occurred ())
464 gdbpy_print_stack ();
465 /* Set a flag so we can know whether we printed all the
466 available elements. */
472 if (! PyArg_ParseTuple (item
, "sO", &name
, &py_v
))
474 gdbpy_print_stack ();
478 inner_cleanup
= make_cleanup_py_decref (item
);
480 /* Print initial "{". For other elements, there are three
482 1. Maps. Print a "," after each value element.
483 2. Arrays. Always print a ",".
484 3. Other. Always print a ",". */
488 fputs_filtered ("{", stream
);
490 fputs_filtered (" = {", stream
);
493 else if (! is_map
|| i
% 2 == 0)
494 fputs_filtered (pretty
? "," : ", ", stream
);
496 /* In summary mode, we just want to print "= {...}" if there is
498 if (options
->summary
)
500 /* This increment tricks the post-loop logic to print what
508 if (! is_map
|| i
% 2 == 0)
512 fputs_filtered ("\n", stream
);
513 print_spaces_filtered (2 + 2 * recurse
, stream
);
516 wrap_here (n_spaces (2 + 2 *recurse
));
519 if (is_map
&& i
% 2 == 0)
520 fputs_filtered ("[", stream
);
523 /* We print the index, not whatever the child method
524 returned as the name. */
525 if (options
->print_array_indexes
)
526 fprintf_filtered (stream
, "[%d] = ", i
);
530 fputs_filtered (name
, stream
);
531 fputs_filtered (" = ", stream
);
534 if (gdbpy_is_lazy_string (py_v
) || gdbpy_is_string (py_v
))
536 gdb_byte
*output
= NULL
;
538 if (gdbpy_is_lazy_string (py_v
))
542 char *encoding
= NULL
;
544 output
= gdbpy_extract_lazy_string (py_v
, &type
,
547 gdbpy_print_stack ();
548 LA_PRINT_STRING (stream
, type
, output
, length
, encoding
,
555 output
= python_string_to_host_string (py_v
);
556 fputs_filtered (output
, stream
);
562 struct value
*value
= convert_value_from_python (py_v
);
566 gdbpy_print_stack ();
567 error (_("Error while executing Python code."));
570 common_val_print (value
, stream
, recurse
+ 1, options
, language
);
573 if (is_map
&& i
% 2 == 0)
574 fputs_filtered ("] = ", stream
);
576 do_cleanups (inner_cleanup
);
585 fputs_filtered ("\n", stream
);
586 print_spaces_filtered (2 + 2 * recurse
, stream
);
588 fputs_filtered ("...", stream
);
592 fputs_filtered ("\n", stream
);
593 print_spaces_filtered (2 * recurse
, stream
);
595 fputs_filtered ("}", stream
);
599 do_cleanups (cleanups
);
603 apply_val_pretty_printer (struct type
*type
, const gdb_byte
*valaddr
,
604 int embedded_offset
, CORE_ADDR address
,
605 struct ui_file
*stream
, int recurse
,
606 const struct value
*val
,
607 const struct value_print_options
*options
,
608 const struct language_defn
*language
)
610 struct gdbarch
*gdbarch
= get_type_arch (type
);
611 PyObject
*printer
= NULL
;
612 PyObject
*val_obj
= NULL
;
615 struct cleanup
*cleanups
;
618 cleanups
= ensure_python_env (gdbarch
, language
);
620 /* Instantiate the printer. */
622 valaddr
+= embedded_offset
;
623 value
= value_from_contents_and_address (type
, valaddr
,
624 address
+ embedded_offset
);
627 set_value_component_location (value
, val
);
628 /* set_value_component_location resets the address, so we may
629 need to set it again. */
630 if (VALUE_LVAL (value
) != lval_internalvar
631 && VALUE_LVAL (value
) != lval_internalvar_component
632 && VALUE_LVAL (value
) != lval_computed
)
633 set_value_address (value
, address
+ embedded_offset
);
636 val_obj
= value_to_value_object (value
);
640 /* Find the constructor. */
641 printer
= find_pretty_printer (val_obj
);
643 make_cleanup_py_decref (printer
);
644 if (! printer
|| printer
== Py_None
)
647 /* If we are printing a map, we want some special formatting. */
648 hint
= gdbpy_get_display_hint (printer
);
649 make_cleanup (free_current_contents
, &hint
);
651 /* Print the section */
652 is_py_none
= print_string_repr (printer
, hint
, stream
, recurse
,
653 options
, language
, gdbarch
);
654 print_children (printer
, hint
, stream
, recurse
, options
, language
,
661 if (PyErr_Occurred ())
662 gdbpy_print_stack ();
663 do_cleanups (cleanups
);
668 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
669 print object. It must have a 'to_string' method (but this is
670 checked by varobj, not here) which takes no arguments and
671 returns a string. The printer will return a value and in the case
672 of a Python string being returned, this function will return a
673 PyObject containing the string. For any other type, *REPLACEMENT is
674 set to the replacement value and this function returns NULL. On
675 error, *REPLACEMENT is set to NULL and this function also returns
678 apply_varobj_pretty_printer (PyObject
*printer_obj
,
679 struct value
**replacement
)
681 PyObject
*py_str
= NULL
;
684 py_str
= pretty_print_one_value (printer_obj
, replacement
);
686 if (*replacement
== NULL
&& py_str
== NULL
)
687 gdbpy_print_stack ();
692 /* Find a pretty-printer object for the varobj module. Returns a new
693 reference to the object if successful; returns NULL if not. VALUE
694 is the value for which a printer tests to determine if it
695 can pretty-print the value. */
697 gdbpy_get_varobj_pretty_printer (struct value
*value
)
700 PyObject
*pretty_printer
= NULL
;
701 volatile struct gdb_exception except
;
703 TRY_CATCH (except
, RETURN_MASK_ALL
)
705 value
= value_copy (value
);
707 GDB_PY_HANDLE_EXCEPTION (except
);
709 val_obj
= value_to_value_object (value
);
713 pretty_printer
= find_pretty_printer (val_obj
);
715 return pretty_printer
;
718 /* A Python function which wraps find_pretty_printer and instantiates
719 the resulting class. This accepts a Value argument and returns a
720 pretty printer instance, or None. This function is useful as an
721 argument to the MI command -var-set-visualizer. */
723 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
729 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
731 value
= value_object_to_value (val_obj
);
734 PyErr_SetString (PyExc_TypeError
,
735 _("Argument must be a gdb.Value."));
739 cons
= find_pretty_printer (val_obj
);
743 #else /* HAVE_PYTHON */
746 apply_val_pretty_printer (struct type
*type
, const gdb_byte
*valaddr
,
747 int embedded_offset
, CORE_ADDR address
,
748 struct ui_file
*stream
, int recurse
,
749 const struct value
*val
,
750 const struct value_print_options
*options
,
751 const struct language_defn
*language
)
756 #endif /* HAVE_PYTHON */