1 /* gdb commands implemented in Python
3 Copyright (C) 2008-2025 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
21 #include "arch-utils.h"
23 #include "python-internal.h"
25 #include "cli/cli-cmds.h"
26 #include "cli/cli-decode.h"
27 #include "completer.h"
30 /* Struct representing built-in completion types. */
31 struct cmdpy_completer
33 /* Python symbol name. */
35 /* Completion function. */
36 completer_ftype
*completer
;
39 static const struct cmdpy_completer completers
[] =
41 { "COMPLETE_NONE", noop_completer
},
42 { "COMPLETE_FILENAME", filename_maybe_quoted_completer
},
43 { "COMPLETE_LOCATION", location_completer
},
44 { "COMPLETE_COMMAND", command_completer
},
45 { "COMPLETE_SYMBOL", symbol_completer
},
46 { "COMPLETE_EXPRESSION", expression_completer
},
49 #define N_COMPLETERS (sizeof (completers) / sizeof (completers[0]))
51 /* A gdb command. For the time being only ordinary commands (not
52 set/show commands) are allowed. */
57 /* The corresponding gdb command object, or NULL if the command is
58 no longer installed. */
59 struct cmd_list_element
*command
;
61 /* A prefix command requires storage for a list of its sub-commands.
62 A pointer to this is passed to add_prefix_command, and to add_cmd
63 for sub-commands of that prefix. If this Command is not a prefix
64 command, then this field is unused. */
65 struct cmd_list_element
*sub_list
;
68 extern PyTypeObject cmdpy_object_type
69 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("cmdpy_object");
71 /* Constants used by this module. */
72 static PyObject
*invoke_cst
;
73 static PyObject
*complete_cst
;
77 /* Python function which wraps dont_repeat. */
79 cmdpy_dont_repeat (PyObject
*self
, PyObject
*args
)
87 /* Called if the gdb cmd_list_element is destroyed. */
90 cmdpy_destroyer (struct cmd_list_element
*self
, void *context
)
94 /* Release our hold on the command object. */
95 gdbpy_ref
<cmdpy_object
> cmd ((cmdpy_object
*) context
);
99 /* Called by gdb to invoke the command. */
102 cmdpy_function (const char *args
, int from_tty
, cmd_list_element
*command
)
104 cmdpy_object
*obj
= (cmdpy_object
*) command
->context ();
106 gdbpy_enter enter_py
;
109 error (_("Invalid invocation of Python command object."));
111 /* If we get here for a prefix command then the prefix command had an
112 'invoke' method when it was created. If the 'invoke' method is now
113 missing, then the user has done something weird (like deleting the
114 invoke method, yuck!). */
115 if (!PyObject_HasAttr ((PyObject
*) obj
, invoke_cst
))
116 error (_("Python command object missing 'invoke' method."));
120 gdbpy_ref
<> argobj (PyUnicode_Decode (args
, strlen (args
), host_charset (),
124 gdbpy_print_stack ();
125 error (_("Could not convert arguments to Python string."));
128 gdbpy_ref
<> ttyobj (PyBool_FromLong (from_tty
));
129 gdbpy_ref
<> result (PyObject_CallMethodObjArgs ((PyObject
*) obj
, invoke_cst
,
130 argobj
.get (), ttyobj
.get (),
134 gdbpy_handle_exception ();
137 /* Helper function for the Python command completers (both "pure"
138 completer and brkchar handler). This function takes COMMAND, TEXT
139 and WORD and tries to call the Python method for completion with
142 This function is usually called twice: once when we are figuring out
143 the break characters to be used, and another to perform the real
144 completion itself. The reason for this two step dance is that we
145 need to know the set of "brkchars" to use early on, before we
146 actually try to perform the completion. But if a Python command
147 supplies a "complete" method then we have to call that method
148 first: it may return as its result the kind of completion to
149 perform and that will in turn specify which brkchars to use. IOW,
150 we need the result of the "complete" method before we actually
151 perform the completion. The only situation when this function is
152 not called twice is when the user uses the "complete" command: in
153 this scenario, there is no call to determine the "brkchars".
155 Ideally, it would be nice to cache the result of the first call (to
156 determine the "brkchars") and return this value directly in the
157 second call (to perform the actual completion). However, due to
158 the peculiarity of the "complete" command mentioned above, it is
159 possible to put GDB in a bad state if you perform a TAB-completion
160 and then a "complete"-completion sequentially. Therefore, we just
161 recalculate everything twice for TAB-completions.
163 This function returns a reference to the PyObject representing the
164 Python method call. */
167 cmdpy_completer_helper (struct cmd_list_element
*command
,
168 const char *text
, const char *word
)
170 cmdpy_object
*obj
= (cmdpy_object
*) command
->context ();
173 error (_("Invalid invocation of Python command object."));
174 if (!PyObject_HasAttr ((PyObject
*) obj
, complete_cst
))
176 /* If there is no complete method, don't error. */
180 gdbpy_ref
<> textobj (PyUnicode_Decode (text
, strlen (text
), host_charset (),
184 gdbpy_print_stack ();
185 error (_("Could not convert argument to Python string."));
191 /* "brkchars" phase. */
192 wordobj
= gdbpy_ref
<>::new_reference (Py_None
);
196 wordobj
.reset (PyUnicode_Decode (word
, strlen (word
), host_charset (),
200 gdbpy_print_stack ();
201 error (_("Could not convert argument to Python string."));
205 gdbpy_ref
<> resultobj (PyObject_CallMethodObjArgs ((PyObject
*) obj
,
208 wordobj
.get (), NULL
));
210 /* Check if an exception was raised by the Command.complete method. */
211 if (resultobj
== nullptr)
213 gdbpy_print_stack_or_quit ();
214 error (_("exception raised during Command.complete method"));
220 /* Python function called to determine the break characters of a
221 certain completer. We are only interested in knowing if the
222 completer registered by the user will return one of the integer
223 codes (see COMPLETER_* symbols). */
226 cmdpy_completer_handle_brkchars (struct cmd_list_element
*command
,
227 completion_tracker
&tracker
,
228 const char *text
, const char *word
)
230 gdbpy_enter enter_py
;
232 /* Calling our helper to obtain a reference to the PyObject of the Python
234 gdbpy_ref
<> resultobj
= cmdpy_completer_helper (command
, text
, word
);
236 /* Check if there was an error. */
237 if (resultobj
== NULL
)
240 if (PyLong_Check (resultobj
.get ()))
242 /* User code may also return one of the completion constants,
243 thus requesting that sort of completion. We are only
244 interested in this kind of return. */
247 if (!gdb_py_int_as_long (resultobj
.get (), &value
))
248 gdbpy_print_stack ();
249 else if (value
>= 0 && value
< (long) N_COMPLETERS
)
251 completer_handle_brkchars_ftype
*brkchars_fn
;
253 /* This is the core of this function. Depending on which
254 completer type the Python function returns, we have to
255 adjust the break characters accordingly. */
256 brkchars_fn
= (completer_handle_brkchars_func_for_completer
257 (completers
[value
].completer
));
258 brkchars_fn (command
, tracker
, text
, word
);
263 /* Called by gdb for command completion. */
266 cmdpy_completer (struct cmd_list_element
*command
,
267 completion_tracker
&tracker
,
268 const char *text
, const char *word
)
270 gdbpy_enter enter_py
;
272 /* Calling our helper to obtain a reference to the PyObject of the Python
274 gdbpy_ref
<> resultobj
= cmdpy_completer_helper (command
, text
, word
);
276 /* If the result object of calling the Python function is NULL, it
277 means that there was an error. In this case, just give up. */
278 if (resultobj
== NULL
)
281 if (PyLong_Check (resultobj
.get ()))
283 /* User code may also return one of the completion constants,
284 thus requesting that sort of completion. */
287 if (! gdb_py_int_as_long (resultobj
.get (), &value
))
288 gdbpy_print_stack ();
289 else if (value
>= 0 && value
< (long) N_COMPLETERS
)
290 completers
[value
].completer (command
, tracker
, text
, word
);
292 else if (PySequence_Check (resultobj
.get ()))
294 gdbpy_ref
<> iter (PyObject_GetIter (resultobj
.get ()));
298 gdbpy_print_stack ();
304 gdbpy_ref
<> elt (PyIter_Next (iter
.get ()));
307 if (PyErr_Occurred() != nullptr)
308 gdbpy_print_stack ();
312 if (! gdbpy_is_string (elt
.get ()))
314 /* Skip problem elements. */
318 gdb::unique_xmalloc_ptr
<char>
319 item (python_string_to_host_string (elt
.get ()));
322 gdbpy_print_stack ();
325 tracker
.add_completion (std::move (item
));
330 /* Helper for cmdpy_init which locates the command list to use and
331 pulls out the command name.
333 NAME is the command name list. The final word in the list is the
334 name of the new command. All earlier words must be existing prefix
337 *BASE_LIST is set to the final prefix command's list of sub-commands.
339 START_LIST is the list in which the search starts.
341 When PREFIX_CMD is not NULL then *PREFIX_CMD is set to the prefix
342 command itself, or NULL, if there is no prefix command.
344 This function returns the name of the new command. On error sets the Python
345 error and returns NULL. */
347 gdb::unique_xmalloc_ptr
<char>
348 gdbpy_parse_command_name (const char *name
,
349 struct cmd_list_element
***base_list
,
350 struct cmd_list_element
**start_list
,
351 struct cmd_list_element
**prefix_cmd
)
353 struct cmd_list_element
*elt
;
354 int len
= strlen (name
);
356 const char *prefix_text2
;
358 if (prefix_cmd
!= nullptr)
359 *prefix_cmd
= nullptr;
361 /* Skip trailing whitespace. */
362 for (i
= len
- 1; i
>= 0 && (name
[i
] == ' ' || name
[i
] == '\t'); --i
)
366 PyErr_SetString (PyExc_RuntimeError
, _("No command name found."));
371 /* Find first character of the final word. */
372 for (; i
> 0 && valid_cmd_char_p (name
[i
- 1]); --i
)
375 gdb::unique_xmalloc_ptr
<char> result
376 = make_unique_xstrndup (&name
[i
], lastchar
- i
+ 1);
378 /* Skip whitespace again. */
379 for (--i
; i
>= 0 && (name
[i
] == ' ' || name
[i
] == '\t'); --i
)
383 *base_list
= start_list
;
387 std::string
prefix_text (name
, i
+ 1);
389 prefix_text2
= prefix_text
.c_str ();
390 elt
= lookup_cmd_1 (&prefix_text2
, *start_list
, NULL
, NULL
, 1);
391 if (elt
== nullptr || elt
== CMD_LIST_AMBIGUOUS
|| *prefix_text2
!= '\0')
393 PyErr_Format (PyExc_RuntimeError
, _("Could not find command prefix %s."),
394 prefix_text
.c_str ());
398 if (elt
->is_prefix ())
400 *base_list
= elt
->subcommands
;
401 if (prefix_cmd
!= nullptr)
406 PyErr_Format (PyExc_RuntimeError
, _("'%s' is not a prefix command."),
407 prefix_text
.c_str ());
411 /* Object initializer; sets up gdb-side structures for command.
413 Use: __init__(NAME, COMMAND_CLASS [, COMPLETER_CLASS][, PREFIX]]).
415 NAME is the name of the command. It may consist of multiple words,
416 in which case the final word is the name of the new command, and
417 earlier words must be prefix commands.
419 COMMAND_CLASS is the kind of command. It should be one of the COMMAND_*
420 constants defined in the gdb module.
422 COMPLETER_CLASS is the kind of completer. If not given, the
423 "complete" method will be used. Otherwise, it should be one of the
424 COMPLETE_* constants defined in the gdb module.
426 If PREFIX is True, then this command is a prefix command.
428 The documentation for the command is taken from the doc string for
432 cmdpy_init (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
434 cmdpy_object
*obj
= (cmdpy_object
*) self
;
437 int completetype
= -1;
438 struct cmd_list_element
**cmd_list
;
439 static const char *keywords
[] = { "name", "command_class", "completer_class",
441 PyObject
*is_prefix_obj
= NULL
;
442 bool is_prefix
= false;
446 /* Note: this is apparently not documented in Python. We return
447 0 for success, -1 for failure. */
448 PyErr_Format (PyExc_RuntimeError
,
449 _("Command object already initialized."));
453 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "si|iO",
454 keywords
, &name
, &cmdtype
,
455 &completetype
, &is_prefix_obj
))
458 if (cmdtype
!= no_class
&& cmdtype
!= class_run
459 && cmdtype
!= class_vars
&& cmdtype
!= class_stack
460 && cmdtype
!= class_files
&& cmdtype
!= class_support
461 && cmdtype
!= class_info
&& cmdtype
!= class_breakpoint
462 && cmdtype
!= class_trace
&& cmdtype
!= class_obscure
463 && cmdtype
!= class_maintenance
&& cmdtype
!= class_user
464 && cmdtype
!= class_tui
)
466 PyErr_Format (PyExc_RuntimeError
, _("Invalid command class argument."));
470 if (completetype
< -1 || completetype
>= (int) N_COMPLETERS
)
472 PyErr_Format (PyExc_RuntimeError
,
473 _("Invalid completion type argument."));
477 cmd_list_element
*prefix_cmd
= nullptr;
478 gdb::unique_xmalloc_ptr
<char> cmd_name
479 = gdbpy_parse_command_name (name
, &cmd_list
, &cmdlist
, &prefix_cmd
);
480 if (cmd_name
== nullptr)
483 if (is_prefix_obj
!= NULL
)
485 int cmp
= PyObject_IsTrue (is_prefix_obj
);
492 gdb::unique_xmalloc_ptr
<char> docstring
= nullptr;
493 if (PyObject_HasAttr (self
, gdbpy_doc_cst
))
495 gdbpy_ref
<> ds_obj (PyObject_GetAttr (self
, gdbpy_doc_cst
));
497 if (ds_obj
!= NULL
&& gdbpy_is_string (ds_obj
.get ()))
499 docstring
= python_string_to_host_string (ds_obj
.get ());
500 if (docstring
== nullptr)
502 docstring
= gdbpy_fix_doc_string_indentation (std::move (docstring
));
505 if (docstring
== nullptr)
506 docstring
= make_unique_xstrdup (_("This command is not documented."));
508 gdbpy_ref
<> self_ref
= gdbpy_ref
<>::new_reference (self
);
512 struct cmd_list_element
*cmd
;
516 bool has_invoke
= PyObject_HasAttr (self
, invoke_cst
) == 1;
519 /* If there's an 'invoke' method, then create the prefix
520 command, but call cmdpy_function to dispatch to the invoke
521 method when the user runs the prefix with no sub-command. */
522 cmd
= add_prefix_cmd (cmd_name
.get (),
523 (enum command_class
) cmdtype
,
525 docstring
.release (), &obj
->sub_list
,
526 1 /* allow_unknown */, cmd_list
);
527 cmd
->func
= cmdpy_function
;
531 /* If there is no 'invoke' method, then create the prefix
532 using the standard prefix callbacks. This means that for
533 'set prefix' the user will get the help text listing all
534 of the sub-commands, and for 'show prefix', the user will
535 see all of the sub-command values. */
536 if (prefix_cmd
!= nullptr)
538 while (prefix_cmd
->prefix
!= nullptr)
539 prefix_cmd
= prefix_cmd
->prefix
;
542 bool is_show
= (prefix_cmd
!= nullptr
543 && prefix_cmd
->subcommands
== &showlist
);
546 cmd
= add_show_prefix_cmd (cmd_name
.get (),
547 (enum command_class
) cmdtype
,
548 docstring
.release (),
550 0 /* allow_unknown */, cmd_list
);
552 cmd
= add_basic_prefix_cmd (cmd_name
.get (),
553 (enum command_class
) cmdtype
,
554 docstring
.release (),
556 0 /* allow_unknown */, cmd_list
);
561 /* For non-prefix commands, arrange to call cmdpy_function, which
562 invokes the Python 'invoke' method, or raises an exception if
563 the 'invoke' method is missing. */
564 cmd
= add_cmd (cmd_name
.get (), (enum command_class
) cmdtype
,
565 docstring
.release (), cmd_list
);
566 cmd
->func
= cmdpy_function
;
569 /* If successful, the above takes ownership of the name, since we set
570 name_allocated, so release it. */
573 /* There appears to be no API to set these member variables. */
574 cmd
->destroyer
= cmdpy_destroyer
;
575 cmd
->doc_allocated
= 1;
576 cmd
->name_allocated
= 1;
579 cmd
->set_context (self_ref
.release ());
580 set_cmd_completer (cmd
, ((completetype
== -1) ? cmdpy_completer
581 : completers
[completetype
].completer
));
582 if (completetype
== -1)
583 set_cmd_completer_handle_brkchars (cmd
,
584 cmdpy_completer_handle_brkchars
);
586 catch (const gdb_exception
&except
)
588 return gdbpy_handle_gdb_exception (-1, except
);
596 /* Initialize the 'commands' code. */
598 static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
599 gdbpy_initialize_commands (void)
603 cmdpy_object_type
.tp_new
= PyType_GenericNew
;
604 if (gdbpy_type_ready (&cmdpy_object_type
) < 0)
607 /* Note: alias and user are special. */
608 if (PyModule_AddIntConstant (gdb_module
, "COMMAND_NONE", no_class
) < 0
609 || PyModule_AddIntConstant (gdb_module
, "COMMAND_RUNNING", class_run
) < 0
610 || PyModule_AddIntConstant (gdb_module
, "COMMAND_DATA", class_vars
) < 0
611 || PyModule_AddIntConstant (gdb_module
, "COMMAND_STACK", class_stack
) < 0
612 || PyModule_AddIntConstant (gdb_module
, "COMMAND_FILES", class_files
) < 0
613 || PyModule_AddIntConstant (gdb_module
, "COMMAND_SUPPORT",
615 || PyModule_AddIntConstant (gdb_module
, "COMMAND_STATUS", class_info
) < 0
616 || PyModule_AddIntConstant (gdb_module
, "COMMAND_BREAKPOINTS",
617 class_breakpoint
) < 0
618 || PyModule_AddIntConstant (gdb_module
, "COMMAND_TRACEPOINTS",
620 || PyModule_AddIntConstant (gdb_module
, "COMMAND_OBSCURE",
622 || PyModule_AddIntConstant (gdb_module
, "COMMAND_MAINTENANCE",
623 class_maintenance
) < 0
624 || PyModule_AddIntConstant (gdb_module
, "COMMAND_USER", class_user
) < 0
625 || PyModule_AddIntConstant (gdb_module
, "COMMAND_TUI", class_tui
) < 0)
628 for (i
= 0; i
< N_COMPLETERS
; ++i
)
630 if (PyModule_AddIntConstant (gdb_module
, completers
[i
].name
, i
) < 0)
634 invoke_cst
= PyUnicode_FromString ("invoke");
635 if (invoke_cst
== NULL
)
637 complete_cst
= PyUnicode_FromString ("complete");
638 if (complete_cst
== NULL
)
644 GDBPY_INITIALIZE_FILE (gdbpy_initialize_commands
);
648 static PyMethodDef cmdpy_object_methods
[] =
650 { "dont_repeat", cmdpy_dont_repeat
, METH_NOARGS
,
651 "Prevent command repetition when user enters empty line." },
656 PyTypeObject cmdpy_object_type
=
658 PyVarObject_HEAD_INIT (NULL
, 0)
659 "gdb.Command", /*tp_name*/
660 sizeof (cmdpy_object
), /*tp_basicsize*/
669 0, /*tp_as_sequence*/
677 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
678 "GDB command object", /* tp_doc */
681 0, /* tp_richcompare */
682 0, /* tp_weaklistoffset */
685 cmdpy_object_methods
, /* tp_methods */
690 0, /* tp_descr_get */
691 0, /* tp_descr_set */
692 0, /* tp_dictoffset */
693 cmdpy_init
, /* tp_init */
699 /* Utility to build a buildargv-like result from ARGS.
700 This intentionally parses arguments the way libiberty/argv.c:buildargv
701 does. It splits up arguments in a reasonable way, and we want a standard
702 way of parsing arguments. Several gdb commands use buildargv to parse their
703 arguments. Plus we want to be able to write compatible python
704 implementations of gdb commands. */
707 gdbpy_string_to_argv (PyObject
*self
, PyObject
*args
)
711 if (!PyArg_ParseTuple (args
, "s", &input
))
714 gdbpy_ref
<> py_argv (PyList_New (0));
718 /* buildargv uses NULL to represent an empty argument list, but we can't use
719 that in Python. Instead, if ARGS is "" then return an empty list.
720 This undoes the NULL -> "" conversion that cmdpy_function does. */
724 gdb_argv
c_argv (input
);
726 for (char *arg
: c_argv
)
728 gdbpy_ref
<> argp (PyUnicode_FromString (arg
));
731 || PyList_Append (py_argv
.get (), argp
.get ()) < 0)
736 return py_argv
.release ();