1 /* gdb commands implemented in Python 2 3 Copyright (C) 2008-2023 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 21 #include "defs.h" 22 #include "arch-utils.h" 23 #include "value.h" 24 #include "python-internal.h" 25 #include "charset.h" 26 #include "gdbcmd.h" 27 #include "cli/cli-decode.h" 28 #include "completer.h" 29 #include "language.h" 30 31 /* Struct representing built-in completion types. */ 32 struct cmdpy_completer 33 { 34 /* Python symbol name. */ 35 const char *name; 36 /* Completion function. */ 37 completer_ftype *completer; 38 }; 39 40 static const struct cmdpy_completer completers[] = 41 { 42 { "COMPLETE_NONE", noop_completer }, 43 { "COMPLETE_FILENAME", filename_completer }, 44 { "COMPLETE_LOCATION", location_completer }, 45 { "COMPLETE_COMMAND", command_completer }, 46 { "COMPLETE_SYMBOL", symbol_completer }, 47 { "COMPLETE_EXPRESSION", expression_completer }, 48 }; 49 50 #define N_COMPLETERS (sizeof (completers) / sizeof (completers[0])) 51 52 /* A gdb command. For the time being only ordinary commands (not 53 set/show commands) are allowed. */ 54 struct cmdpy_object 55 { 56 PyObject_HEAD 57 58 /* The corresponding gdb command object, or NULL if the command is 59 no longer installed. */ 60 struct cmd_list_element *command; 61 62 /* A prefix command requires storage for a list of its sub-commands. 63 A pointer to this is passed to add_prefix_command, and to add_cmd 64 for sub-commands of that prefix. If this Command is not a prefix 65 command, then this field is unused. */ 66 struct cmd_list_element *sub_list; 67 }; 68 69 extern PyTypeObject cmdpy_object_type 70 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("cmdpy_object"); 71 72 /* Constants used by this module. */ 73 static PyObject *invoke_cst; 74 static PyObject *complete_cst; 75 76 77 78 /* Python function which wraps dont_repeat. */ 79 static PyObject * 80 cmdpy_dont_repeat (PyObject *self, PyObject *args) 81 { 82 dont_repeat (); 83 Py_RETURN_NONE; 84 } 85 86 87 88 /* Called if the gdb cmd_list_element is destroyed. */ 89 90 static void 91 cmdpy_destroyer (struct cmd_list_element *self, void *context) 92 { 93 gdbpy_enter enter_py; 94 95 /* Release our hold on the command object. */ 96 gdbpy_ref<cmdpy_object> cmd ((cmdpy_object *) context); 97 cmd->command = NULL; 98 } 99 100 /* Called by gdb to invoke the command. */ 101 102 static void 103 cmdpy_function (const char *args, int from_tty, cmd_list_element *command) 104 { 105 cmdpy_object *obj = (cmdpy_object *) command->context (); 106 107 gdbpy_enter enter_py; 108 109 if (! obj) 110 error (_("Invalid invocation of Python command object.")); 111 if (! PyObject_HasAttr ((PyObject *) obj, invoke_cst)) 112 { 113 if (obj->command->is_prefix ()) 114 { 115 /* A prefix command does not need an invoke method. */ 116 return; 117 } 118 error (_("Python command object missing 'invoke' method.")); 119 } 120 121 if (! args) 122 args = ""; 123 gdbpy_ref<> argobj (PyUnicode_Decode (args, strlen (args), host_charset (), 124 NULL)); 125 if (argobj == NULL) 126 { 127 gdbpy_print_stack (); 128 error (_("Could not convert arguments to Python string.")); 129 } 130 131 gdbpy_ref<> ttyobj (PyBool_FromLong (from_tty)); 132 gdbpy_ref<> result (PyObject_CallMethodObjArgs ((PyObject *) obj, invoke_cst, 133 argobj.get (), ttyobj.get (), 134 NULL)); 135 136 if (result == NULL) 137 gdbpy_handle_exception (); 138 } 139 140 /* Helper function for the Python command completers (both "pure" 141 completer and brkchar handler). This function takes COMMAND, TEXT 142 and WORD and tries to call the Python method for completion with 143 these arguments. 144 145 This function is usually called twice: once when we are figuring out 146 the break characters to be used, and another to perform the real 147 completion itself. The reason for this two step dance is that we 148 need to know the set of "brkchars" to use early on, before we 149 actually try to perform the completion. But if a Python command 150 supplies a "complete" method then we have to call that method 151 first: it may return as its result the kind of completion to 152 perform and that will in turn specify which brkchars to use. IOW, 153 we need the result of the "complete" method before we actually 154 perform the completion. The only situation when this function is 155 not called twice is when the user uses the "complete" command: in 156 this scenario, there is no call to determine the "brkchars". 157 158 Ideally, it would be nice to cache the result of the first call (to 159 determine the "brkchars") and return this value directly in the 160 second call (to perform the actual completion). However, due to 161 the peculiarity of the "complete" command mentioned above, it is 162 possible to put GDB in a bad state if you perform a TAB-completion 163 and then a "complete"-completion sequentially. Therefore, we just 164 recalculate everything twice for TAB-completions. 165 166 This function returns a reference to the PyObject representing the 167 Python method call. */ 168 169 static gdbpy_ref<> 170 cmdpy_completer_helper (struct cmd_list_element *command, 171 const char *text, const char *word) 172 { 173 cmdpy_object *obj = (cmdpy_object *) command->context (); 174 175 if (obj == NULL) 176 error (_("Invalid invocation of Python command object.")); 177 if (!PyObject_HasAttr ((PyObject *) obj, complete_cst)) 178 { 179 /* If there is no complete method, don't error. */ 180 return NULL; 181 } 182 183 gdbpy_ref<> textobj (PyUnicode_Decode (text, strlen (text), host_charset (), 184 NULL)); 185 if (textobj == NULL) 186 error (_("Could not convert argument to Python string.")); 187 188 gdbpy_ref<> wordobj; 189 if (word == NULL) 190 { 191 /* "brkchars" phase. */ 192 wordobj = gdbpy_ref<>::new_reference (Py_None); 193 } 194 else 195 { 196 wordobj.reset (PyUnicode_Decode (word, strlen (word), host_charset (), 197 NULL)); 198 if (wordobj == NULL) 199 error (_("Could not convert argument to Python string.")); 200 } 201 202 gdbpy_ref<> resultobj (PyObject_CallMethodObjArgs ((PyObject *) obj, 203 complete_cst, 204 textobj.get (), 205 wordobj.get (), NULL)); 206 if (resultobj == NULL) 207 { 208 /* Just swallow errors here. */ 209 PyErr_Clear (); 210 } 211 212 return resultobj; 213 } 214 215 /* Python function called to determine the break characters of a 216 certain completer. We are only interested in knowing if the 217 completer registered by the user will return one of the integer 218 codes (see COMPLETER_* symbols). */ 219 220 static void 221 cmdpy_completer_handle_brkchars (struct cmd_list_element *command, 222 completion_tracker &tracker, 223 const char *text, const char *word) 224 { 225 gdbpy_enter enter_py; 226 227 /* Calling our helper to obtain a reference to the PyObject of the Python 228 function. */ 229 gdbpy_ref<> resultobj = cmdpy_completer_helper (command, text, word); 230 231 /* Check if there was an error. */ 232 if (resultobj == NULL) 233 return; 234 235 if (PyLong_Check (resultobj.get ())) 236 { 237 /* User code may also return one of the completion constants, 238 thus requesting that sort of completion. We are only 239 interested in this kind of return. */ 240 long value; 241 242 if (!gdb_py_int_as_long (resultobj.get (), &value)) 243 { 244 /* Ignore. */ 245 PyErr_Clear (); 246 } 247 else if (value >= 0 && value < (long) N_COMPLETERS) 248 { 249 completer_handle_brkchars_ftype *brkchars_fn; 250 251 /* This is the core of this function. Depending on which 252 completer type the Python function returns, we have to 253 adjust the break characters accordingly. */ 254 brkchars_fn = (completer_handle_brkchars_func_for_completer 255 (completers[value].completer)); 256 brkchars_fn (command, tracker, text, word); 257 } 258 } 259 } 260 261 /* Called by gdb for command completion. */ 262 263 static void 264 cmdpy_completer (struct cmd_list_element *command, 265 completion_tracker &tracker, 266 const char *text, const char *word) 267 { 268 gdbpy_enter enter_py; 269 270 /* Calling our helper to obtain a reference to the PyObject of the Python 271 function. */ 272 gdbpy_ref<> resultobj = cmdpy_completer_helper (command, text, word); 273 274 /* If the result object of calling the Python function is NULL, it 275 means that there was an error. In this case, just give up. */ 276 if (resultobj == NULL) 277 return; 278 279 if (PyLong_Check (resultobj.get ())) 280 { 281 /* User code may also return one of the completion constants, 282 thus requesting that sort of completion. */ 283 long value; 284 285 if (! gdb_py_int_as_long (resultobj.get (), &value)) 286 { 287 /* Ignore. */ 288 PyErr_Clear (); 289 } 290 else if (value >= 0 && value < (long) N_COMPLETERS) 291 completers[value].completer (command, tracker, text, word); 292 } 293 else 294 { 295 gdbpy_ref<> iter (PyObject_GetIter (resultobj.get ())); 296 297 if (iter == NULL) 298 return; 299 300 bool got_matches = false; 301 while (true) 302 { 303 gdbpy_ref<> elt (PyIter_Next (iter.get ())); 304 if (elt == NULL) 305 break; 306 307 if (! gdbpy_is_string (elt.get ())) 308 { 309 /* Skip problem elements. */ 310 continue; 311 } 312 gdb::unique_xmalloc_ptr<char> 313 item (python_string_to_host_string (elt.get ())); 314 if (item == NULL) 315 { 316 /* Skip problem elements. */ 317 PyErr_Clear (); 318 continue; 319 } 320 tracker.add_completion (std::move (item)); 321 got_matches = true; 322 } 323 324 /* If we got some results, ignore problems. Otherwise, report 325 the problem. */ 326 if (got_matches && PyErr_Occurred ()) 327 PyErr_Clear (); 328 } 329 } 330 331 /* Helper for cmdpy_init which locates the command list to use and 332 pulls out the command name. 333 334 NAME is the command name list. The final word in the list is the 335 name of the new command. All earlier words must be existing prefix 336 commands. 337 338 *BASE_LIST is set to the final prefix command's list of 339 *sub-commands. 340 341 START_LIST is the list in which the search starts. 342 343 This function returns the name of the new command. On error sets the Python 344 error and returns NULL. */ 345 346 gdb::unique_xmalloc_ptr<char> 347 gdbpy_parse_command_name (const char *name, 348 struct cmd_list_element ***base_list, 349 struct cmd_list_element **start_list) 350 { 351 struct cmd_list_element *elt; 352 int len = strlen (name); 353 int i, lastchar; 354 const char *prefix_text2; 355 356 /* Skip trailing whitespace. */ 357 for (i = len - 1; i >= 0 && (name[i] == ' ' || name[i] == '\t'); --i) 358 ; 359 if (i < 0) 360 { 361 PyErr_SetString (PyExc_RuntimeError, _("No command name found.")); 362 return NULL; 363 } 364 lastchar = i; 365 366 /* Find first character of the final word. */ 367 for (; i > 0 && valid_cmd_char_p (name[i - 1]); --i) 368 ; 369 370 gdb::unique_xmalloc_ptr<char> result ((char *) xmalloc (lastchar - i + 2)); 371 memcpy (result.get (), &name[i], lastchar - i + 1); 372 result.get ()[lastchar - i + 1] = '\0'; 373 374 /* Skip whitespace again. */ 375 for (--i; i >= 0 && (name[i] == ' ' || name[i] == '\t'); --i) 376 ; 377 if (i < 0) 378 { 379 *base_list = start_list; 380 return result; 381 } 382 383 std::string prefix_text (name, i + 1); 384 385 prefix_text2 = prefix_text.c_str (); 386 elt = lookup_cmd_1 (&prefix_text2, *start_list, NULL, NULL, 1); 387 if (elt == NULL || elt == CMD_LIST_AMBIGUOUS) 388 { 389 PyErr_Format (PyExc_RuntimeError, _("Could not find command prefix %s."), 390 prefix_text.c_str ()); 391 return NULL; 392 } 393 394 if (elt->is_prefix ()) 395 { 396 *base_list = elt->subcommands; 397 return result; 398 } 399 400 PyErr_Format (PyExc_RuntimeError, _("'%s' is not a prefix command."), 401 prefix_text.c_str ()); 402 return NULL; 403 } 404 405 /* Object initializer; sets up gdb-side structures for command. 406 407 Use: __init__(NAME, COMMAND_CLASS [, COMPLETER_CLASS][, PREFIX]]). 408 409 NAME is the name of the command. It may consist of multiple words, 410 in which case the final word is the name of the new command, and 411 earlier words must be prefix commands. 412 413 COMMAND_CLASS is the kind of command. It should be one of the COMMAND_* 414 constants defined in the gdb module. 415 416 COMPLETER_CLASS is the kind of completer. If not given, the 417 "complete" method will be used. Otherwise, it should be one of the 418 COMPLETE_* constants defined in the gdb module. 419 420 If PREFIX is True, then this command is a prefix command. 421 422 The documentation for the command is taken from the doc string for 423 the python class. */ 424 425 static int 426 cmdpy_init (PyObject *self, PyObject *args, PyObject *kw) 427 { 428 cmdpy_object *obj = (cmdpy_object *) self; 429 const char *name; 430 int cmdtype; 431 int completetype = -1; 432 struct cmd_list_element **cmd_list; 433 static const char *keywords[] = { "name", "command_class", "completer_class", 434 "prefix", NULL }; 435 PyObject *is_prefix_obj = NULL; 436 bool is_prefix = false; 437 438 if (obj->command) 439 { 440 /* Note: this is apparently not documented in Python. We return 441 0 for success, -1 for failure. */ 442 PyErr_Format (PyExc_RuntimeError, 443 _("Command object already initialized.")); 444 return -1; 445 } 446 447 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "si|iO", 448 keywords, &name, &cmdtype, 449 &completetype, &is_prefix_obj)) 450 return -1; 451 452 if (cmdtype != no_class && cmdtype != class_run 453 && cmdtype != class_vars && cmdtype != class_stack 454 && cmdtype != class_files && cmdtype != class_support 455 && cmdtype != class_info && cmdtype != class_breakpoint 456 && cmdtype != class_trace && cmdtype != class_obscure 457 && cmdtype != class_maintenance && cmdtype != class_user 458 && cmdtype != class_tui) 459 { 460 PyErr_Format (PyExc_RuntimeError, _("Invalid command class argument.")); 461 return -1; 462 } 463 464 if (completetype < -1 || completetype >= (int) N_COMPLETERS) 465 { 466 PyErr_Format (PyExc_RuntimeError, 467 _("Invalid completion type argument.")); 468 return -1; 469 } 470 471 gdb::unique_xmalloc_ptr<char> cmd_name 472 = gdbpy_parse_command_name (name, &cmd_list, &cmdlist); 473 if (cmd_name == nullptr) 474 return -1; 475 476 if (is_prefix_obj != NULL) 477 { 478 int cmp = PyObject_IsTrue (is_prefix_obj); 479 if (cmp < 0) 480 return -1; 481 482 is_prefix = cmp > 0; 483 } 484 485 gdb::unique_xmalloc_ptr<char> docstring = nullptr; 486 if (PyObject_HasAttr (self, gdbpy_doc_cst)) 487 { 488 gdbpy_ref<> ds_obj (PyObject_GetAttr (self, gdbpy_doc_cst)); 489 490 if (ds_obj != NULL && gdbpy_is_string (ds_obj.get ())) 491 { 492 docstring = python_string_to_host_string (ds_obj.get ()); 493 if (docstring == nullptr) 494 return -1; 495 docstring = gdbpy_fix_doc_string_indentation (std::move (docstring)); 496 } 497 } 498 if (docstring == nullptr) 499 docstring = make_unique_xstrdup (_("This command is not documented.")); 500 501 gdbpy_ref<> self_ref = gdbpy_ref<>::new_reference (self); 502 503 try 504 { 505 struct cmd_list_element *cmd; 506 507 if (is_prefix) 508 { 509 int allow_unknown; 510 511 /* If we have our own "invoke" method, then allow unknown 512 sub-commands. */ 513 allow_unknown = PyObject_HasAttr (self, invoke_cst); 514 cmd = add_prefix_cmd (cmd_name.get (), 515 (enum command_class) cmdtype, 516 NULL, docstring.release (), &obj->sub_list, 517 allow_unknown, cmd_list); 518 } 519 else 520 cmd = add_cmd (cmd_name.get (), (enum command_class) cmdtype, 521 docstring.release (), cmd_list); 522 523 /* If successful, the above takes ownership of the name, since we set 524 name_allocated, so release it. */ 525 cmd_name.release (); 526 527 /* There appears to be no API to set this. */ 528 cmd->func = cmdpy_function; 529 cmd->destroyer = cmdpy_destroyer; 530 cmd->doc_allocated = 1; 531 cmd->name_allocated = 1; 532 533 obj->command = cmd; 534 cmd->set_context (self_ref.release ()); 535 set_cmd_completer (cmd, ((completetype == -1) ? cmdpy_completer 536 : completers[completetype].completer)); 537 if (completetype == -1) 538 set_cmd_completer_handle_brkchars (cmd, 539 cmdpy_completer_handle_brkchars); 540 } 541 catch (const gdb_exception &except) 542 { 543 gdbpy_convert_exception (except); 544 return -1; 545 } 546 547 return 0; 548 } 549 550 551 552 /* Initialize the 'commands' code. */ 553 554 int 555 gdbpy_initialize_commands (void) 556 { 557 int i; 558 559 cmdpy_object_type.tp_new = PyType_GenericNew; 560 if (PyType_Ready (&cmdpy_object_type) < 0) 561 return -1; 562 563 /* Note: alias and user are special. */ 564 if (PyModule_AddIntConstant (gdb_module, "COMMAND_NONE", no_class) < 0 565 || PyModule_AddIntConstant (gdb_module, "COMMAND_RUNNING", class_run) < 0 566 || PyModule_AddIntConstant (gdb_module, "COMMAND_DATA", class_vars) < 0 567 || PyModule_AddIntConstant (gdb_module, "COMMAND_STACK", class_stack) < 0 568 || PyModule_AddIntConstant (gdb_module, "COMMAND_FILES", class_files) < 0 569 || PyModule_AddIntConstant (gdb_module, "COMMAND_SUPPORT", 570 class_support) < 0 571 || PyModule_AddIntConstant (gdb_module, "COMMAND_STATUS", class_info) < 0 572 || PyModule_AddIntConstant (gdb_module, "COMMAND_BREAKPOINTS", 573 class_breakpoint) < 0 574 || PyModule_AddIntConstant (gdb_module, "COMMAND_TRACEPOINTS", 575 class_trace) < 0 576 || PyModule_AddIntConstant (gdb_module, "COMMAND_OBSCURE", 577 class_obscure) < 0 578 || PyModule_AddIntConstant (gdb_module, "COMMAND_MAINTENANCE", 579 class_maintenance) < 0 580 || PyModule_AddIntConstant (gdb_module, "COMMAND_USER", class_user) < 0 581 || PyModule_AddIntConstant (gdb_module, "COMMAND_TUI", class_tui) < 0) 582 return -1; 583 584 for (i = 0; i < N_COMPLETERS; ++i) 585 { 586 if (PyModule_AddIntConstant (gdb_module, completers[i].name, i) < 0) 587 return -1; 588 } 589 590 if (gdb_pymodule_addobject (gdb_module, "Command", 591 (PyObject *) &cmdpy_object_type) < 0) 592 return -1; 593 594 invoke_cst = PyUnicode_FromString ("invoke"); 595 if (invoke_cst == NULL) 596 return -1; 597 complete_cst = PyUnicode_FromString ("complete"); 598 if (complete_cst == NULL) 599 return -1; 600 601 return 0; 602 } 603 604 605 606 static PyMethodDef cmdpy_object_methods[] = 607 { 608 { "dont_repeat", cmdpy_dont_repeat, METH_NOARGS, 609 "Prevent command repetition when user enters empty line." }, 610 611 { 0 } 612 }; 613 614 PyTypeObject cmdpy_object_type = 615 { 616 PyVarObject_HEAD_INIT (NULL, 0) 617 "gdb.Command", /*tp_name*/ 618 sizeof (cmdpy_object), /*tp_basicsize*/ 619 0, /*tp_itemsize*/ 620 0, /*tp_dealloc*/ 621 0, /*tp_print*/ 622 0, /*tp_getattr*/ 623 0, /*tp_setattr*/ 624 0, /*tp_compare*/ 625 0, /*tp_repr*/ 626 0, /*tp_as_number*/ 627 0, /*tp_as_sequence*/ 628 0, /*tp_as_mapping*/ 629 0, /*tp_hash */ 630 0, /*tp_call*/ 631 0, /*tp_str*/ 632 0, /*tp_getattro*/ 633 0, /*tp_setattro*/ 634 0, /*tp_as_buffer*/ 635 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ 636 "GDB command object", /* tp_doc */ 637 0, /* tp_traverse */ 638 0, /* tp_clear */ 639 0, /* tp_richcompare */ 640 0, /* tp_weaklistoffset */ 641 0, /* tp_iter */ 642 0, /* tp_iternext */ 643 cmdpy_object_methods, /* tp_methods */ 644 0, /* tp_members */ 645 0, /* tp_getset */ 646 0, /* tp_base */ 647 0, /* tp_dict */ 648 0, /* tp_descr_get */ 649 0, /* tp_descr_set */ 650 0, /* tp_dictoffset */ 651 cmdpy_init, /* tp_init */ 652 0, /* tp_alloc */ 653 }; 654 655 656 657 /* Utility to build a buildargv-like result from ARGS. 658 This intentionally parses arguments the way libiberty/argv.c:buildargv 659 does. It splits up arguments in a reasonable way, and we want a standard 660 way of parsing arguments. Several gdb commands use buildargv to parse their 661 arguments. Plus we want to be able to write compatible python 662 implementations of gdb commands. */ 663 664 PyObject * 665 gdbpy_string_to_argv (PyObject *self, PyObject *args) 666 { 667 const char *input; 668 669 if (!PyArg_ParseTuple (args, "s", &input)) 670 return NULL; 671 672 gdbpy_ref<> py_argv (PyList_New (0)); 673 if (py_argv == NULL) 674 return NULL; 675 676 /* buildargv uses NULL to represent an empty argument list, but we can't use 677 that in Python. Instead, if ARGS is "" then return an empty list. 678 This undoes the NULL -> "" conversion that cmdpy_function does. */ 679 680 if (*input != '\0') 681 { 682 gdb_argv c_argv (input); 683 684 for (char *arg : c_argv) 685 { 686 gdbpy_ref<> argp (PyUnicode_FromString (arg)); 687 688 if (argp == NULL 689 || PyList_Append (py_argv.get (), argp.get ()) < 0) 690 return NULL; 691 } 692 } 693 694 return py_argv.release (); 695 } 696