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 struct cleanup
*cleanup
= make_cleanup_py_decref (py_str
);
280 if (py_str
== Py_None
)
282 else if (gdbpy_is_lazy_string (py_str
))
287 char *encoding
= NULL
;
289 make_cleanup (free_current_contents
, &encoding
);
290 gdbpy_extract_lazy_string (py_str
, &addr
, &type
,
293 val_print_string (type
, encoding
, addr
, (int) length
,
300 string
= python_string_to_target_python_string (py_str
);
307 make_cleanup_py_decref (string
);
308 output
= PyString_AsString (string
);
309 length
= PyString_Size (string
);
310 type
= builtin_type (gdbarch
)->builtin_char
;
312 if (hint
&& !strcmp (hint
, "string"))
313 LA_PRINT_STRING (stream
, type
, output
, length
, NULL
,
316 fputs_filtered (output
, stream
);
319 gdbpy_print_stack ();
322 do_cleanups (cleanup
);
324 else if (replacement
)
326 struct value_print_options opts
= *options
;
328 opts
.addressprint
= 0;
329 common_val_print (replacement
, stream
, recurse
, &opts
, language
);
332 gdbpy_print_stack ();
338 py_restore_tstate (void *p
)
340 PyFrameObject
*frame
= p
;
341 PyThreadState
*tstate
= PyThreadState_GET ();
343 tstate
->frame
= frame
;
346 /* Create a dummy PyFrameObject, needed to work around
347 a Python-2.4 bug with generators. */
349 push_dummy_python_frame ()
351 PyObject
*empty_string
, *null_tuple
, *globals
;
353 PyFrameObject
*frame
;
354 PyThreadState
*tstate
;
356 empty_string
= PyString_FromString ("");
360 null_tuple
= PyTuple_New (0);
363 Py_DECREF (empty_string
);
367 code
= PyCode_New (0, /* argcount */
371 empty_string
, /* code */
372 null_tuple
, /* consts */
373 null_tuple
, /* names */
374 null_tuple
, /* varnames */
375 #if PYTHON_API_VERSION >= 1010
376 null_tuple
, /* freevars */
377 null_tuple
, /* cellvars */
379 empty_string
, /* filename */
380 empty_string
, /* name */
382 empty_string
/* lnotab */
385 Py_DECREF (empty_string
);
386 Py_DECREF (null_tuple
);
391 globals
= PyDict_New ();
398 tstate
= PyThreadState_GET ();
400 frame
= PyFrame_New (tstate
, code
, globals
, NULL
);
408 tstate
->frame
= frame
;
409 make_cleanup (py_restore_tstate
, frame
->f_back
);
410 return (PyObject
*) frame
;
413 /* Helper for apply_val_pretty_printer that formats children of the
414 printer, if any exist. If is_py_none is true, then nothing has
415 been printed by to_string, and format output accordingly. */
417 print_children (PyObject
*printer
, const char *hint
,
418 struct ui_file
*stream
, int recurse
,
419 const struct value_print_options
*options
,
420 const struct language_defn
*language
,
423 int is_map
, is_array
, done_flag
, pretty
;
425 PyObject
*children
, *iter
, *frame
;
426 struct cleanup
*cleanups
;
428 if (! PyObject_HasAttr (printer
, gdbpy_children_cst
))
431 /* If we are printing a map or an array, we want some special
433 is_map
= hint
&& ! strcmp (hint
, "map");
434 is_array
= hint
&& ! strcmp (hint
, "array");
436 children
= PyObject_CallMethodObjArgs (printer
, gdbpy_children_cst
,
440 gdbpy_print_stack ();
444 cleanups
= make_cleanup_py_decref (children
);
446 iter
= PyObject_GetIter (children
);
449 gdbpy_print_stack ();
452 make_cleanup_py_decref (iter
);
454 /* Use the prettyprint_arrays option if we are printing an array,
455 and the pretty option otherwise. */
456 pretty
= is_array
? options
->prettyprint_arrays
: options
->pretty
;
458 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
459 where it insists on having a non-NULL tstate->frame when
460 a generator is called. */
461 frame
= push_dummy_python_frame ();
464 gdbpy_print_stack ();
467 make_cleanup_py_decref (frame
);
470 for (i
= 0; i
< options
->print_max
; ++i
)
472 PyObject
*py_v
, *item
= PyIter_Next (iter
);
474 struct cleanup
*inner_cleanup
;
478 if (PyErr_Occurred ())
479 gdbpy_print_stack ();
480 /* Set a flag so we can know whether we printed all the
481 available elements. */
487 if (! PyArg_ParseTuple (item
, "sO", &name
, &py_v
))
489 gdbpy_print_stack ();
493 inner_cleanup
= make_cleanup_py_decref (item
);
495 /* Print initial "{". For other elements, there are three
497 1. Maps. Print a "," after each value element.
498 2. Arrays. Always print a ",".
499 3. Other. Always print a ",". */
503 fputs_filtered ("{", stream
);
505 fputs_filtered (" = {", stream
);
508 else if (! is_map
|| i
% 2 == 0)
509 fputs_filtered (pretty
? "," : ", ", stream
);
511 /* In summary mode, we just want to print "= {...}" if there is
513 if (options
->summary
)
515 /* This increment tricks the post-loop logic to print what
523 if (! is_map
|| i
% 2 == 0)
527 fputs_filtered ("\n", stream
);
528 print_spaces_filtered (2 + 2 * recurse
, stream
);
531 wrap_here (n_spaces (2 + 2 *recurse
));
534 if (is_map
&& i
% 2 == 0)
535 fputs_filtered ("[", stream
);
538 /* We print the index, not whatever the child method
539 returned as the name. */
540 if (options
->print_array_indexes
)
541 fprintf_filtered (stream
, "[%d] = ", i
);
545 fputs_filtered (name
, stream
);
546 fputs_filtered (" = ", stream
);
549 if (gdbpy_is_lazy_string (py_v
))
554 char *encoding
= NULL
;
556 make_cleanup (free_current_contents
, &encoding
);
557 gdbpy_extract_lazy_string (py_v
, &addr
, &type
, &length
, &encoding
);
559 val_print_string (type
, encoding
, addr
, (int) length
, stream
,
562 do_cleanups (inner_cleanup
);
564 else if (gdbpy_is_string (py_v
))
568 output
= python_string_to_host_string (py_v
);
570 gdbpy_print_stack ();
573 fputs_filtered (output
, stream
);
579 struct value
*value
= convert_value_from_python (py_v
);
583 gdbpy_print_stack ();
584 error (_("Error while executing Python code."));
587 common_val_print (value
, stream
, recurse
+ 1, options
, language
);
590 if (is_map
&& i
% 2 == 0)
591 fputs_filtered ("] = ", stream
);
593 do_cleanups (inner_cleanup
);
602 fputs_filtered ("\n", stream
);
603 print_spaces_filtered (2 + 2 * recurse
, stream
);
605 fputs_filtered ("...", stream
);
609 fputs_filtered ("\n", stream
);
610 print_spaces_filtered (2 * recurse
, stream
);
612 fputs_filtered ("}", stream
);
616 do_cleanups (cleanups
);
620 apply_val_pretty_printer (struct type
*type
, const gdb_byte
*valaddr
,
621 int embedded_offset
, CORE_ADDR address
,
622 struct ui_file
*stream
, int recurse
,
623 const struct value
*val
,
624 const struct value_print_options
*options
,
625 const struct language_defn
*language
)
627 struct gdbarch
*gdbarch
= get_type_arch (type
);
628 PyObject
*printer
= NULL
;
629 PyObject
*val_obj
= NULL
;
632 struct cleanup
*cleanups
;
635 cleanups
= ensure_python_env (gdbarch
, language
);
637 /* Instantiate the printer. */
639 valaddr
+= embedded_offset
;
640 value
= value_from_contents_and_address (type
, valaddr
,
641 address
+ embedded_offset
);
644 set_value_component_location (value
, val
);
645 /* set_value_component_location resets the address, so we may
646 need to set it again. */
647 if (VALUE_LVAL (value
) != lval_internalvar
648 && VALUE_LVAL (value
) != lval_internalvar_component
649 && VALUE_LVAL (value
) != lval_computed
)
650 set_value_address (value
, address
+ embedded_offset
);
653 val_obj
= value_to_value_object (value
);
657 /* Find the constructor. */
658 printer
= find_pretty_printer (val_obj
);
660 make_cleanup_py_decref (printer
);
661 if (! printer
|| printer
== Py_None
)
664 /* If we are printing a map, we want some special formatting. */
665 hint
= gdbpy_get_display_hint (printer
);
666 make_cleanup (free_current_contents
, &hint
);
668 /* Print the section */
669 is_py_none
= print_string_repr (printer
, hint
, stream
, recurse
,
670 options
, language
, gdbarch
);
671 print_children (printer
, hint
, stream
, recurse
, options
, language
,
678 if (PyErr_Occurred ())
679 gdbpy_print_stack ();
680 do_cleanups (cleanups
);
685 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
686 print object. It must have a 'to_string' method (but this is
687 checked by varobj, not here) which takes no arguments and
688 returns a string. The printer will return a value and in the case
689 of a Python string being returned, this function will return a
690 PyObject containing the string. For any other type, *REPLACEMENT is
691 set to the replacement value and this function returns NULL. On
692 error, *REPLACEMENT is set to NULL and this function also returns
695 apply_varobj_pretty_printer (PyObject
*printer_obj
,
696 struct value
**replacement
)
698 PyObject
*py_str
= NULL
;
701 py_str
= pretty_print_one_value (printer_obj
, replacement
);
703 if (*replacement
== NULL
&& py_str
== NULL
)
704 gdbpy_print_stack ();
709 /* Find a pretty-printer object for the varobj module. Returns a new
710 reference to the object if successful; returns NULL if not. VALUE
711 is the value for which a printer tests to determine if it
712 can pretty-print the value. */
714 gdbpy_get_varobj_pretty_printer (struct value
*value
)
717 PyObject
*pretty_printer
= NULL
;
718 volatile struct gdb_exception except
;
720 TRY_CATCH (except
, RETURN_MASK_ALL
)
722 value
= value_copy (value
);
724 GDB_PY_HANDLE_EXCEPTION (except
);
726 val_obj
= value_to_value_object (value
);
730 pretty_printer
= find_pretty_printer (val_obj
);
732 return pretty_printer
;
735 /* A Python function which wraps find_pretty_printer and instantiates
736 the resulting class. This accepts a Value argument and returns a
737 pretty printer instance, or None. This function is useful as an
738 argument to the MI command -var-set-visualizer. */
740 gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
)
746 if (! PyArg_ParseTuple (args
, "O", &val_obj
))
748 value
= value_object_to_value (val_obj
);
751 PyErr_SetString (PyExc_TypeError
,
752 _("Argument must be a gdb.Value."));
756 cons
= find_pretty_printer (val_obj
);
760 #else /* HAVE_PYTHON */
763 apply_val_pretty_printer (struct type
*type
, const gdb_byte
*valaddr
,
764 int embedded_offset
, CORE_ADDR address
,
765 struct ui_file
*stream
, int recurse
,
766 const struct value
*val
,
767 const struct value_print_options
*options
,
768 const struct language_defn
*language
)
773 #endif /* HAVE_PYTHON */