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"
33 /* Helper function for find_pretty_printer which iterates over a list,
34 calls each function and inspects output. This will return a
35 printer object if one recognizes VALUE. If no printer is found, it
36 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 printer = PyObject_CallFunctionObjArgs (function, value, NULL);
54 else if (printer != Py_None)
63 /* Find the pretty-printing constructor function for VALUE. If no
64 pretty-printer exists, return None. If one exists, return a new
65 reference. On error, set the Python error and return NULL. */
67 find_pretty_printer (PyObject *value)
69 PyObject *pp_list = NULL;
70 PyObject *function = NULL;
72 volatile struct gdb_exception except;
74 /* Look at the pretty-printer dictionary for each objfile. */
77 PyObject *objf = objfile_to_objfile_object (obj);
80 /* Ignore the error and continue. */
85 pp_list = objfpy_get_printers (objf, NULL);
86 function = search_pp_list (pp_list, value);
88 /* If there is an error in any objfile list, abort the search and
96 if (function != Py_None)
100 Py_XDECREF (pp_list);
104 /* Fetch the global pretty printer dictionary. */
105 if (! PyObject_HasAttrString (gdb_module, "pretty_printers"))
108 Py_INCREF (function);
111 pp_list = PyObject_GetAttrString (gdb_module, "pretty_printers");
114 if (! PyList_Check (pp_list))
117 function = search_pp_list (pp_list, value);
120 Py_XDECREF (pp_list);
126 /* Pretty-print a single value, via the printer object PRINTER.
127 If the function returns a string, a PyObject containing the string
128 is returned. If the function returns Py_NONE that means the pretty
129 printer returned the Python None as a value. Otherwise, if the
130 function returns a value, *OUT_VALUE is set to the value, and NULL
131 is returned. On error, *OUT_VALUE is set to NULL, and NULL is
135 pretty_print_one_value (PyObject *printer, struct value **out_value)
137 volatile struct gdb_exception except;
138 PyObject *result = NULL;
141 TRY_CATCH (except, RETURN_MASK_ALL)
143 result = PyObject_CallMethodObjArgs (printer, gdbpy_to_string_cst, NULL);
146 if (! gdbpy_is_string (result) && ! gdbpy_is_lazy_string (result)
147 && result != Py_None)
149 *out_value = convert_value_from_python (result);
150 if (PyErr_Occurred ())
161 /* Return the display hint for the object printer, PRINTER. Return
162 NULL if there is no display_hint method, or if the method did not
163 return a string. On error, print stack trace and return NULL. On
164 success, return an xmalloc()d string. */
166 gdbpy_get_display_hint (PyObject *printer)
171 if (! PyObject_HasAttr (printer, gdbpy_display_hint_cst))
174 hint = PyObject_CallMethodObjArgs (printer, gdbpy_display_hint_cst, NULL);
175 if (gdbpy_is_string (hint))
176 result = python_string_to_host_string (hint);
180 gdbpy_print_stack ();
185 /* Helper for apply_val_pretty_printer which calls to_string and
186 formats the result. If the value returnd is Py_None, nothing is
187 printed and the function returns a 1; in all other cases data is
188 printed as given by the pretty printer and the function returns 0.
191 print_string_repr (PyObject *printer, const char *hint,
192 struct ui_file *stream, int recurse,
193 const struct value_print_options *options,
194 const struct language_defn *language,
195 struct gdbarch *gdbarch)
197 struct value *replacement = NULL;
198 PyObject *py_str = NULL;
201 py_str = pretty_print_one_value (printer, &replacement);
204 if (py_str == Py_None)
208 gdb_byte *output = NULL;
211 char *encoding = NULL;
212 PyObject *string = NULL;
215 is_lazy = gdbpy_is_lazy_string (py_str);
217 output = gdbpy_extract_lazy_string (py_str, &type, &length, &encoding);
220 string = python_string_to_target_python_string (py_str);
223 output = PyString_AsString (string);
224 length = PyString_Size (string);
225 type = builtin_type (gdbarch)->builtin_char;
228 gdbpy_print_stack ();
234 if (is_lazy || (hint && !strcmp (hint, "string")))
235 LA_PRINT_STRING (stream, type, output, length, encoding,
238 fputs_filtered (output, stream);
241 gdbpy_print_stack ();
252 else if (replacement)
254 struct value_print_options opts = *options;
256 opts.addressprint = 0;
257 common_val_print (replacement, stream, recurse, &opts, language);
260 gdbpy_print_stack ();
266 py_restore_tstate (void *p)
268 PyFrameObject *frame = p;
269 PyThreadState *tstate = PyThreadState_GET ();
270 tstate->frame = frame;
273 /* Create a dummy PyFrameObject, needed to work around
274 a Python-2.4 bug with generators. */
276 push_dummy_python_frame ()
278 PyObject *empty_string, *null_tuple, *globals;
280 PyFrameObject *frame;
281 PyThreadState *tstate;
283 empty_string = PyString_FromString ("");
287 null_tuple = PyTuple_New (0);
290 Py_DECREF (empty_string);
294 code = PyCode_New (0, /* argcount */
298 empty_string, /* code */
299 null_tuple, /* consts */
300 null_tuple, /* names */
301 null_tuple, /* varnames */
302 #if PYTHON_API_VERSION >= 1010
303 null_tuple, /* freevars */
304 null_tuple, /* cellvars */
306 empty_string, /* filename */
307 empty_string, /* name */
309 empty_string /* lnotab */
312 Py_DECREF (empty_string);
313 Py_DECREF (null_tuple);
318 globals = PyDict_New ();
325 tstate = PyThreadState_GET ();
327 frame = PyFrame_New (tstate, code, globals, NULL);
335 tstate->frame = frame;
336 make_cleanup (py_restore_tstate, frame->f_back);
337 return (PyObject *) frame;
340 /* Helper for apply_val_pretty_printer that formats children of the
341 printer, if any exist. If is_py_none is true, then nothing has
342 been printed by to_string, and format output accordingly. */
344 print_children (PyObject *printer, const char *hint,
345 struct ui_file *stream, int recurse,
346 const struct value_print_options *options,
347 const struct language_defn *language,
350 int is_map, is_array, done_flag, pretty;
352 PyObject *children, *iter, *frame;
353 struct cleanup *cleanups;
355 if (! PyObject_HasAttr (printer, gdbpy_children_cst))
358 /* If we are printing a map or an array, we want some special
360 is_map = hint && ! strcmp (hint, "map");
361 is_array = hint && ! strcmp (hint, "array");
363 children = PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
367 gdbpy_print_stack ();
371 cleanups = make_cleanup_py_decref (children);
373 iter = PyObject_GetIter (children);
376 gdbpy_print_stack ();
379 make_cleanup_py_decref (iter);
381 /* Use the prettyprint_arrays option if we are printing an array,
382 and the pretty option otherwise. */
383 pretty = is_array ? options->prettyprint_arrays : options->pretty;
385 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
386 where it insists on having a non-NULL tstate->frame when
387 a generator is called. */
388 frame = push_dummy_python_frame ();
391 gdbpy_print_stack ();
394 make_cleanup_py_decref (frame);
397 for (i = 0; i < options->print_max; ++i)
399 PyObject *py_v, *item = PyIter_Next (iter);
401 struct cleanup *inner_cleanup;
405 if (PyErr_Occurred ())
406 gdbpy_print_stack ();
407 /* Set a flag so we can know whether we printed all the
408 available elements. */
414 if (! PyArg_ParseTuple (item, "sO", &name, &py_v))
416 gdbpy_print_stack ();
420 inner_cleanup = make_cleanup_py_decref (item);
422 /* Print initial "{". For other elements, there are three
424 1. Maps. Print a "," after each value element.
425 2. Arrays. Always print a ",".
426 3. Other. Always print a ",". */
430 fputs_filtered ("{", stream);
432 fputs_filtered (" = {", stream);
435 else if (! is_map || i % 2 == 0)
436 fputs_filtered (pretty ? "," : ", ", stream);
438 /* In summary mode, we just want to print "= {...}" if there is
440 if (options->summary)
442 /* This increment tricks the post-loop logic to print what
450 if (! is_map || i % 2 == 0)
454 fputs_filtered ("\n", stream);
455 print_spaces_filtered (2 + 2 * recurse, stream);
458 wrap_here (n_spaces (2 + 2 *recurse));
461 if (is_map && i % 2 == 0)
462 fputs_filtered ("[", stream);
465 /* We print the index, not whatever the child method
466 returned as the name. */
467 if (options->print_array_indexes)
468 fprintf_filtered (stream, "[%d] = ", i);
472 fputs_filtered (name, stream);
473 fputs_filtered (" = ", stream);
476 if (gdbpy_is_lazy_string (py_v) || gdbpy_is_string (py_v))
478 gdb_byte *output = NULL;
480 if (gdbpy_is_lazy_string (py_v))
484 char *encoding = NULL;
486 output = gdbpy_extract_lazy_string (py_v, &type,
489 gdbpy_print_stack ();
490 LA_PRINT_STRING (stream, type, output, length, encoding,
497 output = python_string_to_host_string (py_v);
498 fputs_filtered (output, stream);
504 struct value *value = convert_value_from_python (py_v);
508 gdbpy_print_stack ();
509 error (_("Error while executing Python code."));
512 common_val_print (value, stream, recurse + 1, options, language);
515 if (is_map && i % 2 == 0)
516 fputs_filtered ("] = ", stream);
518 do_cleanups (inner_cleanup);
527 fputs_filtered ("\n", stream);
528 print_spaces_filtered (2 + 2 * recurse, stream);
530 fputs_filtered ("...", stream);
534 fputs_filtered ("\n", stream);
535 print_spaces_filtered (2 * recurse, stream);
537 fputs_filtered ("}", stream);
541 do_cleanups (cleanups);
545 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
546 int embedded_offset, CORE_ADDR address,
547 struct ui_file *stream, int recurse,
548 const struct value_print_options *options,
549 const struct language_defn *language)
551 struct gdbarch *gdbarch = get_type_arch (type);
552 PyObject *printer = NULL;
553 PyObject *val_obj = NULL;
556 struct cleanup *cleanups;
559 cleanups = ensure_python_env (gdbarch, language);
561 /* Instantiate the printer. */
563 valaddr += embedded_offset;
564 value = value_from_contents_and_address (type, valaddr,
565 address + embedded_offset);
567 val_obj = value_to_value_object (value);
571 /* Find the constructor. */
572 printer = find_pretty_printer (val_obj);
574 make_cleanup_py_decref (printer);
575 if (! printer || printer == Py_None)
578 /* If we are printing a map, we want some special formatting. */
579 hint = gdbpy_get_display_hint (printer);
580 make_cleanup (free_current_contents, &hint);
582 /* Print the section */
583 is_py_none = print_string_repr (printer, hint, stream, recurse,
584 options, language, gdbarch);
585 print_children (printer, hint, stream, recurse, options, language,
592 if (PyErr_Occurred ())
593 gdbpy_print_stack ();
594 do_cleanups (cleanups);
599 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
600 print object. It must have a 'to_string' method (but this is
601 checked by varobj, not here) which takes no arguments and
602 returns a string. The printer will return a value and in the case
603 of a Python string being returned, this function will return a
604 PyObject containing the string. For any other type, *REPLACEMENT is
605 set to the replacement value and this function returns NULL. On
606 error, *REPLACEMENT is set to NULL and this function also returns
609 apply_varobj_pretty_printer (PyObject *printer_obj,
610 struct value **replacement)
613 PyObject *py_str = NULL;
616 py_str = pretty_print_one_value (printer_obj, replacement);
618 if (*replacement == NULL && py_str == NULL)
619 gdbpy_print_stack ();
624 /* Find a pretty-printer object for the varobj module. Returns a new
625 reference to the object if successful; returns NULL if not. VALUE
626 is the value for which a printer tests to determine if it
627 can pretty-print the value. */
629 gdbpy_get_varobj_pretty_printer (struct value *value)
632 PyObject *pretty_printer = NULL;
633 volatile struct gdb_exception except;
635 TRY_CATCH (except, RETURN_MASK_ALL)
637 value = value_copy (value);
639 GDB_PY_HANDLE_EXCEPTION (except);
641 val_obj = value_to_value_object (value);
645 pretty_printer = find_pretty_printer (val_obj);
647 return pretty_printer;
650 /* A Python function which wraps find_pretty_printer and instantiates
651 the resulting class. This accepts a Value argument and returns a
652 pretty printer instance, or None. This function is useful as an
653 argument to the MI command -var-set-visualizer. */
655 gdbpy_default_visualizer (PyObject *self, PyObject *args)
658 PyObject *cons, *printer = NULL;
661 if (! PyArg_ParseTuple (args, "O", &val_obj))
663 value = value_object_to_value (val_obj);
666 PyErr_SetString (PyExc_TypeError, "argument must be a gdb.Value");
670 cons = find_pretty_printer (val_obj);
674 #else /* HAVE_PYTHON */
677 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
678 int embedded_offset, CORE_ADDR address,
679 struct ui_file *stream, int recurse,
680 const struct value_print_options *options,
681 const struct language_defn *language)
686 #endif /* HAVE_PYTHON */