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 /* Return type of print_string_repr. */
34 enum string_repr_result
36 /* The string method returned None. */
38 /* The string method had an error. */
44 /* Helper function for find_pretty_printer which iterates over a list,
45 calls each function and inspects output. This will return a
46 printer object if one recognizes VALUE. If no printer is found, it
47 will return None. On error, it will set the Python error and
51 search_pp_list (PyObject *list, PyObject *value)
53 Py_ssize_t pp_list_size, list_index;
54 PyObject *function, *printer = NULL;
56 pp_list_size = PyList_Size (list);
57 for (list_index = 0; list_index < pp_list_size; list_index++)
59 function = PyList_GetItem (list, list_index);
63 /* Skip if disabled. */
64 if (PyObject_HasAttr (function, gdbpy_enabled_cst))
66 PyObject *attr = PyObject_GetAttr (function, gdbpy_enabled_cst);
71 cmp = PyObject_IsTrue (attr);
79 printer = PyObject_CallFunctionObjArgs (function, value, NULL);
82 else if (printer != Py_None)
91 /* Subroutine of find_pretty_printer to simplify it.
92 Look for a pretty-printer to print VALUE in all objfiles.
93 The result is NULL if there's an error and the search should be terminated.
94 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
95 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
98 find_pretty_printer_from_objfiles (PyObject *value)
106 PyObject *objf = objfile_to_objfile_object (obj);
109 /* Ignore the error and continue. */
114 pp_list = objfpy_get_printers (objf, NULL);
115 function = search_pp_list (pp_list, value);
116 Py_XDECREF (pp_list);
118 /* If there is an error in any objfile list, abort the search and exit. */
122 if (function != Py_None)
125 Py_DECREF (function);
131 /* Subroutine of find_pretty_printer to simplify it.
132 Look for a pretty-printer to print VALUE in the current program space.
133 The result is NULL if there's an error and the search should be terminated.
134 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
135 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
138 find_pretty_printer_from_progspace (PyObject *value)
142 PyObject *obj = pspace_to_pspace_object (current_program_space);
146 pp_list = pspy_get_printers (obj, NULL);
147 function = search_pp_list (pp_list, value);
148 Py_XDECREF (pp_list);
152 /* Subroutine of find_pretty_printer to simplify it.
153 Look for a pretty-printer to print VALUE in the gdb module.
154 The result is NULL if there's an error and the search should be terminated.
155 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
156 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
159 find_pretty_printer_from_gdb (PyObject *value)
164 /* Fetch the global pretty printer list. */
165 if (! PyObject_HasAttrString (gdb_module, "pretty_printers"))
167 pp_list = PyObject_GetAttrString (gdb_module, "pretty_printers");
168 if (pp_list == NULL || ! PyList_Check (pp_list))
170 Py_XDECREF (pp_list);
174 function = search_pp_list (pp_list, value);
175 Py_XDECREF (pp_list);
179 /* Find the pretty-printing constructor function for VALUE. If no
180 pretty-printer exists, return None. If one exists, return a new
181 reference. On error, set the Python error and return NULL. */
184 find_pretty_printer (PyObject *value)
188 /* Look at the pretty-printer list for each objfile
189 in the current program-space. */
190 function = find_pretty_printer_from_objfiles (value);
191 if (function == NULL || function != Py_None)
193 Py_DECREF (function);
195 /* Look at the pretty-printer list for the current program-space. */
196 function = find_pretty_printer_from_progspace (value);
197 if (function == NULL || function != Py_None)
199 Py_DECREF (function);
201 /* Look at the pretty-printer list in the gdb module. */
202 function = find_pretty_printer_from_gdb (value);
206 /* Pretty-print a single value, via the printer object PRINTER.
207 If the function returns a string, a PyObject containing the string
208 is returned. If the function returns Py_NONE that means the pretty
209 printer returned the Python None as a value. Otherwise, if the
210 function returns a value, *OUT_VALUE is set to the value, and NULL
211 is returned. On error, *OUT_VALUE is set to NULL, NULL is
212 returned, with a python exception set. */
215 pretty_print_one_value (PyObject *printer, struct value **out_value)
217 volatile struct gdb_exception except;
218 PyObject *result = NULL;
221 TRY_CATCH (except, RETURN_MASK_ALL)
223 result = PyObject_CallMethodObjArgs (printer, gdbpy_to_string_cst, NULL);
226 if (! gdbpy_is_string (result) && ! gdbpy_is_lazy_string (result)
227 && result != Py_None)
229 *out_value = convert_value_from_python (result);
230 if (PyErr_Occurred ())
241 /* Return the display hint for the object printer, PRINTER. Return
242 NULL if there is no display_hint method, or if the method did not
243 return a string. On error, print stack trace and return NULL. On
244 success, return an xmalloc()d string. */
246 gdbpy_get_display_hint (PyObject *printer)
251 if (! PyObject_HasAttr (printer, gdbpy_display_hint_cst))
254 hint = PyObject_CallMethodObjArgs (printer, gdbpy_display_hint_cst, NULL);
257 if (gdbpy_is_string (hint))
259 result = python_string_to_host_string (hint);
261 gdbpy_print_stack ();
266 gdbpy_print_stack ();
271 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
274 print_stack_unless_memory_error (struct ui_file *stream)
276 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error))
278 struct cleanup *cleanup;
279 PyObject *type, *value, *trace;
282 PyErr_Fetch (&type, &value, &trace);
283 cleanup = make_cleanup_py_decref (type);
284 make_cleanup_py_decref (value);
285 make_cleanup_py_decref (trace);
287 msg = gdbpy_exception_to_string (type, value);
288 make_cleanup (xfree, msg);
290 if (msg == NULL || *msg == '\0')
291 fprintf_filtered (stream, _("<error reading variable"));
293 fprintf_filtered (stream, _("<error reading variable: %s>"), msg);
295 do_cleanups (cleanup);
298 gdbpy_print_stack ();
301 /* Helper for apply_val_pretty_printer which calls to_string and
302 formats the result. */
304 static enum string_repr_result
305 print_string_repr (PyObject *printer, const char *hint,
306 struct ui_file *stream, int recurse,
307 const struct value_print_options *options,
308 const struct language_defn *language,
309 struct gdbarch *gdbarch)
311 struct value *replacement = NULL;
312 PyObject *py_str = NULL;
313 enum string_repr_result result = string_repr_ok;
315 py_str = pretty_print_one_value (printer, &replacement);
318 struct cleanup *cleanup = make_cleanup_py_decref (py_str);
320 if (py_str == Py_None)
321 result = string_repr_none;
322 else if (gdbpy_is_lazy_string (py_str))
327 char *encoding = NULL;
329 make_cleanup (free_current_contents, &encoding);
330 gdbpy_extract_lazy_string (py_str, &addr, &type,
333 val_print_string (type, encoding, addr, (int) length,
340 string = python_string_to_target_python_string (py_str);
347 make_cleanup_py_decref (string);
348 output = PyString_AsString (string);
349 length = PyString_Size (string);
350 type = builtin_type (gdbarch)->builtin_char;
352 if (hint && !strcmp (hint, "string"))
353 LA_PRINT_STRING (stream, type, output, length, NULL,
356 fputs_filtered (output, stream);
360 result = string_repr_error;
361 print_stack_unless_memory_error (stream);
365 do_cleanups (cleanup);
367 else if (replacement)
369 struct value_print_options opts = *options;
371 opts.addressprint = 0;
372 common_val_print (replacement, stream, recurse, &opts, language);
376 result = string_repr_error;
377 print_stack_unless_memory_error (stream);
384 py_restore_tstate (void *p)
386 PyFrameObject *frame = p;
387 PyThreadState *tstate = PyThreadState_GET ();
389 tstate->frame = frame;
392 /* Create a dummy PyFrameObject, needed to work around
393 a Python-2.4 bug with generators. */
395 push_dummy_python_frame ()
397 PyObject *empty_string, *null_tuple, *globals;
399 PyFrameObject *frame;
400 PyThreadState *tstate;
402 empty_string = PyString_FromString ("");
406 null_tuple = PyTuple_New (0);
409 Py_DECREF (empty_string);
413 code = PyCode_New (0, /* argcount */
417 empty_string, /* code */
418 null_tuple, /* consts */
419 null_tuple, /* names */
420 null_tuple, /* varnames */
421 #if PYTHON_API_VERSION >= 1010
422 null_tuple, /* freevars */
423 null_tuple, /* cellvars */
425 empty_string, /* filename */
426 empty_string, /* name */
428 empty_string /* lnotab */
431 Py_DECREF (empty_string);
432 Py_DECREF (null_tuple);
437 globals = PyDict_New ();
444 tstate = PyThreadState_GET ();
446 frame = PyFrame_New (tstate, code, globals, NULL);
454 tstate->frame = frame;
455 make_cleanup (py_restore_tstate, frame->f_back);
456 return (PyObject *) frame;
459 /* Helper for apply_val_pretty_printer that formats children of the
460 printer, if any exist. If is_py_none is true, then nothing has
461 been printed by to_string, and format output accordingly. */
463 print_children (PyObject *printer, const char *hint,
464 struct ui_file *stream, int recurse,
465 const struct value_print_options *options,
466 const struct language_defn *language,
469 int is_map, is_array, done_flag, pretty;
471 PyObject *children, *iter, *frame;
472 struct cleanup *cleanups;
474 if (! PyObject_HasAttr (printer, gdbpy_children_cst))
477 /* If we are printing a map or an array, we want some special
479 is_map = hint && ! strcmp (hint, "map");
480 is_array = hint && ! strcmp (hint, "array");
482 children = PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
486 print_stack_unless_memory_error (stream);
490 cleanups = make_cleanup_py_decref (children);
492 iter = PyObject_GetIter (children);
495 print_stack_unless_memory_error (stream);
498 make_cleanup_py_decref (iter);
500 /* Use the prettyprint_arrays option if we are printing an array,
501 and the pretty option otherwise. */
502 pretty = is_array ? options->prettyprint_arrays : options->pretty;
504 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
505 where it insists on having a non-NULL tstate->frame when
506 a generator is called. */
507 frame = push_dummy_python_frame ();
510 gdbpy_print_stack ();
513 make_cleanup_py_decref (frame);
516 for (i = 0; i < options->print_max; ++i)
518 PyObject *py_v, *item = PyIter_Next (iter);
520 struct cleanup *inner_cleanup;
524 if (PyErr_Occurred ())
525 print_stack_unless_memory_error (stream);
526 /* Set a flag so we can know whether we printed all the
527 available elements. */
533 if (! PyArg_ParseTuple (item, "sO", &name, &py_v))
535 gdbpy_print_stack ();
539 inner_cleanup = make_cleanup_py_decref (item);
541 /* Print initial "{". For other elements, there are three
543 1. Maps. Print a "," after each value element.
544 2. Arrays. Always print a ",".
545 3. Other. Always print a ",". */
549 fputs_filtered ("{", stream);
551 fputs_filtered (" = {", stream);
554 else if (! is_map || i % 2 == 0)
555 fputs_filtered (pretty ? "," : ", ", stream);
557 /* In summary mode, we just want to print "= {...}" if there is
559 if (options->summary)
561 /* This increment tricks the post-loop logic to print what
569 if (! is_map || i % 2 == 0)
573 fputs_filtered ("\n", stream);
574 print_spaces_filtered (2 + 2 * recurse, stream);
577 wrap_here (n_spaces (2 + 2 *recurse));
580 if (is_map && i % 2 == 0)
581 fputs_filtered ("[", stream);
584 /* We print the index, not whatever the child method
585 returned as the name. */
586 if (options->print_array_indexes)
587 fprintf_filtered (stream, "[%d] = ", i);
591 fputs_filtered (name, stream);
592 fputs_filtered (" = ", stream);
595 if (gdbpy_is_lazy_string (py_v))
600 char *encoding = NULL;
602 make_cleanup (free_current_contents, &encoding);
603 gdbpy_extract_lazy_string (py_v, &addr, &type, &length, &encoding);
605 val_print_string (type, encoding, addr, (int) length, stream,
608 do_cleanups (inner_cleanup);
610 else if (gdbpy_is_string (py_v))
614 output = python_string_to_host_string (py_v);
616 gdbpy_print_stack ();
619 fputs_filtered (output, stream);
625 struct value *value = convert_value_from_python (py_v);
629 gdbpy_print_stack ();
630 error (_("Error while executing Python code."));
633 common_val_print (value, stream, recurse + 1, options, language);
636 if (is_map && i % 2 == 0)
637 fputs_filtered ("] = ", stream);
639 do_cleanups (inner_cleanup);
648 fputs_filtered ("\n", stream);
649 print_spaces_filtered (2 + 2 * recurse, stream);
651 fputs_filtered ("...", stream);
655 fputs_filtered ("\n", stream);
656 print_spaces_filtered (2 * recurse, stream);
658 fputs_filtered ("}", stream);
662 do_cleanups (cleanups);
666 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
667 int embedded_offset, CORE_ADDR address,
668 struct ui_file *stream, int recurse,
669 const struct value *val,
670 const struct value_print_options *options,
671 const struct language_defn *language)
673 struct gdbarch *gdbarch = get_type_arch (type);
674 PyObject *printer = NULL;
675 PyObject *val_obj = NULL;
678 struct cleanup *cleanups;
680 enum string_repr_result print_result;
681 cleanups = ensure_python_env (gdbarch, language);
683 /* Instantiate the printer. */
685 valaddr += embedded_offset;
686 value = value_from_contents_and_address (type, valaddr,
687 address + embedded_offset);
690 set_value_component_location (value, val);
691 /* set_value_component_location resets the address, so we may
692 need to set it again. */
693 if (VALUE_LVAL (value) != lval_internalvar
694 && VALUE_LVAL (value) != lval_internalvar_component
695 && VALUE_LVAL (value) != lval_computed)
696 set_value_address (value, address + embedded_offset);
699 val_obj = value_to_value_object (value);
703 /* Find the constructor. */
704 printer = find_pretty_printer (val_obj);
706 make_cleanup_py_decref (printer);
707 if (! printer || printer == Py_None)
710 /* If we are printing a map, we want some special formatting. */
711 hint = gdbpy_get_display_hint (printer);
712 make_cleanup (free_current_contents, &hint);
714 /* Print the section */
715 print_result = print_string_repr (printer, hint, stream, recurse,
716 options, language, gdbarch);
717 if (print_result != string_repr_error)
718 print_children (printer, hint, stream, recurse, options, language,
719 print_result == string_repr_none);
725 if (PyErr_Occurred ())
726 print_stack_unless_memory_error (stream);
727 do_cleanups (cleanups);
732 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
733 print object. It must have a 'to_string' method (but this is
734 checked by varobj, not here) which takes no arguments and
735 returns a string. The printer will return a value and in the case
736 of a Python string being returned, this function will return a
737 PyObject containing the string. For any other type, *REPLACEMENT is
738 set to the replacement value and this function returns NULL. On
739 error, *REPLACEMENT is set to NULL and this function also returns
742 apply_varobj_pretty_printer (PyObject *printer_obj,
743 struct value **replacement,
744 struct ui_file *stream)
746 PyObject *py_str = NULL;
749 py_str = pretty_print_one_value (printer_obj, replacement);
751 if (*replacement == NULL && py_str == NULL)
752 print_stack_unless_memory_error (stream);
757 /* Find a pretty-printer object for the varobj module. Returns a new
758 reference to the object if successful; returns NULL if not. VALUE
759 is the value for which a printer tests to determine if it
760 can pretty-print the value. */
762 gdbpy_get_varobj_pretty_printer (struct value *value)
765 PyObject *pretty_printer = NULL;
766 volatile struct gdb_exception except;
768 TRY_CATCH (except, RETURN_MASK_ALL)
770 value = value_copy (value);
772 GDB_PY_HANDLE_EXCEPTION (except);
774 val_obj = value_to_value_object (value);
778 pretty_printer = find_pretty_printer (val_obj);
780 return pretty_printer;
783 /* A Python function which wraps find_pretty_printer and instantiates
784 the resulting class. This accepts a Value argument and returns a
785 pretty printer instance, or None. This function is useful as an
786 argument to the MI command -var-set-visualizer. */
788 gdbpy_default_visualizer (PyObject *self, PyObject *args)
794 if (! PyArg_ParseTuple (args, "O", &val_obj))
796 value = value_object_to_value (val_obj);
799 PyErr_SetString (PyExc_TypeError,
800 _("Argument must be a gdb.Value."));
804 cons = find_pretty_printer (val_obj);
808 #else /* HAVE_PYTHON */
811 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
812 int embedded_offset, CORE_ADDR address,
813 struct ui_file *stream, int recurse,
814 const struct value *val,
815 const struct value_print_options *options,
816 const struct language_defn *language)
821 #endif /* HAVE_PYTHON */