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