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 #ifndef IS_PY3K 354 355 /* Create a dummy PyFrameObject, needed to work around 356 a Python-2.4 bug with generators. */ 357 class dummy_python_frame 358 { 359 public: 360 361 dummy_python_frame (); 362 363 ~dummy_python_frame () 364 { 365 if (m_valid) 366 m_tstate->frame = m_saved_frame; 367 } 368 369 bool failed () const 370 { 371 return !m_valid; 372 } 373 374 private: 375 376 bool m_valid; 377 PyFrameObject *m_saved_frame; 378 gdbpy_ref<> m_frame; 379 PyThreadState *m_tstate; 380 }; 381 382 dummy_python_frame::dummy_python_frame () 383 : m_valid (false), 384 m_saved_frame (NULL), 385 m_tstate (NULL) 386 { 387 PyCodeObject *code; 388 PyFrameObject *frame; 389 390 gdbpy_ref<> empty_string (PyString_FromString ("")); 391 if (empty_string == NULL) 392 return; 393 394 gdbpy_ref<> null_tuple (PyTuple_New (0)); 395 if (null_tuple == NULL) 396 return; 397 398 code = PyCode_New (0, /* argcount */ 399 0, /* locals */ 400 0, /* stacksize */ 401 0, /* flags */ 402 empty_string.get (), /* code */ 403 null_tuple.get (), /* consts */ 404 null_tuple.get (), /* names */ 405 null_tuple.get (), /* varnames */ 406 #if PYTHON_API_VERSION >= 1010 407 null_tuple.get (), /* freevars */ 408 null_tuple.get (), /* cellvars */ 409 #endif 410 empty_string.get (), /* filename */ 411 empty_string.get (), /* name */ 412 1, /* firstlineno */ 413 empty_string.get () /* lnotab */ 414 ); 415 if (code == NULL) 416 return; 417 gdbpy_ref<> code_holder ((PyObject *) code); 418 419 gdbpy_ref<> globals (PyDict_New ()); 420 if (globals == NULL) 421 return; 422 423 m_tstate = PyThreadState_GET (); 424 frame = PyFrame_New (m_tstate, code, globals.get (), NULL); 425 if (frame == NULL) 426 return; 427 428 m_frame.reset ((PyObject *) frame); 429 m_tstate->frame = frame; 430 m_saved_frame = frame->f_back; 431 m_valid = true; 432 } 433 #endif 434 435 /* Helper for gdbpy_apply_val_pretty_printer that formats children of the 436 printer, if any exist. If is_py_none is true, then nothing has 437 been printed by to_string, and format output accordingly. */ 438 static void 439 print_children (PyObject *printer, const char *hint, 440 struct ui_file *stream, int recurse, 441 const struct value_print_options *options, 442 const struct language_defn *language, 443 int is_py_none) 444 { 445 int is_map, is_array, done_flag, pretty; 446 unsigned int i; 447 448 if (! PyObject_HasAttr (printer, gdbpy_children_cst)) 449 return; 450 451 /* If we are printing a map or an array, we want some special 452 formatting. */ 453 is_map = hint && ! strcmp (hint, "map"); 454 is_array = hint && ! strcmp (hint, "array"); 455 456 gdbpy_ref<> children (PyObject_CallMethodObjArgs (printer, gdbpy_children_cst, 457 NULL)); 458 if (children == NULL) 459 { 460 print_stack_unless_memory_error (stream); 461 return; 462 } 463 464 gdbpy_ref<> iter (PyObject_GetIter (children.get ())); 465 if (iter == NULL) 466 { 467 print_stack_unless_memory_error (stream); 468 return; 469 } 470 471 /* Use the prettyformat_arrays option if we are printing an array, 472 and the pretty option otherwise. */ 473 if (is_array) 474 pretty = options->prettyformat_arrays; 475 else 476 { 477 if (options->prettyformat == Val_prettyformat) 478 pretty = 1; 479 else 480 pretty = options->prettyformat_structs; 481 } 482 483 /* Manufacture a dummy Python frame to work around Python 2.4 bug, 484 where it insists on having a non-NULL tstate->frame when 485 a generator is called. */ 486 #ifndef IS_PY3K 487 dummy_python_frame frame; 488 if (frame.failed ()) 489 { 490 gdbpy_print_stack (); 491 return; 492 } 493 #endif 494 495 done_flag = 0; 496 for (i = 0; i < options->print_max; ++i) 497 { 498 PyObject *py_v; 499 const char *name; 500 501 gdbpy_ref<> item (PyIter_Next (iter.get ())); 502 if (item == NULL) 503 { 504 if (PyErr_Occurred ()) 505 print_stack_unless_memory_error (stream); 506 /* Set a flag so we can know whether we printed all the 507 available elements. */ 508 else 509 done_flag = 1; 510 break; 511 } 512 513 if (! PyTuple_Check (item.get ()) || PyTuple_Size (item.get ()) != 2) 514 { 515 PyErr_SetString (PyExc_TypeError, 516 _("Result of children iterator not a tuple" 517 " of two elements.")); 518 gdbpy_print_stack (); 519 continue; 520 } 521 if (! PyArg_ParseTuple (item.get (), "sO", &name, &py_v)) 522 { 523 /* The user won't necessarily get a stack trace here, so provide 524 more context. */ 525 if (gdbpy_print_python_errors_p ()) 526 fprintf_unfiltered (gdb_stderr, 527 _("Bad result from children iterator.\n")); 528 gdbpy_print_stack (); 529 continue; 530 } 531 532 /* Print initial "{". For other elements, there are three 533 cases: 534 1. Maps. Print a "," after each value element. 535 2. Arrays. Always print a ",". 536 3. Other. Always print a ",". */ 537 if (i == 0) 538 { 539 if (is_py_none) 540 fputs_filtered ("{", stream); 541 else 542 fputs_filtered (" = {", stream); 543 } 544 545 else if (! is_map || i % 2 == 0) 546 fputs_filtered (pretty ? "," : ", ", stream); 547 548 /* In summary mode, we just want to print "= {...}" if there is 549 a value. */ 550 if (options->summary) 551 { 552 /* This increment tricks the post-loop logic to print what 553 we want. */ 554 ++i; 555 /* Likewise. */ 556 pretty = 0; 557 break; 558 } 559 560 if (! is_map || i % 2 == 0) 561 { 562 if (pretty) 563 { 564 fputs_filtered ("\n", stream); 565 print_spaces_filtered (2 + 2 * recurse, stream); 566 } 567 else 568 wrap_here (n_spaces (2 + 2 *recurse)); 569 } 570 571 if (is_map && i % 2 == 0) 572 fputs_filtered ("[", stream); 573 else if (is_array) 574 { 575 /* We print the index, not whatever the child method 576 returned as the name. */ 577 if (options->print_array_indexes) 578 fprintf_filtered (stream, "[%d] = ", i); 579 } 580 else if (! is_map) 581 { 582 fputs_filtered (name, stream); 583 fputs_filtered (" = ", stream); 584 } 585 586 if (gdbpy_is_lazy_string (py_v)) 587 { 588 CORE_ADDR addr; 589 struct type *type; 590 long length; 591 gdb::unique_xmalloc_ptr<char> encoding; 592 struct value_print_options local_opts = *options; 593 594 gdbpy_extract_lazy_string (py_v, &addr, &type, &length, &encoding); 595 596 local_opts.addressprint = 0; 597 val_print_string (type, encoding.get (), addr, (int) length, stream, 598 &local_opts); 599 } 600 else if (gdbpy_is_string (py_v)) 601 { 602 gdb::unique_xmalloc_ptr<char> output; 603 604 output = python_string_to_host_string (py_v); 605 if (!output) 606 gdbpy_print_stack (); 607 else 608 fputs_filtered (output.get (), stream); 609 } 610 else 611 { 612 struct value *value = convert_value_from_python (py_v); 613 614 if (value == NULL) 615 { 616 gdbpy_print_stack (); 617 error (_("Error while executing Python code.")); 618 } 619 else 620 common_val_print (value, stream, recurse + 1, options, language); 621 } 622 623 if (is_map && i % 2 == 0) 624 fputs_filtered ("] = ", stream); 625 } 626 627 if (i) 628 { 629 if (!done_flag) 630 { 631 if (pretty) 632 { 633 fputs_filtered ("\n", stream); 634 print_spaces_filtered (2 + 2 * recurse, stream); 635 } 636 fputs_filtered ("...", stream); 637 } 638 if (pretty) 639 { 640 fputs_filtered ("\n", stream); 641 print_spaces_filtered (2 * recurse, stream); 642 } 643 fputs_filtered ("}", stream); 644 } 645 } 646 647 enum ext_lang_rc 648 gdbpy_apply_val_pretty_printer (const struct extension_language_defn *extlang, 649 struct type *type, 650 LONGEST embedded_offset, CORE_ADDR address, 651 struct ui_file *stream, int recurse, 652 struct value *val, 653 const struct value_print_options *options, 654 const struct language_defn *language) 655 { 656 struct gdbarch *gdbarch = get_type_arch (type); 657 struct value *value; 658 enum string_repr_result print_result; 659 660 if (value_lazy (val)) 661 value_fetch_lazy (val); 662 663 /* No pretty-printer support for unavailable values. */ 664 if (!value_bytes_available (val, embedded_offset, TYPE_LENGTH (type))) 665 return EXT_LANG_RC_NOP; 666 667 if (!gdb_python_initialized) 668 return EXT_LANG_RC_NOP; 669 670 gdbpy_enter enter_py (gdbarch, language); 671 672 /* Instantiate the printer. */ 673 value = value_from_component (val, type, embedded_offset); 674 675 gdbpy_ref<> val_obj (value_to_value_object (value)); 676 if (val_obj == NULL) 677 { 678 print_stack_unless_memory_error (stream); 679 return EXT_LANG_RC_ERROR; 680 } 681 682 /* Find the constructor. */ 683 gdbpy_ref<> printer (find_pretty_printer (val_obj.get ())); 684 if (printer == NULL) 685 { 686 print_stack_unless_memory_error (stream); 687 return EXT_LANG_RC_ERROR; 688 } 689 690 if (printer == Py_None) 691 return EXT_LANG_RC_NOP; 692 693 /* If we are printing a map, we want some special formatting. */ 694 gdb::unique_xmalloc_ptr<char> hint (gdbpy_get_display_hint (printer.get ())); 695 696 /* Print the section */ 697 print_result = print_string_repr (printer.get (), hint.get (), stream, 698 recurse, options, language, gdbarch); 699 if (print_result != string_repr_error) 700 print_children (printer.get (), hint.get (), stream, recurse, options, 701 language, print_result == string_repr_none); 702 703 if (PyErr_Occurred ()) 704 print_stack_unless_memory_error (stream); 705 return EXT_LANG_RC_OK; 706 } 707 708 709 /* Apply a pretty-printer for the varobj code. PRINTER_OBJ is the 710 print object. It must have a 'to_string' method (but this is 711 checked by varobj, not here) which takes no arguments and 712 returns a string. The printer will return a value and in the case 713 of a Python string being returned, this function will return a 714 PyObject containing the string. For any other type, *REPLACEMENT is 715 set to the replacement value and this function returns NULL. On 716 error, *REPLACEMENT is set to NULL and this function also returns 717 NULL. */ 718 gdbpy_ref<> 719 apply_varobj_pretty_printer (PyObject *printer_obj, 720 struct value **replacement, 721 struct ui_file *stream) 722 { 723 *replacement = NULL; 724 gdbpy_ref<> py_str = pretty_print_one_value (printer_obj, replacement); 725 726 if (*replacement == NULL && py_str == NULL) 727 print_stack_unless_memory_error (stream); 728 729 return py_str; 730 } 731 732 /* Find a pretty-printer object for the varobj module. Returns a new 733 reference to the object if successful; returns NULL if not. VALUE 734 is the value for which a printer tests to determine if it 735 can pretty-print the value. */ 736 gdbpy_ref<> 737 gdbpy_get_varobj_pretty_printer (struct value *value) 738 { 739 TRY 740 { 741 value = value_copy (value); 742 } 743 CATCH (except, RETURN_MASK_ALL) 744 { 745 GDB_PY_HANDLE_EXCEPTION (except); 746 } 747 END_CATCH 748 749 gdbpy_ref<> val_obj (value_to_value_object (value)); 750 if (val_obj == NULL) 751 return NULL; 752 753 return find_pretty_printer (val_obj.get ()); 754 } 755 756 /* A Python function which wraps find_pretty_printer and instantiates 757 the resulting class. This accepts a Value argument and returns a 758 pretty printer instance, or None. This function is useful as an 759 argument to the MI command -var-set-visualizer. */ 760 PyObject * 761 gdbpy_default_visualizer (PyObject *self, PyObject *args) 762 { 763 PyObject *val_obj; 764 struct value *value; 765 766 if (! PyArg_ParseTuple (args, "O", &val_obj)) 767 return NULL; 768 value = value_object_to_value (val_obj); 769 if (! value) 770 { 771 PyErr_SetString (PyExc_TypeError, 772 _("Argument must be a gdb.Value.")); 773 return NULL; 774 } 775 776 return find_pretty_printer (val_obj).release (); 777 } 778