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