Remove Python 2.4 and 2.5 support
[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 #ifdef IS_PY3K
316 output = PyBytes_AS_STRING (string.get ());
317 length = PyBytes_GET_SIZE (string.get ());
318 #else
319 output = PyString_AsString (string.get ());
320 length = PyString_Size (string.get ());
321 #endif
322 type = builtin_type (gdbarch)->builtin_char;
323
324 if (hint && !strcmp (hint, "string"))
325 LA_PRINT_STRING (stream, type, (gdb_byte *) output,
326 length, NULL, 0, options);
327 else
328 fputs_filtered (output, stream);
329 }
330 else
331 {
332 result = string_repr_error;
333 print_stack_unless_memory_error (stream);
334 }
335 }
336 }
337 else if (replacement)
338 {
339 struct value_print_options opts = *options;
340
341 opts.addressprint = 0;
342 common_val_print (replacement, stream, recurse, &opts, language);
343 }
344 else
345 {
346 result = string_repr_error;
347 print_stack_unless_memory_error (stream);
348 }
349
350 return result;
351 }
352
353 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the
354 printer, if any exist. If is_py_none is true, then nothing has
355 been printed by to_string, and format output accordingly. */
356 static void
357 print_children (PyObject *printer, const char *hint,
358 struct ui_file *stream, int recurse,
359 const struct value_print_options *options,
360 const struct language_defn *language,
361 int is_py_none)
362 {
363 int is_map, is_array, done_flag, pretty;
364 unsigned int i;
365
366 if (! PyObject_HasAttr (printer, gdbpy_children_cst))
367 return;
368
369 /* If we are printing a map or an array, we want some special
370 formatting. */
371 is_map = hint && ! strcmp (hint, "map");
372 is_array = hint && ! strcmp (hint, "array");
373
374 gdbpy_ref<> children (PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
375 NULL));
376 if (children == NULL)
377 {
378 print_stack_unless_memory_error (stream);
379 return;
380 }
381
382 gdbpy_ref<> iter (PyObject_GetIter (children.get ()));
383 if (iter == NULL)
384 {
385 print_stack_unless_memory_error (stream);
386 return;
387 }
388
389 /* Use the prettyformat_arrays option if we are printing an array,
390 and the pretty option otherwise. */
391 if (is_array)
392 pretty = options->prettyformat_arrays;
393 else
394 {
395 if (options->prettyformat == Val_prettyformat)
396 pretty = 1;
397 else
398 pretty = options->prettyformat_structs;
399 }
400
401 done_flag = 0;
402 for (i = 0; i < options->print_max; ++i)
403 {
404 PyObject *py_v;
405 const char *name;
406
407 gdbpy_ref<> item (PyIter_Next (iter.get ()));
408 if (item == NULL)
409 {
410 if (PyErr_Occurred ())
411 print_stack_unless_memory_error (stream);
412 /* Set a flag so we can know whether we printed all the
413 available elements. */
414 else
415 done_flag = 1;
416 break;
417 }
418
419 if (! PyTuple_Check (item.get ()) || PyTuple_Size (item.get ()) != 2)
420 {
421 PyErr_SetString (PyExc_TypeError,
422 _("Result of children iterator not a tuple"
423 " of two elements."));
424 gdbpy_print_stack ();
425 continue;
426 }
427 if (! PyArg_ParseTuple (item.get (), "sO", &name, &py_v))
428 {
429 /* The user won't necessarily get a stack trace here, so provide
430 more context. */
431 if (gdbpy_print_python_errors_p ())
432 fprintf_unfiltered (gdb_stderr,
433 _("Bad result from children iterator.\n"));
434 gdbpy_print_stack ();
435 continue;
436 }
437
438 /* Print initial "{". For other elements, there are three
439 cases:
440 1. Maps. Print a "," after each value element.
441 2. Arrays. Always print a ",".
442 3. Other. Always print a ",". */
443 if (i == 0)
444 {
445 if (is_py_none)
446 fputs_filtered ("{", stream);
447 else
448 fputs_filtered (" = {", stream);
449 }
450
451 else if (! is_map || i % 2 == 0)
452 fputs_filtered (pretty ? "," : ", ", stream);
453
454 /* In summary mode, we just want to print "= {...}" if there is
455 a value. */
456 if (options->summary)
457 {
458 /* This increment tricks the post-loop logic to print what
459 we want. */
460 ++i;
461 /* Likewise. */
462 pretty = 0;
463 break;
464 }
465
466 if (! is_map || i % 2 == 0)
467 {
468 if (pretty)
469 {
470 fputs_filtered ("\n", stream);
471 print_spaces_filtered (2 + 2 * recurse, stream);
472 }
473 else
474 wrap_here (n_spaces (2 + 2 *recurse));
475 }
476
477 if (is_map && i % 2 == 0)
478 fputs_filtered ("[", stream);
479 else if (is_array)
480 {
481 /* We print the index, not whatever the child method
482 returned as the name. */
483 if (options->print_array_indexes)
484 fprintf_filtered (stream, "[%d] = ", i);
485 }
486 else if (! is_map)
487 {
488 fputs_filtered (name, stream);
489 fputs_filtered (" = ", stream);
490 }
491
492 if (gdbpy_is_lazy_string (py_v))
493 {
494 CORE_ADDR addr;
495 struct type *type;
496 long length;
497 gdb::unique_xmalloc_ptr<char> encoding;
498 struct value_print_options local_opts = *options;
499
500 gdbpy_extract_lazy_string (py_v, &addr, &type, &length, &encoding);
501
502 local_opts.addressprint = 0;
503 val_print_string (type, encoding.get (), addr, (int) length, stream,
504 &local_opts);
505 }
506 else if (gdbpy_is_string (py_v))
507 {
508 gdb::unique_xmalloc_ptr<char> output;
509
510 output = python_string_to_host_string (py_v);
511 if (!output)
512 gdbpy_print_stack ();
513 else
514 fputs_filtered (output.get (), stream);
515 }
516 else
517 {
518 struct value *value = convert_value_from_python (py_v);
519
520 if (value == NULL)
521 {
522 gdbpy_print_stack ();
523 error (_("Error while executing Python code."));
524 }
525 else
526 common_val_print (value, stream, recurse + 1, options, language);
527 }
528
529 if (is_map && i % 2 == 0)
530 fputs_filtered ("] = ", stream);
531 }
532
533 if (i)
534 {
535 if (!done_flag)
536 {
537 if (pretty)
538 {
539 fputs_filtered ("\n", stream);
540 print_spaces_filtered (2 + 2 * recurse, stream);
541 }
542 fputs_filtered ("...", stream);
543 }
544 if (pretty)
545 {
546 fputs_filtered ("\n", stream);
547 print_spaces_filtered (2 * recurse, stream);
548 }
549 fputs_filtered ("}", stream);
550 }
551 }
552
553 enum ext_lang_rc
554 gdbpy_apply_val_pretty_printer (const struct extension_language_defn *extlang,
555 struct type *type,
556 LONGEST embedded_offset, CORE_ADDR address,
557 struct ui_file *stream, int recurse,
558 struct value *val,
559 const struct value_print_options *options,
560 const struct language_defn *language)
561 {
562 struct gdbarch *gdbarch = get_type_arch (type);
563 struct value *value;
564 enum string_repr_result print_result;
565
566 if (value_lazy (val))
567 value_fetch_lazy (val);
568
569 /* No pretty-printer support for unavailable values. */
570 if (!value_bytes_available (val, embedded_offset, TYPE_LENGTH (type)))
571 return EXT_LANG_RC_NOP;
572
573 if (!gdb_python_initialized)
574 return EXT_LANG_RC_NOP;
575
576 gdbpy_enter enter_py (gdbarch, language);
577
578 /* Instantiate the printer. */
579 value = value_from_component (val, type, embedded_offset);
580
581 gdbpy_ref<> val_obj (value_to_value_object (value));
582 if (val_obj == NULL)
583 {
584 print_stack_unless_memory_error (stream);
585 return EXT_LANG_RC_ERROR;
586 }
587
588 /* Find the constructor. */
589 gdbpy_ref<> printer (find_pretty_printer (val_obj.get ()));
590 if (printer == NULL)
591 {
592 print_stack_unless_memory_error (stream);
593 return EXT_LANG_RC_ERROR;
594 }
595
596 if (printer == Py_None)
597 return EXT_LANG_RC_NOP;
598
599 /* If we are printing a map, we want some special formatting. */
600 gdb::unique_xmalloc_ptr<char> hint (gdbpy_get_display_hint (printer.get ()));
601
602 /* Print the section */
603 print_result = print_string_repr (printer.get (), hint.get (), stream,
604 recurse, options, language, gdbarch);
605 if (print_result != string_repr_error)
606 print_children (printer.get (), hint.get (), stream, recurse, options,
607 language, print_result == string_repr_none);
608
609 if (PyErr_Occurred ())
610 print_stack_unless_memory_error (stream);
611 return EXT_LANG_RC_OK;
612 }
613
614
615 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the
616 print object. It must have a 'to_string' method (but this is
617 checked by varobj, not here) which takes no arguments and
618 returns a string. The printer will return a value and in the case
619 of a Python string being returned, this function will return a
620 PyObject containing the string. For any other type, *REPLACEMENT is
621 set to the replacement value and this function returns NULL. On
622 error, *REPLACEMENT is set to NULL and this function also returns
623 NULL. */
624 gdbpy_ref<>
625 apply_varobj_pretty_printer (PyObject *printer_obj,
626 struct value **replacement,
627 struct ui_file *stream)
628 {
629 *replacement = NULL;
630 gdbpy_ref<> py_str = pretty_print_one_value (printer_obj, replacement);
631
632 if (*replacement == NULL && py_str == NULL)
633 print_stack_unless_memory_error (stream);
634
635 return py_str;
636 }
637
638 /* Find a pretty-printer object for the varobj module. Returns a new
639 reference to the object if successful; returns NULL if not. VALUE
640 is the value for which a printer tests to determine if it
641 can pretty-print the value. */
642 gdbpy_ref<>
643 gdbpy_get_varobj_pretty_printer (struct value *value)
644 {
645 TRY
646 {
647 value = value_copy (value);
648 }
649 CATCH (except, RETURN_MASK_ALL)
650 {
651 GDB_PY_HANDLE_EXCEPTION (except);
652 }
653 END_CATCH
654
655 gdbpy_ref<> val_obj (value_to_value_object (value));
656 if (val_obj == NULL)
657 return NULL;
658
659 return find_pretty_printer (val_obj.get ());
660 }
661
662 /* A Python function which wraps find_pretty_printer and instantiates
663 the resulting class. This accepts a Value argument and returns a
664 pretty printer instance, or None. This function is useful as an
665 argument to the MI command -var-set-visualizer. */
666 PyObject *
667 gdbpy_default_visualizer (PyObject *self, PyObject *args)
668 {
669 PyObject *val_obj;
670 struct value *value;
671
672 if (! PyArg_ParseTuple (args, "O", &val_obj))
673 return NULL;
674 value = value_object_to_value (val_obj);
675 if (! value)
676 {
677 PyErr_SetString (PyExc_TypeError,
678 _("Argument must be a gdb.Value."));
679 return NULL;
680 }
681
682 return find_pretty_printer (val_obj).release ();
683 }