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
))
54 PyObject
*attr
= PyObject_GetAttr (function
, gdbpy_enabled_cst
);
59 cmp
= PyObject_IsTrue (attr
);
67 printer
= PyObject_CallFunctionObjArgs (function
, value
, NULL
);
70 else if (printer
!= Py_None
)
79 /* Subroutine of find_pretty_printer to simplify it.
80 Look for a pretty-printer to print VALUE in all objfiles.
81 The result is NULL if there's an error and the search should be terminated.
82 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
83 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
86 find_pretty_printer_from_objfiles (PyObject
*value
)
94 PyObject
*objf
= objfile_to_objfile_object (obj
);
97 /* Ignore the error and continue. */
102 pp_list
= objfpy_get_printers (objf
, NULL
);
103 function
= search_pp_list (pp_list
, value
);
104 Py_XDECREF (pp_list
);
106 /* If there is an error in any objfile list, abort the search and exit. */
110 if (function
!= Py_None
)
113 Py_DECREF (function
);
119 /* Subroutine of find_pretty_printer to simplify it.
120 Look for a pretty-printer to print VALUE in the current program space.
121 The result is NULL if there's an error and the search should be terminated.
122 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
123 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
126 find_pretty_printer_from_progspace (PyObject
*value
)
130 PyObject
*obj
= pspace_to_pspace_object (current_program_space
);
134 pp_list
= pspy_get_printers (obj
, NULL
);
135 function
= search_pp_list (pp_list
, value
);
136 Py_XDECREF (pp_list
);
140 /* Subroutine of find_pretty_printer to simplify it.
141 Look for a pretty-printer to print VALUE in the gdb module.
142 The result is NULL if there's an error and the search should be terminated.
143 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
144 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
147 find_pretty_printer_from_gdb (PyObject
*value
)
152 /* Fetch the global pretty printer dictionary. */
153 if (! PyObject_HasAttrString (gdb_module
, "pretty_printers"))
155 pp_list
= PyObject_GetAttrString (gdb_module
, "pretty_printers");
156 if (pp_list
== NULL
|| ! PyList_Check (pp_list
))
158 Py_XDECREF (pp_list
);
162 function
= search_pp_list (pp_list
, value
);
163 Py_XDECREF (pp_list
);
167 /* Find the pretty-printing constructor function for VALUE. If no
168 pretty-printer exists, return None. If one exists, return a new
169 reference. On error, set the Python error and return NULL. */
172 find_pretty_printer (PyObject
*value
)
176 /* Look at the pretty-printer dictionary for each objfile
177 in the current program-space. */
178 function
= find_pretty_printer_from_objfiles (value
);
179 if (function
== NULL
|| function
!= Py_None
)
181 Py_DECREF (function
);
183 /* Look at the pretty-printer dictionary for the current program-space. */
184 function
= find_pretty_printer_from_progspace (value
);
185 if (function
== NULL
|| function
!= Py_None
)
187 Py_DECREF (function
);
189 /* Look at the pretty-printer dictionary in the gdb module. */
190 function
= find_pretty_printer_from_gdb (value
);
194 /* Pretty-print a single value, via the printer object PRINTER.
195 If the function returns a string, a PyObject containing the string
196 is returned. If the function returns Py_NONE that means the pretty
197 printer returned the Python None as a value. Otherwise, if the
198 function returns a value, *OUT_VALUE is set to the value, and NULL
199 is returned. On error, *OUT_VALUE is set to NULL, NULL is
200 returned, with a python exception set. */
203 pretty_print_one_value (PyObject
*printer
, struct value
**out_value
)
205 volatile struct gdb_exception except
;
206 PyObject
*result
= NULL
;
209 TRY_CATCH (except
, RETURN_MASK_ALL
)
211 result
= PyObject_CallMethodObjArgs (printer
, gdbpy_to_string_cst
, NULL
);
214 if (! gdbpy_is_string (result
) && ! gdbpy_is_lazy_string (result
)
215 && result
!= Py_None
)
217 *out_value
= convert_value_from_python (result
);
218 if (PyErr_Occurred ())
229 /* Return the display hint for the object printer, PRINTER. Return
230 NULL if there is no display_hint method, or if the method did not
231 return a string. On error, print stack trace and return NULL. On
232 success, return an xmalloc()d string. */
234 gdbpy_get_display_hint (PyObject
*printer
)
239 if (! PyObject_HasAttr (printer
, gdbpy_display_hint_cst
))
242 hint
= PyObject_CallMethodObjArgs (printer
, gdbpy_display_hint_cst
, NULL
);
245 if (gdbpy_is_string (hint
))
247 result
= python_string_to_host_string (hint
);
249 gdbpy_print_stack ();
254 gdbpy_print_stack ();
259 /* Helper for apply_val_pretty_printer which calls to_string and
260 formats the result. If the value returnd is Py_None, nothing is
261 printed and the function returns a 1; in all other cases data is
262 printed as given by the pretty printer and the function returns 0.
265 print_string_repr (PyObject
*printer
, const char *hint
,
266 struct ui_file
*stream
, int recurse
,
267 const struct value_print_options
*options
,
268 const struct language_defn
*language
,
269 struct gdbarch
*gdbarch
)
271 struct value
*replacement
= NULL
;
272 PyObject
*py_str
= NULL
;
275 py_str
= pretty_print_one_value (printer
, &replacement
);
278 if (py_str
== Py_None
)
282 gdb_byte
*output
= NULL
;
285 char *encoding
= NULL
;
286 PyObject
*string
= NULL
;
289 is_lazy
= gdbpy_is_lazy_string (py_str
);
291 output
= gdbpy_extract_lazy_string (py_str
, &type
, &length
, &encoding
);
294 string
= python_string_to_target_python_string (py_str
);
297 output
= PyString_AsString (string
);
298 length
= PyString_Size (string
);
299 type
= builtin_type (gdbarch
)->builtin_char
;
302 gdbpy_print_stack ();
308 if (is_lazy
|| (hint
&& !strcmp (hint
, "string")))
309 LA_PRINT_STRING (stream
, type
, output
, length
, encoding
,
312 fputs_filtered (output
, stream
);
315 gdbpy_print_stack ();
326 else if (replacement
)
328 struct value_print_options opts
= *options
;
330 opts
.addressprint
= 0;
331 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
334 gdbpy_print_stack ();
340 py_restore_tstate (void *p
)
342 PyFrameObject
*frame
= p
;
343 PyThreadState
*tstate
= PyThreadState_GET ();
345 tstate
->frame
= frame
;
348 /* Create a dummy PyFrameObject, needed to work around
349 a Python-2.4 bug with generators. */
351 push_dummy_python_frame ()
353 PyObject
*empty_string
, *null_tuple
, *globals
;
355 PyFrameObject
*frame
;
356 PyThreadState
*tstate
;
358 empty_string
= PyString_FromString ("");
362 null_tuple
= PyTuple_New (0);
365 Py_DECREF (empty_string
);
369 code
= PyCode_New (0, /* argcount */
373 empty_string
, /* code */
374 null_tuple
, /* consts */
375 null_tuple
, /* names */
376 null_tuple
, /* varnames */
377 #if PYTHON_API_VERSION >= 1010
378 null_tuple
, /* freevars */
379 null_tuple
, /* cellvars */
381 empty_string
, /* filename */
382 empty_string
, /* name */
384 empty_string
/* lnotab */
387 Py_DECREF (empty_string
);
388 Py_DECREF (null_tuple
);
393 globals
= PyDict_New ();
400 tstate
= PyThreadState_GET ();
402 frame
= PyFrame_New (tstate
, code
, globals
, NULL
);
410 tstate
->frame
= frame
;
411 make_cleanup (py_restore_tstate
, frame
->f_back
);
412 return (PyObject
*) frame
;
415 /* Helper for apply_val_pretty_printer that formats children of the
416 printer, if any exist. If is_py_none is true, then nothing has
417 been printed by to_string, and format output accordingly. */
419 print_children (PyObject
*printer
, const char *hint
,
420 struct ui_file
*stream
, int recurse
,
421 const struct value_print_options
*options
,
422 const struct language_defn
*language
,
425 int is_map
, is_array
, done_flag
, pretty
;
427 PyObject
*children
, *iter
, *frame
;
428 struct cleanup
*cleanups
;
430 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
433 /* If we are printing a map or an array, we want some special
435 is_map
= hint
&& ! strcmp (hint
, "map");
436 is_array
= hint
&& ! strcmp (hint
, "array");
438 children
= PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
442 gdbpy_print_stack ();
446 cleanups
= make_cleanup_py_decref (children
);
448 iter
= PyObject_GetIter (children
);
451 gdbpy_print_stack ();
454 make_cleanup_py_decref (iter
);
456 /* Use the prettyprint_arrays option if we are printing an array,
457 and the pretty option otherwise. */
458 pretty
= is_array
? options
->prettyprint_arrays
: options
->pretty
;
460 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
461 where it insists on having a non-NULL tstate->frame when
462 a generator is called. */
463 frame
= push_dummy_python_frame ();
466 gdbpy_print_stack ();
469 make_cleanup_py_decref (frame
);
472 for (i
= 0; i
< options
->print_max
; ++i
)
474 PyObject
*py_v
, *item
= PyIter_Next (iter
);
476 struct cleanup
*inner_cleanup
;
480 if (PyErr_Occurred ())
481 gdbpy_print_stack ();
482 /* Set a flag so we can know whether we printed all the
483 available elements. */
489 if (! PyArg_ParseTuple (item
, "sO", &name
, &py_v
))
491 gdbpy_print_stack ();
495 inner_cleanup
= make_cleanup_py_decref (item
);
497 /* Print initial "{". For other elements, there are three
499 1. Maps. Print a "," after each value element.
500 2. Arrays. Always print a ",".
501 3. Other. Always print a ",". */
505 fputs_filtered ("{", stream
);
507 fputs_filtered (" = {", stream
);
510 else if (! is_map
|| i
% 2 == 0)
511 fputs_filtered (pretty
? "," : ", ", stream
);
513 /* In summary mode, we just want to print "= {...}" if there is
515 if (options
->summary
)
517 /* This increment tricks the post-loop logic to print what
525 if (! is_map
|| i
% 2 == 0)
529 fputs_filtered ("\n", stream
);
530 print_spaces_filtered (2 + 2 * recurse
, stream
);
533 wrap_here (n_spaces (2 + 2 *recurse
));
536 if (is_map
&& i
% 2 == 0)
537 fputs_filtered ("[", stream
);
540 /* We print the index, not whatever the child method
541 returned as the name. */
542 if (options
->print_array_indexes
)
543 fprintf_filtered (stream
, "[%d] = ", i
);
547 fputs_filtered (name
, stream
);
548 fputs_filtered (" = ", stream
);
551 if (gdbpy_is_lazy_string (py_v
) || gdbpy_is_string (py_v
))
553 gdb_byte
*output
= NULL
;
555 if (gdbpy_is_lazy_string (py_v
))
559 char *encoding
= NULL
;
561 output
= gdbpy_extract_lazy_string (py_v
, &type
,
564 gdbpy_print_stack ();
565 LA_PRINT_STRING (stream
, type
, output
, length
, encoding
,
572 output
= python_string_to_host_string (py_v
);
574 gdbpy_print_stack ();
576 fputs_filtered (output
, stream
);
582 struct value
*value
= convert_value_from_python (py_v
);
586 gdbpy_print_stack ();
587 error (_("Error while executing Python code."));
590 common_val_print (value
, stream
, recurse
+ 1, options
, language
);
593 if (is_map
&& i
% 2 == 0)
594 fputs_filtered ("] = ", stream
);
596 do_cleanups (inner_cleanup
);
605 fputs_filtered ("\n", stream
);
606 print_spaces_filtered (2 + 2 * recurse
, stream
);
608 fputs_filtered ("...", stream
);
612 fputs_filtered ("\n", stream
);
613 print_spaces_filtered (2 * recurse
, stream
);
615 fputs_filtered ("}", stream
);
619 do_cleanups (cleanups
);
623 apply_val_pretty_printer (struct type
*type
, const gdb_byte
*valaddr
,
624 int embedded_offset
, CORE_ADDR address
,
625 struct ui_file
*stream
, int recurse
,
626 const struct value
*val
,
627 const struct value_print_options
*options
,
628 const struct language_defn
*language
)
630 struct gdbarch
*gdbarch
= get_type_arch (type
);
631 PyObject
*printer
= NULL
;
632 PyObject
*val_obj
= NULL
;
635 struct cleanup
*cleanups
;
638 cleanups
= ensure_python_env (gdbarch
, language
);
640 /* Instantiate the printer. */
642 valaddr
+= embedded_offset
;
643 value
= value_from_contents_and_address (type
, valaddr
,
644 address
+ embedded_offset
);
647 set_value_component_location (value
, val
);
648 /* set_value_component_location resets the address, so we may
649 need to set it again. */
650 if (VALUE_LVAL (value
) != lval_internalvar
651 && VALUE_LVAL (value
) != lval_internalvar_component
652 && VALUE_LVAL (value
) != lval_computed
)
653 set_value_address (value
, address
+ embedded_offset
);
656 val_obj
= value_to_value_object (value
);
660 /* Find the constructor. */
661 printer
= find_pretty_printer (val_obj
);
663 make_cleanup_py_decref (printer
);
664 if (! printer
|| printer
== Py_None
)
667 /* If we are printing a map, we want some special formatting. */
668 hint
= gdbpy_get_display_hint (printer
);
669 make_cleanup (free_current_contents
, &hint
);
671 /* Print the section */
672 is_py_none
= print_string_repr (printer
, hint
, stream
, recurse
,
673 options
, language
, gdbarch
);
674 print_children (printer
, hint
, stream
, recurse
, options
, language
,
681 if (PyErr_Occurred ())
682 gdbpy_print_stack ();
683 do_cleanups (cleanups
);
688 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
689 print object. It must have a 'to_string' method (but this is
690 checked by varobj, not here) which takes no arguments and
691 returns a string. The printer will return a value and in the case
692 of a Python string being returned, this function will return a
693 PyObject containing the string. For any other type, *REPLACEMENT is
694 set to the replacement value and this function returns NULL. On
695 error, *REPLACEMENT is set to NULL and this function also returns
698 apply_varobj_pretty_printer (PyObject
*printer_obj
,
699 struct value
**replacement
)
701 PyObject
*py_str
= NULL
;
704 py_str
= pretty_print_one_value (printer_obj
, replacement
);
706 if (*replacement
== NULL
&& py_str
== NULL
)
707 gdbpy_print_stack ();
712 /* Find a pretty-printer object for the varobj module. Returns a new
713 reference to the object if successful; returns NULL if not. VALUE
714 is the value for which a printer tests to determine if it
715 can pretty-print the value. */
717 gdbpy_get_varobj_pretty_printer (struct value
*value
)
720 PyObject
*pretty_printer
= NULL
;
721 volatile struct gdb_exception except
;
723 TRY_CATCH (except
, RETURN_MASK_ALL
)
725 value
= value_copy (value
);
727 GDB_PY_HANDLE_EXCEPTION (except
);
729 val_obj
= value_to_value_object (value
);
733 pretty_printer
= find_pretty_printer (val_obj
);
735 return pretty_printer
;
738 /* A Python function which wraps find_pretty_printer and instantiates
739 the resulting class. This accepts a Value argument and returns a
740 pretty printer instance, or None. This function is useful as an
741 argument to the MI command -var-set-visualizer. */
743 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
749 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
751 value
= value_object_to_value (val_obj
);
754 PyErr_SetString (PyExc_TypeError
,
755 _("Argument must be a gdb.Value."));
759 cons
= find_pretty_printer (val_obj
);
763 #else /* HAVE_PYTHON */
766 apply_val_pretty_printer (struct type
*type
, const gdb_byte
*valaddr
,
767 int embedded_offset
, CORE_ADDR address
,
768 struct ui_file
*stream
, int recurse
,
769 const struct value
*val
,
770 const struct value_print_options
*options
,
771 const struct language_defn
*language
)
776 #endif /* HAVE_PYTHON */