1 /* MI Command Set for GDB, the GNU debugger.
3 Copyright (C) 2019-2022 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/>. */
20 /* GDB/MI commands implemented in Python. */
23 #include "python-internal.h"
24 #include "arch-utils.h"
27 #include "mi/mi-cmds.h"
28 #include "mi/mi-parse.h"
29 #include "cli/cli-cmds.h"
32 /* Debugging of Python MI commands. */
34 static bool pymicmd_debug;
36 /* Implementation of "show debug py-micmd". */
39 show_pymicmd_debug (struct ui_file *file, int from_tty,
40 struct cmd_list_element *c, const char *value)
42 gdb_printf (file, _("Python MI command debugging is %s.\n"), value);
45 /* Print a "py-micmd" debug statement. */
47 #define pymicmd_debug_printf(fmt, ...) \
48 debug_prefixed_printf_cond (pymicmd_debug, "py-micmd", fmt, ##__VA_ARGS__)
50 /* Print a "py-micmd" enter/exit debug statements. */
52 #define PYMICMD_SCOPED_DEBUG_ENTER_EXIT \
53 scoped_debug_enter_exit (pymicmd_debug, "py-micmd")
57 /* Representation of a Python gdb.MICommand object. */
63 /* The object representing this command in the MI command table. This
64 pointer can be nullptr if the command is not currently installed into
65 the MI command table (see gdb.MICommand.installed property). */
66 struct mi_command_py *mi_command;
68 /* The string representing the name of this command, without the leading
69 dash. This string is never nullptr once the Python object has been
72 The memory for this string was allocated with malloc, and needs to be
73 deallocated with free when the Python object is deallocated.
75 When the MI_COMMAND field is not nullptr, then the mi_command_py
76 object's name will point back to this string. */
77 char *mi_command_name;
80 /* The MI command implemented in Python. */
82 struct mi_command_py : public mi_command
84 /* Constructs a new mi_command_py object. NAME is command name without
85 leading dash. OBJECT is a reference to a Python object implementing
86 the command. This object must inherit from gdb.MICommand and must
87 implement the invoke method. */
89 mi_command_py (const char *name, micmdpy_object *object)
90 : mi_command (name, nullptr),
91 m_pyobj (gdbpy_ref<micmdpy_object>::new_reference (object))
93 pymicmd_debug_printf ("this = %p", this);
94 m_pyobj->mi_command = this;
99 /* The Python object representing a MI command contains a pointer back
100 to this c++ object. We can safely set this pointer back to nullptr
101 now, to indicate the Python object no longer references a valid c++
104 However, the Python object also holds the storage for our name
105 string. We can't clear that here as our parent's destructor might
106 still want to reference that string. Instead we rely on the Python
107 object deallocator to free that memory, and reset the pointer. */
108 m_pyobj->mi_command = nullptr;
110 pymicmd_debug_printf ("this = %p", this);
113 /* Validate that CMD_OBJ, a non-nullptr pointer, is installed into the MI
114 command table correctly. This function looks up the command in the MI
115 command table and checks that the object we get back references
116 CMD_OBJ. This function is only intended for calling within a
117 gdb_assert. This function performs many assertions internally, and
118 then always returns true. */
119 static void validate_installation (micmdpy_object *cmd_obj);
121 /* Update M_PYOBJ to NEW_PYOBJ. The pointer from M_PYOBJ that points
122 back to this object is swapped with the pointer in NEW_PYOBJ, which
123 must be nullptr, so that NEW_PYOBJ now points back to this object.
124 Additionally our parent's name string is stored in M_PYOBJ, so we
125 swap the name string with NEW_PYOBJ.
127 Before this call M_PYOBJ is the Python object representing this MI
128 command object. After this call has completed, NEW_PYOBJ now
129 represents this MI command object. */
130 void swap_python_object (micmdpy_object *new_pyobj)
132 /* Current object has a backlink, new object doesn't have a backlink. */
133 gdb_assert (m_pyobj->mi_command != nullptr);
134 gdb_assert (new_pyobj->mi_command == nullptr);
136 /* Clear the current M_PYOBJ's backlink, set NEW_PYOBJ's backlink. */
137 std::swap (new_pyobj->mi_command, m_pyobj->mi_command);
139 /* Both object have names. */
140 gdb_assert (m_pyobj->mi_command_name != nullptr);
141 gdb_assert (new_pyobj->mi_command_name != nullptr);
143 /* mi_command::m_name is the string owned by the current object. */
144 gdb_assert (m_pyobj->mi_command_name == this->name ());
146 /* The name in mi_command::m_name is owned by the current object. Rather
147 than changing the value of mi_command::m_name (which is not accessible
148 from here) to point to the name owned by the new object, swap the names
149 of the two objects, since we know they are identical strings. */
150 gdb_assert (strcmp (new_pyobj->mi_command_name,
151 m_pyobj->mi_command_name) == 0);
152 std::swap (new_pyobj->mi_command_name, m_pyobj->mi_command_name);
154 /* Take a reference to the new object, drop the reference to the current
156 m_pyobj = gdbpy_ref<micmdpy_object>::new_reference (new_pyobj);
159 /* Called when the MI command is invoked. */
160 virtual void invoke(struct mi_parse *parse) const override;
163 /* The Python object representing this MI command. */
164 gdbpy_ref<micmdpy_object> m_pyobj;
167 using mi_command_py_up = std::unique_ptr<mi_command_py>;
169 extern PyTypeObject micmdpy_object_type
170 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("micmdpy_object");
172 /* Holds a Python object containing the string 'invoke'. */
174 static PyObject *invoke_cst;
176 /* Convert KEY_OBJ into a string that can be used as a field name in MI
177 output. KEY_OBJ must be a Python string object, and must only contain
178 characters suitable for use as an MI field name.
180 If KEY_OBJ is not a string, or if KEY_OBJ contains invalid characters,
181 then an error is thrown. Otherwise, KEY_OBJ is converted to a string
184 static gdb::unique_xmalloc_ptr<char>
185 py_object_to_mi_key (PyObject *key_obj)
187 /* The key must be a string. */
188 if (!PyUnicode_Check (key_obj))
190 gdbpy_ref<> key_repr (PyObject_Repr (key_obj));
191 gdb::unique_xmalloc_ptr<char> key_repr_string;
192 if (key_repr != nullptr)
193 key_repr_string = python_string_to_target_string (key_repr.get ());
194 if (key_repr_string == nullptr)
195 gdbpy_handle_exception ();
197 gdbpy_error (_("non-string object used as key: %s"),
198 key_repr_string.get ());
201 gdb::unique_xmalloc_ptr<char> key_string
202 = python_string_to_target_string (key_obj);
203 if (key_string == nullptr)
204 gdbpy_handle_exception ();
206 /* Predicate function, returns true if NAME is a valid field name for use
207 in MI result output, otherwise, returns false. */
208 auto is_valid_key_name = [] (const char *name) -> bool
210 gdb_assert (name != nullptr);
212 if (*name == '\0' || !isalpha (*name))
215 for (; *name != '\0'; ++name)
216 if (!isalnum (*name) && *name != '_' && *name != '-')
222 if (!is_valid_key_name (key_string.get ()))
224 if (*key_string.get () == '\0')
225 gdbpy_error (_("Invalid empty key in MI result"));
227 gdbpy_error (_("Invalid key in MI result: %s"), key_string.get ());
233 /* Serialize RESULT and print it in MI format to the current_uiout.
234 FIELD_NAME is used as the name of this result field.
236 RESULT can be a dictionary, a sequence, an iterator, or an object that
237 can be converted to a string, these are converted to the matching MI
238 output format (dictionaries as tuples, sequences and iterators as lists,
239 and strings as named fields).
241 If anything goes wrong while formatting the output then an error is
244 This function is the recursive inner core of serialize_mi_result, and
245 should only be called from that function. */
248 serialize_mi_result_1 (PyObject *result, const char *field_name)
250 struct ui_out *uiout = current_uiout;
252 if (PyDict_Check (result))
254 PyObject *key, *value;
256 ui_out_emit_tuple tuple_emitter (uiout, field_name);
257 while (PyDict_Next (result, &pos, &key, &value))
259 gdb::unique_xmalloc_ptr<char> key_string
260 (py_object_to_mi_key (key));
261 serialize_mi_result_1 (value, key_string.get ());
264 else if (PySequence_Check (result) && !PyUnicode_Check (result))
266 ui_out_emit_list list_emitter (uiout, field_name);
267 Py_ssize_t len = PySequence_Size (result);
269 gdbpy_handle_exception ();
270 for (Py_ssize_t i = 0; i < len; ++i)
272 gdbpy_ref<> item (PySequence_ITEM (result, i));
274 gdbpy_handle_exception ();
275 serialize_mi_result_1 (item.get (), nullptr);
278 else if (PyIter_Check (result))
281 ui_out_emit_list list_emitter (uiout, field_name);
284 item.reset (PyIter_Next (result));
287 if (PyErr_Occurred () != nullptr)
288 gdbpy_handle_exception ();
291 serialize_mi_result_1 (item.get (), nullptr);
296 gdb::unique_xmalloc_ptr<char> string (gdbpy_obj_to_string (result));
297 if (string == nullptr)
298 gdbpy_handle_exception ();
299 uiout->field_string (field_name, string.get ());
303 /* Serialize RESULT and print it in MI format to the current_uiout.
305 This function handles the top-level result initially returned from the
306 invoke method of the Python command implementation. At the top-level
307 the result must be a dictionary. The values within this dictionary can
308 be a wider range of types. Handling the values of the top-level
309 dictionary is done by serialize_mi_result_1, see that function for more
312 If anything goes wrong while parsing and printing the MI output then an
316 serialize_mi_result (PyObject *result)
318 /* At the top-level, the result must be a dictionary. */
320 if (!PyDict_Check (result))
321 gdbpy_error (_("Result from invoke must be a dictionary"));
323 PyObject *key, *value;
325 while (PyDict_Next (result, &pos, &key, &value))
327 gdb::unique_xmalloc_ptr<char> key_string
328 (py_object_to_mi_key (key));
329 serialize_mi_result_1 (value, key_string.get ());
333 /* Called when the MI command is invoked. PARSE contains the parsed
334 command line arguments from the user. */
337 mi_command_py::invoke (struct mi_parse *parse) const
339 PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
341 pymicmd_debug_printf ("this = %p, name = %s", this, name ());
343 mi_parse_argv (parse->args, parse);
345 if (parse->argv == nullptr)
346 error (_("Problem parsing arguments: %s %s"), parse->command, parse->args);
349 gdbpy_enter enter_py;
351 /* Place all the arguments into a list which we pass as a single argument
352 to the MI command's invoke method. */
353 gdbpy_ref<> argobj (PyList_New (parse->argc));
354 if (argobj == nullptr)
355 gdbpy_handle_exception ();
357 for (int i = 0; i < parse->argc; ++i)
359 gdbpy_ref<> str (PyUnicode_Decode (parse->argv[i],
360 strlen (parse->argv[i]),
361 host_charset (), nullptr));
362 if (PyList_SetItem (argobj.get (), i, str.release ()) < 0)
363 gdbpy_handle_exception ();
366 gdb_assert (this->m_pyobj != nullptr);
367 gdb_assert (PyErr_Occurred () == nullptr);
369 (PyObject_CallMethodObjArgs ((PyObject *) this->m_pyobj.get (), invoke_cst,
370 argobj.get (), nullptr));
371 if (result == nullptr)
372 gdbpy_handle_exception ();
374 if (result != Py_None)
375 serialize_mi_result (result.get ());
378 /* See declaration above. */
381 mi_command_py::validate_installation (micmdpy_object *cmd_obj)
383 gdb_assert (cmd_obj != nullptr);
384 mi_command_py *cmd = cmd_obj->mi_command;
385 gdb_assert (cmd != nullptr);
386 const char *name = cmd_obj->mi_command_name;
387 gdb_assert (name != nullptr);
388 gdb_assert (name == cmd->name ());
389 mi_command *mi_cmd = mi_cmd_lookup (name);
390 gdb_assert (mi_cmd == cmd);
391 gdb_assert (cmd->m_pyobj == cmd_obj);
394 /* Return CMD as an mi_command_py if it is a Python MI command, else
397 static mi_command_py *
398 as_mi_command_py (mi_command *cmd)
400 return dynamic_cast<mi_command_py *> (cmd);
403 /* Uninstall OBJ, making the MI command represented by OBJ unavailable for
404 use by the user. On success 0 is returned, otherwise -1 is returned
405 and a Python exception will be set. */
408 micmdpy_uninstall_command (micmdpy_object *obj)
410 PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
412 gdb_assert (obj->mi_command != nullptr);
413 gdb_assert (obj->mi_command_name != nullptr);
415 pymicmd_debug_printf ("name = %s", obj->mi_command_name);
417 /* Remove the command from the internal MI table of commands. This will
418 cause the mi_command_py object to be deleted, which will clear the
420 bool removed = remove_mi_cmd_entry (obj->mi_command->name ());
421 gdb_assert (removed);
422 gdb_assert (obj->mi_command == nullptr);
427 /* Install OBJ as a usable MI command. Return 0 on success, and -1 on
428 error, in which case, a Python error will have been set.
430 After successful completion the command name associated with OBJ will
431 be installed in the MI command table (so it can be found if the user
432 enters that command name), additionally, OBJ will have been added to
433 the gdb._mi_commands dictionary (using the command name as its key),
434 this will ensure that OBJ remains live even if the user gives up all
438 micmdpy_install_command (micmdpy_object *obj)
440 PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
442 gdb_assert (obj->mi_command == nullptr);
443 gdb_assert (obj->mi_command_name != nullptr);
445 pymicmd_debug_printf ("name = %s", obj->mi_command_name);
447 /* Look up this command name in MI_COMMANDS, a command with this name may
449 mi_command *cmd = mi_cmd_lookup (obj->mi_command_name);
450 mi_command_py *cmd_py = as_mi_command_py (cmd);
452 if (cmd != nullptr && cmd_py == nullptr)
454 /* There is already an MI command registered with that name, and it's not
455 a Python one. Forbid replacing a non-Python MI command. */
456 PyErr_SetString (PyExc_RuntimeError,
457 _("unable to add command, name is already in use"));
461 if (cmd_py != nullptr)
463 /* There is already a Python MI command registered with that name, swap
464 in the new gdb.MICommand implementation. */
465 cmd_py->swap_python_object (obj);
469 /* There's no MI command registered with that name at all, create one. */
470 mi_command_py_up mi_cmd (new mi_command_py (obj->mi_command_name, obj));
472 /* Add the command to the gdb internal MI command table. */
473 bool result = insert_mi_cmd_entry (std::move (mi_cmd));
480 /* Implement gdb.MICommand.__init__. The init method takes the name of
481 the MI command as the first argument, which must be a string, starting
482 with a single dash. */
485 micmdpy_init (PyObject *self, PyObject *args, PyObject *kwargs)
487 PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
489 micmdpy_object *cmd = (micmdpy_object *) self;
491 static const char *keywords[] = { "name", nullptr };
494 if (!gdb_PyArg_ParseTupleAndKeywords (args, kwargs, "s", keywords,
498 /* Validate command name */
499 const int name_len = strlen (name);
502 PyErr_SetString (PyExc_ValueError, _("MI command name is empty."));
505 else if ((name_len < 2) || (name[0] != '-') || !isalnum (name[1]))
507 PyErr_SetString (PyExc_ValueError,
508 _("MI command name does not start with '-'"
509 " followed by at least one letter or digit."));
514 for (int i = 2; i < name_len; i++)
516 if (!isalnum (name[i]) && name[i] != '-')
520 _("MI command name contains invalid character: %c."),
526 /* Skip over the leading dash. For the rest of this function the
527 dash is not important. */
531 /* If this object already has a name set, then this object has been
532 initialized before. We handle this case a little differently. */
533 if (cmd->mi_command_name != nullptr)
535 /* First, we don't allow the user to change the MI command name.
536 Supporting this would be tricky as we would need to delete the
537 mi_command_py from the MI command table, however, the user might
538 be trying to perform this reinitialization from within the very
539 command we're about to delete... it all gets very messy.
541 So, for now at least, we don't allow this. This doesn't seem like
542 an excessive restriction. */
543 if (strcmp (cmd->mi_command_name, name) != 0)
547 _("can't reinitialize object with a different command name"));
551 /* If there's already an object registered with the MI command table,
552 then we're done. That object must be a mi_command_py, which
553 should reference back to this micmdpy_object. */
554 if (cmd->mi_command != nullptr)
556 mi_command_py::validate_installation (cmd);
561 cmd->mi_command_name = xstrdup (name);
563 /* Now we can install this mi_command_py in the MI command table. */
564 return micmdpy_install_command (cmd);
567 /* Called when a gdb.MICommand object is deallocated. */
570 micmdpy_dealloc (PyObject *obj)
572 PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
574 micmdpy_object *cmd = (micmdpy_object *) obj;
576 /* If the Python object failed to initialize, then the name field might
578 pymicmd_debug_printf ("obj = %p, name = %s", cmd,
579 (cmd->mi_command_name == nullptr
580 ? "(null)" : cmd->mi_command_name));
582 /* As the mi_command_py object holds a reference to the micmdpy_object,
583 the only way the dealloc function can be called is if the mi_command_py
584 object has been deleted, in which case the following assert will
586 gdb_assert (cmd->mi_command == nullptr);
588 /* Free the memory that holds the command name. */
589 xfree (cmd->mi_command_name);
590 cmd->mi_command_name = nullptr;
592 /* Finally, free the memory for this Python object. */
593 Py_TYPE (obj)->tp_free (obj);
596 /* Python initialization for the MI commands components. */
599 gdbpy_initialize_micommands ()
601 micmdpy_object_type.tp_new = PyType_GenericNew;
602 if (PyType_Ready (&micmdpy_object_type) < 0)
605 if (gdb_pymodule_addobject (gdb_module, "MICommand",
606 (PyObject *) &micmdpy_object_type)
610 invoke_cst = PyUnicode_FromString ("invoke");
611 if (invoke_cst == nullptr)
618 gdbpy_finalize_micommands ()
620 /* mi_command_py objects hold references to micmdpy_object objects. They must
621 be dropped before the Python interpreter is finalized. Do so by removing
622 those MI command entries, thus deleting the mi_command_py objects. */
623 remove_mi_cmd_entries ([] (mi_command *cmd)
625 return as_mi_command_py (cmd) != nullptr;
629 /* Get the gdb.MICommand.name attribute, returns a string, the name of this
633 micmdpy_get_name (PyObject *self, void *closure)
635 struct micmdpy_object *micmd_obj = (struct micmdpy_object *) self;
637 gdb_assert (micmd_obj->mi_command_name != nullptr);
638 std::string name_str = string_printf ("-%s", micmd_obj->mi_command_name);
639 return PyUnicode_FromString (name_str.c_str ());
642 /* Get the gdb.MICommand.installed property. Returns true if this MI
643 command is installed into the MI command table, otherwise returns
647 micmdpy_get_installed (PyObject *self, void *closure)
649 struct micmdpy_object *micmd_obj = (struct micmdpy_object *) self;
651 if (micmd_obj->mi_command == nullptr)
656 /* Set the gdb.MICommand.installed property. The property can be set to
657 either true or false. Setting the property to true will cause the
658 command to be installed into the MI command table (if it isn't
659 already), while setting this property to false will cause the command
660 to be removed from the MI command table (if it is present). */
663 micmdpy_set_installed (PyObject *self, PyObject *newvalue, void *closure)
665 struct micmdpy_object *micmd_obj = (struct micmdpy_object *) self;
667 bool installed_p = PyObject_IsTrue (newvalue);
668 if (installed_p == (micmd_obj->mi_command != nullptr))
672 return micmdpy_install_command (micmd_obj);
674 return micmdpy_uninstall_command (micmd_obj);
677 /* The gdb.MICommand properties. */
679 static gdb_PyGetSetDef micmdpy_object_getset[] = {
680 { "name", micmdpy_get_name, nullptr, "The command's name.", nullptr },
681 { "installed", micmdpy_get_installed, micmdpy_set_installed,
682 "Is this command installed for use.", nullptr },
683 { nullptr } /* Sentinel. */
686 /* The gdb.MICommand descriptor. */
688 PyTypeObject micmdpy_object_type = {
689 PyVarObject_HEAD_INIT (nullptr, 0) "gdb.MICommand", /*tp_name */
690 sizeof (micmdpy_object), /*tp_basicsize */
692 micmdpy_dealloc, /*tp_dealloc */
699 0, /*tp_as_sequence */
700 0, /*tp_as_mapping */
707 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags */
708 "GDB mi-command object", /* tp_doc */
711 0, /* tp_richcompare */
712 0, /* tp_weaklistoffset */
717 micmdpy_object_getset, /* tp_getset */
720 0, /* tp_descr_get */
721 0, /* tp_descr_set */
722 0, /* tp_dictoffset */
723 micmdpy_init, /* tp_init */
727 void _initialize_py_micmd ();
729 _initialize_py_micmd ()
731 add_setshow_boolean_cmd
732 ("py-micmd", class_maintenance, &pymicmd_debug,
733 _("Set Python micmd debugging."),
734 _("Show Python micmd debugging."),
735 _("When on, Python micmd debugging is enabled."),
738 &setdebuglist, &showdebuglist);