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);
234 if (gdbpy_is_string (hint))
235 result = python_string_to_host_string (hint);
239 gdbpy_print_stack ();
244 /* Helper for apply_val_pretty_printer which calls to_string and
245 formats the result. If the value returnd is Py_None, nothing is
246 printed and the function returns a 1; in all other cases data is
247 printed as given by the pretty printer and the function returns 0.
250 print_string_repr (PyObject *printer, const char *hint,
251 struct ui_file *stream, int recurse,
252 const struct value_print_options *options,
253 const struct language_defn *language,
254 struct gdbarch *gdbarch)
256 struct value *replacement = NULL;
257 PyObject *py_str = NULL;
260 py_str = pretty_print_one_value (printer, &replacement);
263 if (py_str == Py_None)
267 gdb_byte *output = NULL;
270 char *encoding = NULL;
271 PyObject *string = NULL;
274 is_lazy = gdbpy_is_lazy_string (py_str);
276 output = gdbpy_extract_lazy_string (py_str, &type, &length, &encoding);
279 string = python_string_to_target_python_string (py_str);
282 output = PyString_AsString (string);
283 length = PyString_Size (string);
284 type = builtin_type (gdbarch)->builtin_char;
287 gdbpy_print_stack ();
293 if (is_lazy || (hint && !strcmp (hint, "string")))
294 LA_PRINT_STRING (stream, type, output, length, encoding,
297 fputs_filtered (output, stream);
300 gdbpy_print_stack ();
311 else if (replacement)
313 struct value_print_options opts = *options;
315 opts.addressprint = 0;
316 common_val_print (replacement, stream, recurse, &opts, language);
319 gdbpy_print_stack ();
325 py_restore_tstate (void *p)
327 PyFrameObject *frame = p;
328 PyThreadState *tstate = PyThreadState_GET ();
330 tstate->frame = frame;
333 /* Create a dummy PyFrameObject, needed to work around
334 a Python-2.4 bug with generators. */
336 push_dummy_python_frame ()
338 PyObject *empty_string, *null_tuple, *globals;
340 PyFrameObject *frame;
341 PyThreadState *tstate;
343 empty_string = PyString_FromString ("");
347 null_tuple = PyTuple_New (0);
350 Py_DECREF (empty_string);
354 code = PyCode_New (0, /* argcount */
358 empty_string, /* code */
359 null_tuple, /* consts */
360 null_tuple, /* names */
361 null_tuple, /* varnames */
362 #if PYTHON_API_VERSION >= 1010
363 null_tuple, /* freevars */
364 null_tuple, /* cellvars */
366 empty_string, /* filename */
367 empty_string, /* name */
369 empty_string /* lnotab */
372 Py_DECREF (empty_string);
373 Py_DECREF (null_tuple);
378 globals = PyDict_New ();
385 tstate = PyThreadState_GET ();
387 frame = PyFrame_New (tstate, code, globals, NULL);
395 tstate->frame = frame;
396 make_cleanup (py_restore_tstate, frame->f_back);
397 return (PyObject *) frame;
400 /* Helper for apply_val_pretty_printer that formats children of the
401 printer, if any exist. If is_py_none is true, then nothing has
402 been printed by to_string, and format output accordingly. */
404 print_children (PyObject *printer, const char *hint,
405 struct ui_file *stream, int recurse,
406 const struct value_print_options *options,
407 const struct language_defn *language,
410 int is_map, is_array, done_flag, pretty;
412 PyObject *children, *iter, *frame;
413 struct cleanup *cleanups;
415 if (! PyObject_HasAttr (printer, gdbpy_children_cst))
418 /* If we are printing a map or an array, we want some special
420 is_map = hint && ! strcmp (hint, "map");
421 is_array = hint && ! strcmp (hint, "array");
423 children = PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
427 gdbpy_print_stack ();
431 cleanups = make_cleanup_py_decref (children);
433 iter = PyObject_GetIter (children);
436 gdbpy_print_stack ();
439 make_cleanup_py_decref (iter);
441 /* Use the prettyprint_arrays option if we are printing an array,
442 and the pretty option otherwise. */
443 pretty = is_array ? options->prettyprint_arrays : options->pretty;
445 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
446 where it insists on having a non-NULL tstate->frame when
447 a generator is called. */
448 frame = push_dummy_python_frame ();
451 gdbpy_print_stack ();
454 make_cleanup_py_decref (frame);
457 for (i = 0; i < options->print_max; ++i)
459 PyObject *py_v, *item = PyIter_Next (iter);
461 struct cleanup *inner_cleanup;
465 if (PyErr_Occurred ())
466 gdbpy_print_stack ();
467 /* Set a flag so we can know whether we printed all the
468 available elements. */
474 if (! PyArg_ParseTuple (item, "sO", &name, &py_v))
476 gdbpy_print_stack ();
480 inner_cleanup = make_cleanup_py_decref (item);
482 /* Print initial "{". For other elements, there are three
484 1. Maps. Print a "," after each value element.
485 2. Arrays. Always print a ",".
486 3. Other. Always print a ",". */
490 fputs_filtered ("{", stream);
492 fputs_filtered (" = {", stream);
495 else if (! is_map || i % 2 == 0)
496 fputs_filtered (pretty ? "," : ", ", stream);
498 /* In summary mode, we just want to print "= {...}" if there is
500 if (options->summary)
502 /* This increment tricks the post-loop logic to print what
510 if (! is_map || i % 2 == 0)
514 fputs_filtered ("\n", stream);
515 print_spaces_filtered (2 + 2 * recurse, stream);
518 wrap_here (n_spaces (2 + 2 *recurse));
521 if (is_map && i % 2 == 0)
522 fputs_filtered ("[", stream);
525 /* We print the index, not whatever the child method
526 returned as the name. */
527 if (options->print_array_indexes)
528 fprintf_filtered (stream, "[%d] = ", i);
532 fputs_filtered (name, stream);
533 fputs_filtered (" = ", stream);
536 if (gdbpy_is_lazy_string (py_v) || gdbpy_is_string (py_v))
538 gdb_byte *output = NULL;
540 if (gdbpy_is_lazy_string (py_v))
544 char *encoding = NULL;
546 output = gdbpy_extract_lazy_string (py_v, &type,
549 gdbpy_print_stack ();
550 LA_PRINT_STRING (stream, type, output, length, encoding,
557 output = python_string_to_host_string (py_v);
558 fputs_filtered (output, stream);
564 struct value *value = convert_value_from_python (py_v);
568 gdbpy_print_stack ();
569 error (_("Error while executing Python code."));
572 common_val_print (value, stream, recurse + 1, options, language);
575 if (is_map && i % 2 == 0)
576 fputs_filtered ("] = ", stream);
578 do_cleanups (inner_cleanup);
587 fputs_filtered ("\n", stream);
588 print_spaces_filtered (2 + 2 * recurse, stream);
590 fputs_filtered ("...", stream);
594 fputs_filtered ("\n", stream);
595 print_spaces_filtered (2 * recurse, stream);
597 fputs_filtered ("}", stream);
601 do_cleanups (cleanups);
605 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
606 int embedded_offset, CORE_ADDR address,
607 struct ui_file *stream, int recurse,
608 const struct value *val,
609 const struct value_print_options *options,
610 const struct language_defn *language)
612 struct gdbarch *gdbarch = get_type_arch (type);
613 PyObject *printer = NULL;
614 PyObject *val_obj = NULL;
617 struct cleanup *cleanups;
620 cleanups = ensure_python_env (gdbarch, language);
622 /* Instantiate the printer. */
624 valaddr += embedded_offset;
625 value = value_from_contents_and_address (type, valaddr,
626 address + embedded_offset);
629 set_value_component_location (value, val);
630 /* set_value_component_location resets the address, so we may
631 need to set it again. */
632 if (VALUE_LVAL (value) != lval_internalvar
633 && VALUE_LVAL (value) != lval_internalvar_component
634 && VALUE_LVAL (value) != lval_computed)
635 set_value_address (value, address + embedded_offset);
638 val_obj = value_to_value_object (value);
642 /* Find the constructor. */
643 printer = find_pretty_printer (val_obj);
645 make_cleanup_py_decref (printer);
646 if (! printer || printer == Py_None)
649 /* If we are printing a map, we want some special formatting. */
650 hint = gdbpy_get_display_hint (printer);
651 make_cleanup (free_current_contents, &hint);
653 /* Print the section */
654 is_py_none = print_string_repr (printer, hint, stream, recurse,
655 options, language, gdbarch);
656 print_children (printer, hint, stream, recurse, options, language,
663 if (PyErr_Occurred ())
664 gdbpy_print_stack ();
665 do_cleanups (cleanups);
670 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
671 print object. It must have a 'to_string' method (but this is
672 checked by varobj, not here) which takes no arguments and
673 returns a string. The printer will return a value and in the case
674 of a Python string being returned, this function will return a
675 PyObject containing the string. For any other type, *REPLACEMENT is
676 set to the replacement value and this function returns NULL. On
677 error, *REPLACEMENT is set to NULL and this function also returns
680 apply_varobj_pretty_printer (PyObject *printer_obj,
681 struct value **replacement)
683 PyObject *py_str = NULL;
686 py_str = pretty_print_one_value (printer_obj, replacement);
688 if (*replacement == NULL && py_str == NULL)
689 gdbpy_print_stack ();
694 /* Find a pretty-printer object for the varobj module. Returns a new
695 reference to the object if successful; returns NULL if not. VALUE
696 is the value for which a printer tests to determine if it
697 can pretty-print the value. */
699 gdbpy_get_varobj_pretty_printer (struct value *value)
702 PyObject *pretty_printer = NULL;
703 volatile struct gdb_exception except;
705 TRY_CATCH (except, RETURN_MASK_ALL)
707 value = value_copy (value);
709 GDB_PY_HANDLE_EXCEPTION (except);
711 val_obj = value_to_value_object (value);
715 pretty_printer = find_pretty_printer (val_obj);
717 return pretty_printer;
720 /* A Python function which wraps find_pretty_printer and instantiates
721 the resulting class. This accepts a Value argument and returns a
722 pretty printer instance, or None. This function is useful as an
723 argument to the MI command -var-set-visualizer. */
725 gdbpy_default_visualizer (PyObject *self, PyObject *args)
731 if (! PyArg_ParseTuple (args, "O", &val_obj))
733 value = value_object_to_value (val_obj);
736 PyErr_SetString (PyExc_TypeError,
737 _("Argument must be a gdb.Value."));
741 cons = find_pretty_printer (val_obj);
745 #else /* HAVE_PYTHON */
748 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
749 int embedded_offset, CORE_ADDR address,
750 struct ui_file *stream, int recurse,
751 const struct value *val,
752 const struct value_print_options *options,
753 const struct language_defn *language)
758 #endif /* HAVE_PYTHON */