gdb
[deliverable/binutils-gdb.git] / gdb / python / py-prettyprint.c
1 /* Python pretty-printing
2
3 Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
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.
11
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.
16
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/>. */
19
20 #include "defs.h"
21 #include "exceptions.h"
22 #include "objfiles.h"
23 #include "symtab.h"
24 #include "language.h"
25 #include "valprint.h"
26
27 #include "python.h"
28
29 #ifdef HAVE_PYTHON
30 #include "python-internal.h"
31
32 /* Return type of print_string_repr. */
33
34 enum string_repr_result
35 {
36 /* The string method returned None. */
37 string_repr_none,
38 /* The string method had an error. */
39 string_repr_error,
40 /* Everything ok. */
41 string_repr_ok
42 };
43
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
48 return NULL. */
49
50 static PyObject *
51 search_pp_list (PyObject *list, PyObject *value)
52 {
53 Py_ssize_t pp_list_size, list_index;
54 PyObject *function, *printer = NULL;
55
56 pp_list_size = PyList_Size (list);
57 for (list_index = 0; list_index < pp_list_size; list_index++)
58 {
59 function = PyList_GetItem (list, list_index);
60 if (! function)
61 return NULL;
62
63 /* Skip if disabled. */
64 if (PyObject_HasAttr (function, gdbpy_enabled_cst))
65 {
66 PyObject *attr = PyObject_GetAttr (function, gdbpy_enabled_cst);
67 int cmp;
68
69 if (!attr)
70 return NULL;
71 cmp = PyObject_IsTrue (attr);
72 if (cmp == -1)
73 return NULL;
74
75 if (!cmp)
76 continue;
77 }
78
79 printer = PyObject_CallFunctionObjArgs (function, value, NULL);
80 if (! printer)
81 return NULL;
82 else if (printer != Py_None)
83 return printer;
84
85 Py_DECREF (printer);
86 }
87
88 Py_RETURN_NONE;
89 }
90
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. */
96
97 static PyObject *
98 find_pretty_printer_from_objfiles (PyObject *value)
99 {
100 PyObject *pp_list;
101 PyObject *function;
102 struct objfile *obj;
103
104 ALL_OBJFILES (obj)
105 {
106 PyObject *objf = objfile_to_objfile_object (obj);
107 if (!objf)
108 {
109 /* Ignore the error and continue. */
110 PyErr_Clear ();
111 continue;
112 }
113
114 pp_list = objfpy_get_printers (objf, NULL);
115 function = search_pp_list (pp_list, value);
116 Py_XDECREF (pp_list);
117
118 /* If there is an error in any objfile list, abort the search and exit. */
119 if (! function)
120 return NULL;
121
122 if (function != Py_None)
123 return function;
124
125 Py_DECREF (function);
126 }
127
128 Py_RETURN_NONE;
129 }
130
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. */
136
137 static PyObject *
138 find_pretty_printer_from_progspace (PyObject *value)
139 {
140 PyObject *pp_list;
141 PyObject *function;
142 PyObject *obj = pspace_to_pspace_object (current_program_space);
143
144 if (!obj)
145 return NULL;
146 pp_list = pspy_get_printers (obj, NULL);
147 function = search_pp_list (pp_list, value);
148 Py_XDECREF (pp_list);
149 return function;
150 }
151
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. */
157
158 static PyObject *
159 find_pretty_printer_from_gdb (PyObject *value)
160 {
161 PyObject *pp_list;
162 PyObject *function;
163
164 /* Fetch the global pretty printer list. */
165 if (! PyObject_HasAttrString (gdb_module, "pretty_printers"))
166 Py_RETURN_NONE;
167 pp_list = PyObject_GetAttrString (gdb_module, "pretty_printers");
168 if (pp_list == NULL || ! PyList_Check (pp_list))
169 {
170 Py_XDECREF (pp_list);
171 Py_RETURN_NONE;
172 }
173
174 function = search_pp_list (pp_list, value);
175 Py_XDECREF (pp_list);
176 return function;
177 }
178
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. */
182
183 static PyObject *
184 find_pretty_printer (PyObject *value)
185 {
186 PyObject *function;
187
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)
192 return function;
193 Py_DECREF (function);
194
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)
198 return function;
199 Py_DECREF (function);
200
201 /* Look at the pretty-printer list in the gdb module. */
202 function = find_pretty_printer_from_gdb (value);
203 return function;
204 }
205
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. */
213
214 static PyObject *
215 pretty_print_one_value (PyObject *printer, struct value **out_value)
216 {
217 volatile struct gdb_exception except;
218 PyObject *result = NULL;
219
220 *out_value = NULL;
221 TRY_CATCH (except, RETURN_MASK_ALL)
222 {
223 result = PyObject_CallMethodObjArgs (printer, gdbpy_to_string_cst, NULL);
224 if (result)
225 {
226 if (! gdbpy_is_string (result) && ! gdbpy_is_lazy_string (result)
227 && result != Py_None)
228 {
229 *out_value = convert_value_from_python (result);
230 if (PyErr_Occurred ())
231 *out_value = NULL;
232 Py_DECREF (result);
233 result = NULL;
234 }
235 }
236 }
237
238 return result;
239 }
240
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. */
245 char *
246 gdbpy_get_display_hint (PyObject *printer)
247 {
248 PyObject *hint;
249 char *result = NULL;
250
251 if (! PyObject_HasAttr (printer, gdbpy_display_hint_cst))
252 return NULL;
253
254 hint = PyObject_CallMethodObjArgs (printer, gdbpy_display_hint_cst, NULL);
255 if (hint)
256 {
257 if (gdbpy_is_string (hint))
258 {
259 result = python_string_to_host_string (hint);
260 if (result == NULL)
261 gdbpy_print_stack ();
262 }
263 Py_DECREF (hint);
264 }
265 else
266 gdbpy_print_stack ();
267
268 return result;
269 }
270
271 /* A wrapper for gdbpy_print_stack that ignores MemoryError. */
272
273 static void
274 print_stack_unless_memory_error (struct ui_file *stream)
275 {
276 if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error))
277 {
278 struct cleanup *cleanup;
279 PyObject *type, *value, *trace;
280 char *msg;
281
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);
286
287 msg = gdbpy_exception_to_string (type, value);
288 make_cleanup (xfree, msg);
289
290 if (msg == NULL || *msg == '\0')
291 fprintf_filtered (stream, _("<error reading variable"));
292 else
293 fprintf_filtered (stream, _("<error reading variable: %s>"), msg);
294
295 do_cleanups (cleanup);
296 }
297 else
298 gdbpy_print_stack ();
299 }
300
301 /* Helper for apply_val_pretty_printer which calls to_string and
302 formats the result. */
303
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)
310 {
311 struct value *replacement = NULL;
312 PyObject *py_str = NULL;
313 enum string_repr_result result = string_repr_ok;
314
315 py_str = pretty_print_one_value (printer, &replacement);
316 if (py_str)
317 {
318 struct cleanup *cleanup = make_cleanup_py_decref (py_str);
319
320 if (py_str == Py_None)
321 result = string_repr_none;
322 else if (gdbpy_is_lazy_string (py_str))
323 {
324 CORE_ADDR addr;
325 long length;
326 struct type *type;
327 char *encoding = NULL;
328
329 make_cleanup (free_current_contents, &encoding);
330 gdbpy_extract_lazy_string (py_str, &addr, &type,
331 &length, &encoding);
332
333 val_print_string (type, encoding, addr, (int) length,
334 stream, options);
335 }
336 else
337 {
338 PyObject *string;
339
340 string = python_string_to_target_python_string (py_str);
341 if (string)
342 {
343 gdb_byte *output;
344 long length;
345 struct type *type;
346
347 make_cleanup_py_decref (string);
348 output = PyString_AsString (string);
349 length = PyString_Size (string);
350 type = builtin_type (gdbarch)->builtin_char;
351
352 if (hint && !strcmp (hint, "string"))
353 LA_PRINT_STRING (stream, type, output, length, NULL,
354 0, options);
355 else
356 fputs_filtered (output, stream);
357 }
358 else
359 {
360 result = string_repr_error;
361 print_stack_unless_memory_error (stream);
362 }
363 }
364
365 do_cleanups (cleanup);
366 }
367 else if (replacement)
368 {
369 struct value_print_options opts = *options;
370
371 opts.addressprint = 0;
372 common_val_print (replacement, stream, recurse, &opts, language);
373 }
374 else
375 {
376 result = string_repr_error;
377 print_stack_unless_memory_error (stream);
378 }
379
380 return result;
381 }
382
383 static void
384 py_restore_tstate (void *p)
385 {
386 PyFrameObject *frame = p;
387 PyThreadState *tstate = PyThreadState_GET ();
388
389 tstate->frame = frame;
390 }
391
392 /* Create a dummy PyFrameObject, needed to work around
393 a Python-2.4 bug with generators. */
394 static PyObject *
395 push_dummy_python_frame ()
396 {
397 PyObject *empty_string, *null_tuple, *globals;
398 PyCodeObject *code;
399 PyFrameObject *frame;
400 PyThreadState *tstate;
401
402 empty_string = PyString_FromString ("");
403 if (!empty_string)
404 return NULL;
405
406 null_tuple = PyTuple_New (0);
407 if (!null_tuple)
408 {
409 Py_DECREF (empty_string);
410 return NULL;
411 }
412
413 code = PyCode_New (0, /* argcount */
414 0, /* nlocals */
415 0, /* stacksize */
416 0, /* flags */
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 */
424 #endif
425 empty_string, /* filename */
426 empty_string, /* name */
427 1, /* firstlineno */
428 empty_string /* lnotab */
429 );
430
431 Py_DECREF (empty_string);
432 Py_DECREF (null_tuple);
433
434 if (!code)
435 return NULL;
436
437 globals = PyDict_New ();
438 if (!globals)
439 {
440 Py_DECREF (code);
441 return NULL;
442 }
443
444 tstate = PyThreadState_GET ();
445
446 frame = PyFrame_New (tstate, code, globals, NULL);
447
448 Py_DECREF (globals);
449 Py_DECREF (code);
450
451 if (!frame)
452 return NULL;
453
454 tstate->frame = frame;
455 make_cleanup (py_restore_tstate, frame->f_back);
456 return (PyObject *) frame;
457 }
458
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. */
462 static void
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,
467 int is_py_none)
468 {
469 int is_map, is_array, done_flag, pretty;
470 unsigned int i;
471 PyObject *children, *iter, *frame;
472 struct cleanup *cleanups;
473
474 if (! PyObject_HasAttr (printer, gdbpy_children_cst))
475 return;
476
477 /* If we are printing a map or an array, we want some special
478 formatting. */
479 is_map = hint && ! strcmp (hint, "map");
480 is_array = hint && ! strcmp (hint, "array");
481
482 children = PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
483 NULL);
484 if (! children)
485 {
486 print_stack_unless_memory_error (stream);
487 return;
488 }
489
490 cleanups = make_cleanup_py_decref (children);
491
492 iter = PyObject_GetIter (children);
493 if (!iter)
494 {
495 print_stack_unless_memory_error (stream);
496 goto done;
497 }
498 make_cleanup_py_decref (iter);
499
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;
503
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 ();
508 if (!frame)
509 {
510 gdbpy_print_stack ();
511 goto done;
512 }
513 make_cleanup_py_decref (frame);
514
515 done_flag = 0;
516 for (i = 0; i < options->print_max; ++i)
517 {
518 PyObject *py_v, *item = PyIter_Next (iter);
519 char *name;
520 struct cleanup *inner_cleanup;
521
522 if (! item)
523 {
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. */
528 else
529 done_flag = 1;
530 break;
531 }
532
533 if (! PyArg_ParseTuple (item, "sO", &name, &py_v))
534 {
535 gdbpy_print_stack ();
536 Py_DECREF (item);
537 continue;
538 }
539 inner_cleanup = make_cleanup_py_decref (item);
540
541 /* Print initial "{". For other elements, there are three
542 cases:
543 1. Maps. Print a "," after each value element.
544 2. Arrays. Always print a ",".
545 3. Other. Always print a ",". */
546 if (i == 0)
547 {
548 if (is_py_none)
549 fputs_filtered ("{", stream);
550 else
551 fputs_filtered (" = {", stream);
552 }
553
554 else if (! is_map || i % 2 == 0)
555 fputs_filtered (pretty ? "," : ", ", stream);
556
557 /* In summary mode, we just want to print "= {...}" if there is
558 a value. */
559 if (options->summary)
560 {
561 /* This increment tricks the post-loop logic to print what
562 we want. */
563 ++i;
564 /* Likewise. */
565 pretty = 0;
566 break;
567 }
568
569 if (! is_map || i % 2 == 0)
570 {
571 if (pretty)
572 {
573 fputs_filtered ("\n", stream);
574 print_spaces_filtered (2 + 2 * recurse, stream);
575 }
576 else
577 wrap_here (n_spaces (2 + 2 *recurse));
578 }
579
580 if (is_map && i % 2 == 0)
581 fputs_filtered ("[", stream);
582 else if (is_array)
583 {
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);
588 }
589 else if (! is_map)
590 {
591 fputs_filtered (name, stream);
592 fputs_filtered (" = ", stream);
593 }
594
595 if (gdbpy_is_lazy_string (py_v))
596 {
597 CORE_ADDR addr;
598 struct type *type;
599 long length;
600 char *encoding = NULL;
601
602 make_cleanup (free_current_contents, &encoding);
603 gdbpy_extract_lazy_string (py_v, &addr, &type, &length, &encoding);
604
605 val_print_string (type, encoding, addr, (int) length, stream,
606 options);
607
608 do_cleanups (inner_cleanup);
609 }
610 else if (gdbpy_is_string (py_v))
611 {
612 gdb_byte *output;
613
614 output = python_string_to_host_string (py_v);
615 if (!output)
616 gdbpy_print_stack ();
617 else
618 {
619 fputs_filtered (output, stream);
620 xfree (output);
621 }
622 }
623 else
624 {
625 struct value *value = convert_value_from_python (py_v);
626
627 if (value == NULL)
628 {
629 gdbpy_print_stack ();
630 error (_("Error while executing Python code."));
631 }
632 else
633 common_val_print (value, stream, recurse + 1, options, language);
634 }
635
636 if (is_map && i % 2 == 0)
637 fputs_filtered ("] = ", stream);
638
639 do_cleanups (inner_cleanup);
640 }
641
642 if (i)
643 {
644 if (!done_flag)
645 {
646 if (pretty)
647 {
648 fputs_filtered ("\n", stream);
649 print_spaces_filtered (2 + 2 * recurse, stream);
650 }
651 fputs_filtered ("...", stream);
652 }
653 if (pretty)
654 {
655 fputs_filtered ("\n", stream);
656 print_spaces_filtered (2 * recurse, stream);
657 }
658 fputs_filtered ("}", stream);
659 }
660
661 done:
662 do_cleanups (cleanups);
663 }
664
665 int
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)
672 {
673 struct gdbarch *gdbarch = get_type_arch (type);
674 PyObject *printer = NULL;
675 PyObject *val_obj = NULL;
676 struct value *value;
677 char *hint = NULL;
678 struct cleanup *cleanups;
679 int result = 0;
680 enum string_repr_result print_result;
681 cleanups = ensure_python_env (gdbarch, language);
682
683 /* Instantiate the printer. */
684 if (valaddr)
685 valaddr += embedded_offset;
686 value = value_from_contents_and_address (type, valaddr,
687 address + embedded_offset);
688 if (val != NULL)
689 {
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);
697 }
698
699 val_obj = value_to_value_object (value);
700 if (! val_obj)
701 goto done;
702
703 /* Find the constructor. */
704 printer = find_pretty_printer (val_obj);
705 Py_DECREF (val_obj);
706 make_cleanup_py_decref (printer);
707 if (! printer || printer == Py_None)
708 goto done;
709
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);
713
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);
720
721 result = 1;
722
723
724 done:
725 if (PyErr_Occurred ())
726 print_stack_unless_memory_error (stream);
727 do_cleanups (cleanups);
728 return result;
729 }
730
731
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
740 NULL. */
741 PyObject *
742 apply_varobj_pretty_printer (PyObject *printer_obj,
743 struct value **replacement,
744 struct ui_file *stream)
745 {
746 PyObject *py_str = NULL;
747
748 *replacement = NULL;
749 py_str = pretty_print_one_value (printer_obj, replacement);
750
751 if (*replacement == NULL && py_str == NULL)
752 print_stack_unless_memory_error (stream);
753
754 return py_str;
755 }
756
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. */
761 PyObject *
762 gdbpy_get_varobj_pretty_printer (struct value *value)
763 {
764 PyObject *val_obj;
765 PyObject *pretty_printer = NULL;
766 volatile struct gdb_exception except;
767
768 TRY_CATCH (except, RETURN_MASK_ALL)
769 {
770 value = value_copy (value);
771 }
772 GDB_PY_HANDLE_EXCEPTION (except);
773
774 val_obj = value_to_value_object (value);
775 if (! val_obj)
776 return NULL;
777
778 pretty_printer = find_pretty_printer (val_obj);
779 Py_DECREF (val_obj);
780 return pretty_printer;
781 }
782
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. */
787 PyObject *
788 gdbpy_default_visualizer (PyObject *self, PyObject *args)
789 {
790 PyObject *val_obj;
791 PyObject *cons;
792 struct value *value;
793
794 if (! PyArg_ParseTuple (args, "O", &val_obj))
795 return NULL;
796 value = value_object_to_value (val_obj);
797 if (! value)
798 {
799 PyErr_SetString (PyExc_TypeError,
800 _("Argument must be a gdb.Value."));
801 return NULL;
802 }
803
804 cons = find_pretty_printer (val_obj);
805 return cons;
806 }
807
808 #else /* HAVE_PYTHON */
809
810 int
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)
817 {
818 return 0;
819 }
820
821 #endif /* HAVE_PYTHON */
This page took 0.04695 seconds and 4 git commands to generate.