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