2010-05-07 Michael Snyder <msnyder@vmware.com>
[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 /* 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
36 return NULL. */
37
38 static PyObject *
39 search_pp_list (PyObject *list, PyObject *value)
40 {
41 Py_ssize_t pp_list_size, list_index;
42 PyObject *function, *printer = NULL;
43
44 pp_list_size = PyList_Size (list);
45 for (list_index = 0; list_index < pp_list_size; list_index++)
46 {
47 function = PyList_GetItem (list, list_index);
48 if (! function)
49 return NULL;
50
51 printer = PyObject_CallFunctionObjArgs (function, value, NULL);
52 if (! printer)
53 return NULL;
54 else if (printer != Py_None)
55 return printer;
56
57 Py_DECREF (printer);
58 }
59
60 Py_RETURN_NONE;
61 }
62
63 /* Subroutine of find_pretty_printer to simplify it.
64 Look for a pretty-printer to print VALUE in all objfiles.
65 The result is NULL if there's an error and the search should be terminated.
66 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
67 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
68
69 static PyObject *
70 find_pretty_printer_from_objfiles (PyObject *value)
71 {
72 PyObject *pp_list;
73 PyObject *function;
74 struct objfile *obj;
75
76 ALL_OBJFILES (obj)
77 {
78 PyObject *objf = objfile_to_objfile_object (obj);
79 if (!objf)
80 {
81 /* Ignore the error and continue. */
82 PyErr_Clear ();
83 continue;
84 }
85
86 pp_list = objfpy_get_printers (objf, NULL);
87 function = search_pp_list (pp_list, value);
88 Py_XDECREF (pp_list);
89
90 /* If there is an error in any objfile list, abort the search and exit. */
91 if (! function)
92 return NULL;
93
94 if (function != Py_None)
95 return function;
96
97 Py_DECREF (function);
98 }
99
100 Py_RETURN_NONE;
101 }
102
103 /* Subroutine of find_pretty_printer to simplify it.
104 Look for a pretty-printer to print VALUE in the current program space.
105 The result is NULL if there's an error and the search should be terminated.
106 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
107 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
108
109 static PyObject *
110 find_pretty_printer_from_progspace (PyObject *value)
111 {
112 PyObject *pp_list;
113 PyObject *function;
114 PyObject *obj = pspace_to_pspace_object (current_program_space);
115
116 if (!obj)
117 return NULL;
118 pp_list = pspy_get_printers (obj, NULL);
119 function = search_pp_list (pp_list, value);
120 Py_XDECREF (pp_list);
121 return function;
122 }
123
124 /* Subroutine of find_pretty_printer to simplify it.
125 Look for a pretty-printer to print VALUE in the gdb module.
126 The result is NULL if there's an error and the search should be terminated.
127 The result is Py_None, suitably inc-ref'd, if no pretty-printer was found.
128 Otherwise the result is the pretty-printer function, suitably inc-ref'd. */
129
130 static PyObject *
131 find_pretty_printer_from_gdb (PyObject *value)
132 {
133 PyObject *pp_list;
134 PyObject *function;
135
136 /* Fetch the global pretty printer dictionary. */
137 if (! PyObject_HasAttrString (gdb_module, "pretty_printers"))
138 Py_RETURN_NONE;
139 pp_list = PyObject_GetAttrString (gdb_module, "pretty_printers");
140 if (pp_list == NULL || ! PyList_Check (pp_list))
141 {
142 Py_XDECREF (pp_list);
143 Py_RETURN_NONE;
144 }
145
146 function = search_pp_list (pp_list, value);
147 Py_XDECREF (pp_list);
148 return function;
149 }
150
151 /* Find the pretty-printing constructor function for VALUE. If no
152 pretty-printer exists, return None. If one exists, return a new
153 reference. On error, set the Python error and return NULL. */
154
155 static PyObject *
156 find_pretty_printer (PyObject *value)
157 {
158 PyObject *function;
159
160 /* Look at the pretty-printer dictionary for each objfile
161 in the current program-space. */
162 function = find_pretty_printer_from_objfiles (value);
163 if (function == NULL || function != Py_None)
164 return function;
165 Py_DECREF (function);
166
167 /* Look at the pretty-printer dictionary for the current program-space. */
168 function = find_pretty_printer_from_progspace (value);
169 if (function == NULL || function != Py_None)
170 return function;
171 Py_DECREF (function);
172
173 /* Look at the pretty-printer dictionary in the gdb module. */
174 function = find_pretty_printer_from_gdb (value);
175 return function;
176 }
177
178 /* Pretty-print a single value, via the printer object PRINTER.
179 If the function returns a string, a PyObject containing the string
180 is returned. If the function returns Py_NONE that means the pretty
181 printer returned the Python None as a value. Otherwise, if the
182 function returns a value, *OUT_VALUE is set to the value, and NULL
183 is returned. On error, *OUT_VALUE is set to NULL, and NULL is
184 returned. */
185
186 static PyObject *
187 pretty_print_one_value (PyObject *printer, struct value **out_value)
188 {
189 volatile struct gdb_exception except;
190 PyObject *result = NULL;
191
192 *out_value = NULL;
193 TRY_CATCH (except, RETURN_MASK_ALL)
194 {
195 result = PyObject_CallMethodObjArgs (printer, gdbpy_to_string_cst, NULL);
196 if (result)
197 {
198 if (! gdbpy_is_string (result) && ! gdbpy_is_lazy_string (result)
199 && result != Py_None)
200 {
201 *out_value = convert_value_from_python (result);
202 if (PyErr_Occurred ())
203 *out_value = NULL;
204 Py_DECREF (result);
205 result = NULL;
206 }
207 }
208 }
209
210 return result;
211 }
212
213 /* Return the display hint for the object printer, PRINTER. Return
214 NULL if there is no display_hint method, or if the method did not
215 return a string. On error, print stack trace and return NULL. On
216 success, return an xmalloc()d string. */
217 char *
218 gdbpy_get_display_hint (PyObject *printer)
219 {
220 PyObject *hint;
221 char *result = NULL;
222
223 if (! PyObject_HasAttr (printer, gdbpy_display_hint_cst))
224 return NULL;
225
226 hint = PyObject_CallMethodObjArgs (printer, gdbpy_display_hint_cst, NULL);
227 if (gdbpy_is_string (hint))
228 result = python_string_to_host_string (hint);
229 if (hint)
230 Py_DECREF (hint);
231 else
232 gdbpy_print_stack ();
233
234 return result;
235 }
236
237 /* Helper for apply_val_pretty_printer which calls to_string and
238 formats the result. If the value returnd is Py_None, nothing is
239 printed and the function returns a 1; in all other cases data is
240 printed as given by the pretty printer and the function returns 0.
241 */
242 static int
243 print_string_repr (PyObject *printer, const char *hint,
244 struct ui_file *stream, int recurse,
245 const struct value_print_options *options,
246 const struct language_defn *language,
247 struct gdbarch *gdbarch)
248 {
249 struct value *replacement = NULL;
250 PyObject *py_str = NULL;
251 int is_py_none = 0;
252
253 py_str = pretty_print_one_value (printer, &replacement);
254 if (py_str)
255 {
256 if (py_str == Py_None)
257 is_py_none = 1;
258 else
259 {
260 gdb_byte *output = NULL;
261 long length;
262 struct type *type;
263 char *encoding = NULL;
264 PyObject *string = NULL;
265 int is_lazy;
266
267 is_lazy = gdbpy_is_lazy_string (py_str);
268 if (is_lazy)
269 output = gdbpy_extract_lazy_string (py_str, &type, &length, &encoding);
270 else
271 {
272 string = python_string_to_target_python_string (py_str);
273 if (string)
274 {
275 output = PyString_AsString (string);
276 length = PyString_Size (string);
277 type = builtin_type (gdbarch)->builtin_char;
278 }
279 else
280 gdbpy_print_stack ();
281
282 }
283
284 if (output)
285 {
286 if (is_lazy || (hint && !strcmp (hint, "string")))
287 LA_PRINT_STRING (stream, type, output, length, encoding,
288 0, options);
289 else
290 fputs_filtered (output, stream);
291 }
292 else
293 gdbpy_print_stack ();
294
295 if (string)
296 Py_DECREF (string);
297 else
298 xfree (output);
299
300 xfree (encoding);
301 Py_DECREF (py_str);
302 }
303 }
304 else if (replacement)
305 {
306 struct value_print_options opts = *options;
307
308 opts.addressprint = 0;
309 common_val_print (replacement, stream, recurse, &opts, language);
310 }
311 else
312 gdbpy_print_stack ();
313
314 return is_py_none;
315 }
316
317 static void
318 py_restore_tstate (void *p)
319 {
320 PyFrameObject *frame = p;
321 PyThreadState *tstate = PyThreadState_GET ();
322 tstate->frame = frame;
323 }
324
325 /* Create a dummy PyFrameObject, needed to work around
326 a Python-2.4 bug with generators. */
327 static PyObject *
328 push_dummy_python_frame ()
329 {
330 PyObject *empty_string, *null_tuple, *globals;
331 PyCodeObject *code;
332 PyFrameObject *frame;
333 PyThreadState *tstate;
334
335 empty_string = PyString_FromString ("");
336 if (!empty_string)
337 return NULL;
338
339 null_tuple = PyTuple_New (0);
340 if (!null_tuple)
341 {
342 Py_DECREF (empty_string);
343 return NULL;
344 }
345
346 code = PyCode_New (0, /* argcount */
347 0, /* nlocals */
348 0, /* stacksize */
349 0, /* flags */
350 empty_string, /* code */
351 null_tuple, /* consts */
352 null_tuple, /* names */
353 null_tuple, /* varnames */
354 #if PYTHON_API_VERSION >= 1010
355 null_tuple, /* freevars */
356 null_tuple, /* cellvars */
357 #endif
358 empty_string, /* filename */
359 empty_string, /* name */
360 1, /* firstlineno */
361 empty_string /* lnotab */
362 );
363
364 Py_DECREF (empty_string);
365 Py_DECREF (null_tuple);
366
367 if (!code)
368 return NULL;
369
370 globals = PyDict_New ();
371 if (!globals)
372 {
373 Py_DECREF (code);
374 return NULL;
375 }
376
377 tstate = PyThreadState_GET ();
378
379 frame = PyFrame_New (tstate, code, globals, NULL);
380
381 Py_DECREF (globals);
382 Py_DECREF (code);
383
384 if (!frame)
385 return NULL;
386
387 tstate->frame = frame;
388 make_cleanup (py_restore_tstate, frame->f_back);
389 return (PyObject *) frame;
390 }
391
392 /* Helper for apply_val_pretty_printer that formats children of the
393 printer, if any exist. If is_py_none is true, then nothing has
394 been printed by to_string, and format output accordingly. */
395 static void
396 print_children (PyObject *printer, const char *hint,
397 struct ui_file *stream, int recurse,
398 const struct value_print_options *options,
399 const struct language_defn *language,
400 int is_py_none)
401 {
402 int is_map, is_array, done_flag, pretty;
403 unsigned int i;
404 PyObject *children, *iter, *frame;
405 struct cleanup *cleanups;
406
407 if (! PyObject_HasAttr (printer, gdbpy_children_cst))
408 return;
409
410 /* If we are printing a map or an array, we want some special
411 formatting. */
412 is_map = hint && ! strcmp (hint, "map");
413 is_array = hint && ! strcmp (hint, "array");
414
415 children = PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
416 NULL);
417 if (! children)
418 {
419 gdbpy_print_stack ();
420 return;
421 }
422
423 cleanups = make_cleanup_py_decref (children);
424
425 iter = PyObject_GetIter (children);
426 if (!iter)
427 {
428 gdbpy_print_stack ();
429 goto done;
430 }
431 make_cleanup_py_decref (iter);
432
433 /* Use the prettyprint_arrays option if we are printing an array,
434 and the pretty option otherwise. */
435 pretty = is_array ? options->prettyprint_arrays : options->pretty;
436
437 /* Manufacture a dummy Python frame to work around Python 2.4 bug,
438 where it insists on having a non-NULL tstate->frame when
439 a generator is called. */
440 frame = push_dummy_python_frame ();
441 if (!frame)
442 {
443 gdbpy_print_stack ();
444 goto done;
445 }
446 make_cleanup_py_decref (frame);
447
448 done_flag = 0;
449 for (i = 0; i < options->print_max; ++i)
450 {
451 PyObject *py_v, *item = PyIter_Next (iter);
452 char *name;
453 struct cleanup *inner_cleanup;
454
455 if (! item)
456 {
457 if (PyErr_Occurred ())
458 gdbpy_print_stack ();
459 /* Set a flag so we can know whether we printed all the
460 available elements. */
461 else
462 done_flag = 1;
463 break;
464 }
465
466 if (! PyArg_ParseTuple (item, "sO", &name, &py_v))
467 {
468 gdbpy_print_stack ();
469 Py_DECREF (item);
470 continue;
471 }
472 inner_cleanup = make_cleanup_py_decref (item);
473
474 /* Print initial "{". For other elements, there are three
475 cases:
476 1. Maps. Print a "," after each value element.
477 2. Arrays. Always print a ",".
478 3. Other. Always print a ",". */
479 if (i == 0)
480 {
481 if (is_py_none)
482 fputs_filtered ("{", stream);
483 else
484 fputs_filtered (" = {", stream);
485 }
486
487 else if (! is_map || i % 2 == 0)
488 fputs_filtered (pretty ? "," : ", ", stream);
489
490 /* In summary mode, we just want to print "= {...}" if there is
491 a value. */
492 if (options->summary)
493 {
494 /* This increment tricks the post-loop logic to print what
495 we want. */
496 ++i;
497 /* Likewise. */
498 pretty = 0;
499 break;
500 }
501
502 if (! is_map || i % 2 == 0)
503 {
504 if (pretty)
505 {
506 fputs_filtered ("\n", stream);
507 print_spaces_filtered (2 + 2 * recurse, stream);
508 }
509 else
510 wrap_here (n_spaces (2 + 2 *recurse));
511 }
512
513 if (is_map && i % 2 == 0)
514 fputs_filtered ("[", stream);
515 else if (is_array)
516 {
517 /* We print the index, not whatever the child method
518 returned as the name. */
519 if (options->print_array_indexes)
520 fprintf_filtered (stream, "[%d] = ", i);
521 }
522 else if (! is_map)
523 {
524 fputs_filtered (name, stream);
525 fputs_filtered (" = ", stream);
526 }
527
528 if (gdbpy_is_lazy_string (py_v) || gdbpy_is_string (py_v))
529 {
530 gdb_byte *output = NULL;
531
532 if (gdbpy_is_lazy_string (py_v))
533 {
534 struct type *type;
535 long length;
536 char *encoding = NULL;
537
538 output = gdbpy_extract_lazy_string (py_v, &type,
539 &length, &encoding);
540 if (!output)
541 gdbpy_print_stack ();
542 LA_PRINT_STRING (stream, type, output, length, encoding,
543 0, options);
544 xfree (encoding);
545 xfree (output);
546 }
547 else
548 {
549 output = python_string_to_host_string (py_v);
550 fputs_filtered (output, stream);
551 xfree (output);
552 }
553 }
554 else
555 {
556 struct value *value = convert_value_from_python (py_v);
557
558 if (value == NULL)
559 {
560 gdbpy_print_stack ();
561 error (_("Error while executing Python code."));
562 }
563 else
564 common_val_print (value, stream, recurse + 1, options, language);
565 }
566
567 if (is_map && i % 2 == 0)
568 fputs_filtered ("] = ", stream);
569
570 do_cleanups (inner_cleanup);
571 }
572
573 if (i)
574 {
575 if (!done_flag)
576 {
577 if (pretty)
578 {
579 fputs_filtered ("\n", stream);
580 print_spaces_filtered (2 + 2 * recurse, stream);
581 }
582 fputs_filtered ("...", stream);
583 }
584 if (pretty)
585 {
586 fputs_filtered ("\n", stream);
587 print_spaces_filtered (2 * recurse, stream);
588 }
589 fputs_filtered ("}", stream);
590 }
591
592 done:
593 do_cleanups (cleanups);
594 }
595
596 int
597 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
598 int embedded_offset, CORE_ADDR address,
599 struct ui_file *stream, int recurse,
600 const struct value_print_options *options,
601 const struct language_defn *language)
602 {
603 struct gdbarch *gdbarch = get_type_arch (type);
604 PyObject *printer = NULL;
605 PyObject *val_obj = NULL;
606 struct value *value;
607 char *hint = NULL;
608 struct cleanup *cleanups;
609 int result = 0;
610 int is_py_none = 0;
611 cleanups = ensure_python_env (gdbarch, language);
612
613 /* Instantiate the printer. */
614 if (valaddr)
615 valaddr += embedded_offset;
616 value = value_from_contents_and_address (type, valaddr,
617 address + embedded_offset);
618
619 val_obj = value_to_value_object (value);
620 if (! val_obj)
621 goto done;
622
623 /* Find the constructor. */
624 printer = find_pretty_printer (val_obj);
625 Py_DECREF (val_obj);
626 make_cleanup_py_decref (printer);
627 if (! printer || printer == Py_None)
628 goto done;
629
630 /* If we are printing a map, we want some special formatting. */
631 hint = gdbpy_get_display_hint (printer);
632 make_cleanup (free_current_contents, &hint);
633
634 /* Print the section */
635 is_py_none = print_string_repr (printer, hint, stream, recurse,
636 options, language, gdbarch);
637 print_children (printer, hint, stream, recurse, options, language,
638 is_py_none);
639
640 result = 1;
641
642
643 done:
644 if (PyErr_Occurred ())
645 gdbpy_print_stack ();
646 do_cleanups (cleanups);
647 return result;
648 }
649
650
651 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
652 print object. It must have a 'to_string' method (but this is
653 checked by varobj, not here) which takes no arguments and
654 returns a string. The printer will return a value and in the case
655 of a Python string being returned, this function will return a
656 PyObject containing the string. For any other type, *REPLACEMENT is
657 set to the replacement value and this function returns NULL. On
658 error, *REPLACEMENT is set to NULL and this function also returns
659 NULL. */
660 PyObject *
661 apply_varobj_pretty_printer (PyObject *printer_obj,
662 struct value **replacement)
663 {
664 PyObject *py_str = NULL;
665
666 *replacement = NULL;
667 py_str = pretty_print_one_value (printer_obj, replacement);
668
669 if (*replacement == NULL && py_str == NULL)
670 gdbpy_print_stack ();
671
672 return py_str;
673 }
674
675 /* Find a pretty-printer object for the varobj module. Returns a new
676 reference to the object if successful; returns NULL if not. VALUE
677 is the value for which a printer tests to determine if it
678 can pretty-print the value. */
679 PyObject *
680 gdbpy_get_varobj_pretty_printer (struct value *value)
681 {
682 PyObject *val_obj;
683 PyObject *pretty_printer = NULL;
684 volatile struct gdb_exception except;
685
686 TRY_CATCH (except, RETURN_MASK_ALL)
687 {
688 value = value_copy (value);
689 }
690 GDB_PY_HANDLE_EXCEPTION (except);
691
692 val_obj = value_to_value_object (value);
693 if (! val_obj)
694 return NULL;
695
696 pretty_printer = find_pretty_printer (val_obj);
697 Py_DECREF (val_obj);
698 return pretty_printer;
699 }
700
701 /* A Python function which wraps find_pretty_printer and instantiates
702 the resulting class. This accepts a Value argument and returns a
703 pretty printer instance, or None. This function is useful as an
704 argument to the MI command -var-set-visualizer. */
705 PyObject *
706 gdbpy_default_visualizer (PyObject *self, PyObject *args)
707 {
708 PyObject *val_obj;
709 PyObject *cons;
710 struct value *value;
711
712 if (! PyArg_ParseTuple (args, "O", &val_obj))
713 return NULL;
714 value = value_object_to_value (val_obj);
715 if (! value)
716 {
717 PyErr_SetString (PyExc_TypeError,
718 _("Argument must be a gdb.Value."));
719 return NULL;
720 }
721
722 cons = find_pretty_printer (val_obj);
723 return cons;
724 }
725
726 #else /* HAVE_PYTHON */
727
728 int
729 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
730 int embedded_offset, CORE_ADDR address,
731 struct ui_file *stream, int recurse,
732 const struct value_print_options *options,
733 const struct language_defn *language)
734 {
735 return 0;
736 }
737
738 #endif /* HAVE_PYTHON */
This page took 0.046395 seconds and 5 git commands to generate.