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, and NULL is
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))
246 result = python_string_to_host_string (hint);
250 gdbpy_print_stack ();
255 /* Helper for apply_val_pretty_printer which calls to_string and
256 formats the result. If the value returnd is Py_None, nothing is
257 printed and the function returns a 1; in all other cases data is
258 printed as given by the pretty printer and the function returns 0.
261 print_string_repr (PyObject *printer, const char *hint,
262 struct ui_file *stream, int recurse,
263 const struct value_print_options *options,
264 const struct language_defn *language,
265 struct gdbarch *gdbarch)
267 struct value *replacement = NULL;
268 PyObject *py_str = NULL;
271 py_str = pretty_print_one_value (printer, &replacement);
274 if (py_str == Py_None)
278 gdb_byte *output = NULL;
281 char *encoding = NULL;
282 PyObject *string = NULL;
285 is_lazy = gdbpy_is_lazy_string (py_str);
287 output = gdbpy_extract_lazy_string (py_str, &type, &length, &encoding);
290 string = python_string_to_target_python_string (py_str);
293 output = PyString_AsString (string);
294 length = PyString_Size (string);
295 type = builtin_type (gdbarch)->builtin_char;
298 gdbpy_print_stack ();
304 if (is_lazy || (hint && !strcmp (hint, "string")))
305 LA_PRINT_STRING (stream, type, output, length, encoding,
308 fputs_filtered (output, stream);
311 gdbpy_print_stack ();
322 else if (replacement)
324 struct value_print_options opts = *options;
326 opts.addressprint = 0;
327 common_val_print (replacement, stream, recurse, &opts, language);
330 gdbpy_print_stack ();
336 py_restore_tstate (void *p)
338 PyFrameObject *frame = p;
339 PyThreadState *tstate = PyThreadState_GET ();
341 tstate->frame = frame;
344 /* Create a dummy PyFrameObject, needed to work around
345 a Python-2.4 bug with generators. */
347 push_dummy_python_frame ()
349 PyObject *empty_string, *null_tuple, *globals;
351 PyFrameObject *frame;
352 PyThreadState *tstate;
354 empty_string = PyString_FromString ("");
358 null_tuple = PyTuple_New (0);
361 Py_DECREF (empty_string);
365 code = PyCode_New (0, /* argcount */
369 empty_string, /* code */
370 null_tuple, /* consts */
371 null_tuple, /* names */
372 null_tuple, /* varnames */
373 #if PYTHON_API_VERSION >= 1010
374 null_tuple, /* freevars */
375 null_tuple, /* cellvars */
377 empty_string, /* filename */
378 empty_string, /* name */
380 empty_string /* lnotab */
383 Py_DECREF (empty_string);
384 Py_DECREF (null_tuple);
389 globals = PyDict_New ();
396 tstate = PyThreadState_GET ();
398 frame = PyFrame_New (tstate, code, globals, NULL);
406 tstate->frame = frame;
407 make_cleanup (py_restore_tstate, frame->f_back);
408 return (PyObject *) frame;
411 /* Helper for apply_val_pretty_printer that formats children of the
412 printer, if any exist. If is_py_none is true, then nothing has
413 been printed by to_string, and format output accordingly. */
415 print_children (PyObject *printer, const char *hint,
416 struct ui_file *stream, int recurse,
417 const struct value_print_options *options,
418 const struct language_defn *language,
421 int is_map, is_array, done_flag, pretty;
423 PyObject *children, *iter, *frame;
424 struct cleanup *cleanups;
426 if (! PyObject_HasAttr (printer, gdbpy_children_cst))
429 /* If we are printing a map or an array, we want some special
431 is_map = hint && ! strcmp (hint, "map");
432 is_array = hint && ! strcmp (hint, "array");
434 children = PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
438 gdbpy_print_stack ();
442 cleanups = make_cleanup_py_decref (children);
444 iter = PyObject_GetIter (children);
447 gdbpy_print_stack ();
450 make_cleanup_py_decref (iter);
452 /* Use the prettyprint_arrays option if we are printing an array,
453 and the pretty option otherwise. */
454 pretty = is_array ? options->prettyprint_arrays : options->pretty;
456 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
457 where it insists on having a non-NULL tstate->frame when
458 a generator is called. */
459 frame = push_dummy_python_frame ();
462 gdbpy_print_stack ();
465 make_cleanup_py_decref (frame);
468 for (i = 0; i < options->print_max; ++i)
470 PyObject *py_v, *item = PyIter_Next (iter);
472 struct cleanup *inner_cleanup;
476 if (PyErr_Occurred ())
477 gdbpy_print_stack ();
478 /* Set a flag so we can know whether we printed all the
479 available elements. */
485 if (! PyArg_ParseTuple (item, "sO", &name, &py_v))
487 gdbpy_print_stack ();
491 inner_cleanup = make_cleanup_py_decref (item);
493 /* Print initial "{". For other elements, there are three
495 1. Maps. Print a "," after each value element.
496 2. Arrays. Always print a ",".
497 3. Other. Always print a ",". */
501 fputs_filtered ("{", stream);
503 fputs_filtered (" = {", stream);
506 else if (! is_map || i % 2 == 0)
507 fputs_filtered (pretty ? "," : ", ", stream);
509 /* In summary mode, we just want to print "= {...}" if there is
511 if (options->summary)
513 /* This increment tricks the post-loop logic to print what
521 if (! is_map || i % 2 == 0)
525 fputs_filtered ("\n", stream);
526 print_spaces_filtered (2 + 2 * recurse, stream);
529 wrap_here (n_spaces (2 + 2 *recurse));
532 if (is_map && i % 2 == 0)
533 fputs_filtered ("[", stream);
536 /* We print the index, not whatever the child method
537 returned as the name. */
538 if (options->print_array_indexes)
539 fprintf_filtered (stream, "[%d] = ", i);
543 fputs_filtered (name, stream);
544 fputs_filtered (" = ", stream);
547 if (gdbpy_is_lazy_string (py_v) || gdbpy_is_string (py_v))
549 gdb_byte *output = NULL;
551 if (gdbpy_is_lazy_string (py_v))
555 char *encoding = NULL;
557 output = gdbpy_extract_lazy_string (py_v, &type,
560 gdbpy_print_stack ();
561 LA_PRINT_STRING (stream, type, output, length, encoding,
568 output = python_string_to_host_string (py_v);
569 fputs_filtered (output, stream);
575 struct value *value = convert_value_from_python (py_v);
579 gdbpy_print_stack ();
580 error (_("Error while executing Python code."));
583 common_val_print (value, stream, recurse + 1, options, language);
586 if (is_map && i % 2 == 0)
587 fputs_filtered ("] = ", stream);
589 do_cleanups (inner_cleanup);
598 fputs_filtered ("\n", stream);
599 print_spaces_filtered (2 + 2 * recurse, stream);
601 fputs_filtered ("...", stream);
605 fputs_filtered ("\n", stream);
606 print_spaces_filtered (2 * recurse, stream);
608 fputs_filtered ("}", stream);
612 do_cleanups (cleanups);
616 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
617 int embedded_offset, CORE_ADDR address,
618 struct ui_file *stream, int recurse,
619 const struct value *val,
620 const struct value_print_options *options,
621 const struct language_defn *language)
623 struct gdbarch *gdbarch = get_type_arch (type);
624 PyObject *printer = NULL;
625 PyObject *val_obj = NULL;
628 struct cleanup *cleanups;
631 cleanups = ensure_python_env (gdbarch, language);
633 /* Instantiate the printer. */
635 valaddr += embedded_offset;
636 value = value_from_contents_and_address (type, valaddr,
637 address + embedded_offset);
640 set_value_component_location (value, val);
641 /* set_value_component_location resets the address, so we may
642 need to set it again. */
643 if (VALUE_LVAL (value) != lval_internalvar
644 && VALUE_LVAL (value) != lval_internalvar_component
645 && VALUE_LVAL (value) != lval_computed)
646 set_value_address (value, address + embedded_offset);
649 val_obj = value_to_value_object (value);
653 /* Find the constructor. */
654 printer = find_pretty_printer (val_obj);
656 make_cleanup_py_decref (printer);
657 if (! printer || printer == Py_None)
660 /* If we are printing a map, we want some special formatting. */
661 hint = gdbpy_get_display_hint (printer);
662 make_cleanup (free_current_contents, &hint);
664 /* Print the section */
665 is_py_none = print_string_repr (printer, hint, stream, recurse,
666 options, language, gdbarch);
667 print_children (printer, hint, stream, recurse, options, language,
674 if (PyErr_Occurred ())
675 gdbpy_print_stack ();
676 do_cleanups (cleanups);
681 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
682 print object. It must have a 'to_string' method (but this is
683 checked by varobj, not here) which takes no arguments and
684 returns a string. The printer will return a value and in the case
685 of a Python string being returned, this function will return a
686 PyObject containing the string. For any other type, *REPLACEMENT is
687 set to the replacement value and this function returns NULL. On
688 error, *REPLACEMENT is set to NULL and this function also returns
691 apply_varobj_pretty_printer (PyObject *printer_obj,
692 struct value **replacement)
694 PyObject *py_str = NULL;
697 py_str = pretty_print_one_value (printer_obj, replacement);
699 if (*replacement == NULL && py_str == NULL)
700 gdbpy_print_stack ();
705 /* Find a pretty-printer object for the varobj module. Returns a new
706 reference to the object if successful; returns NULL if not. VALUE
707 is the value for which a printer tests to determine if it
708 can pretty-print the value. */
710 gdbpy_get_varobj_pretty_printer (struct value *value)
713 PyObject *pretty_printer = NULL;
714 volatile struct gdb_exception except;
716 TRY_CATCH (except, RETURN_MASK_ALL)
718 value = value_copy (value);
720 GDB_PY_HANDLE_EXCEPTION (except);
722 val_obj = value_to_value_object (value);
726 pretty_printer = find_pretty_printer (val_obj);
728 return pretty_printer;
731 /* A Python function which wraps find_pretty_printer and instantiates
732 the resulting class. This accepts a Value argument and returns a
733 pretty printer instance, or None. This function is useful as an
734 argument to the MI command -var-set-visualizer. */
736 gdbpy_default_visualizer (PyObject *self, PyObject *args)
742 if (! PyArg_ParseTuple (args, "O", &val_obj))
744 value = value_object_to_value (val_obj);
747 PyErr_SetString (PyExc_TypeError,
748 _("Argument must be a gdb.Value."));
752 cons = find_pretty_printer (val_obj);
756 #else /* HAVE_PYTHON */
759 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
760 int embedded_offset, CORE_ADDR address,
761 struct ui_file *stream, int recurse,
762 const struct value *val,
763 const struct value_print_options *options,
764 const struct language_defn *language)
769 #endif /* HAVE_PYTHON */