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