[PATCH 0/5] create GDB/MI commands using python

Andrew Burgess aburgess@redhat.com
Fri Jan 21 15:22:08 GMT 2022


* Jan Vrany via Gdb-patches <gdb-patches@sourceware.org> [2022-01-18 15:13:01 +0000]:

> On Tue, 2022-01-18 at 13:55 +0000, Andrew Burgess wrote:
> > * Jan Vrany via Gdb-patches <gdb-patches@sourceware.org> [2022-01-17 12:44:20 +0000]:
> > 
> > > This is a restart of an earlier attempts to allow custom
> > > GDB/MI commands written in Python.
> > 
> > Thanks for continuing to work on this feature.
> > 
> > I too had been looking at getting the remaining patches from your
> > series upstream, and I'd like to discuss some of the differences
> > between the approaches we took.
> 
> Great, thanks a lot!
> 
> > 
> > At the end of this mail you'll find my current work-in-progress
> > patch, it definitely needs the docs and NEWS entries adding, as well
> > as a few extra tests.  However, functionality wise I think its mostly
> > there.
> > 
> > My patch includes two sets of tests, gdb.python/py-mi-cmd.exp and
> > gdb.python/py-mi-cmd-orig.exp.  The former is based on your tests, but
> > with some tweaks based on changes I made.  The latter set is your
> > tests taken from this m/l thread.
> > 
> > When running the gdb.python/py-mi-cmd-orig.exp tests there should be
> > just 2 failures, both related to the same feature which is not present
> > in my version, that is, the ability of a command to redefine itself,
> > like this:
> > 
> >       class my_command(gdb.MICommand):
> >         def invoke(self, args):
> >           my_command("-blah")
> >           return None
> > 
> >        my_command("-blah")
> > 
> > this works with your version, but not with mine, this is because I'm
> > using python's own reference counting to track when a command can be
> > redefined or not, and, when you are within a commands invoke method
> > the reference count of the containing object is incremented, and this
> > prevents gdb from deleting the command.
> > 
> > My question then, is how important is this feature, and what use case
> > do you see for this?  Or, was support for this just a happy side
> > effect of the implementation approach you chose?
> 
> Initially I did not think of it and it was - IIRC - pointed out in
> some review. I thought to be a corner case, but it turned out to be
> (potentiality very useful feature. 
> 
> While developing custom commands, pretty printers and so on, it is useful
> to be able to "reload" Python code into running GDB without need to restart 
> it. To support that, I created a "pr" command which reloads all custom python 
> code (well, tries to at least), see 
> 
> https://swing.fit.cvut.cz/hg/jv-vdb/file/tip/python/vdb/cli.py#l20
> 
> So ultimately, this custom "pr" command's invoke() causes redefinition
> of the "pr" command itself. I have not done it yet, but having 
> menu item/icon in (my) GDB frontend using something like -python-reload`
> seems desirable from UX POV.

Thanks, that's not an unreasonable use case.  I've tweaked things so
that this case is now supported.

I've gone through that patch and ported over your NEWS and doc
changes, with some updates based on Eli's feedback, as well as some
new content to cover some of the changes in my patch.

For the testing, I have, for now, kept gdb.python/py-mi-cmd-orig.exp,
which is your test file taken from your patch series.  I added some
'setup_kfail' markers to 7 tests that now fail due to changes in error
strings, hopefully, this will allow you to review what changed.
However, except for the differences in error string, everything your
original series supported is now supported by this patch.

>From a user's point of view, I think the only differences with your
patch are:

 1. New .name attribute, that returns the name of the command as a
    string, here's an example session:

    (gdb) python
    >class MyCommand(gdb.MICommand):
    >  def __init__(self):
    >    super(MyCommand, self).__init__("-my-command")
    >  def invoke(self, args):
    >    return None
    >
    >end
    (gdb) python cmd = MyCommand()
    (gdb) python print(cmd.name)
    -my-command
    (gdb)

 2. New .installed attribute, that allows a command to be installed or
    removed from the mi command table, here's an example session:

    (gdb) python
    >class MyCommand(gdb.MICommand):
    >  def __init__(self, name, message):
    >    self._message = message
    >    super(MyCommand, self).__init__(name)
    >
    >  def invoke(self, args):
    >    return self._message
    >
    >end
    (gdb) python cmd1 = MyCommand("-my-command", "cmd1")
    (gdb) python print(cmd1.installed)
    True
    (gdb) interpreter-exec mi "-my-command"
    ^done,result="cmd1"
    (gdb) python cmd2 = MyCommand("-my-command", "cmd2")
    (gdb) python print(cmd2.installed)
    True
    (gdb) python print(cmd1.installed)
    False
    (gdb) interpreter-exec mi "-my-command"
    ^done,result="cmd2"
    (gdb) python cmd1.installed = True
    (gdb) python print(cmd2.installed)
    False
    (gdb) python print(cmd1.installed)
    True
    (gdb) interpreter-exec mi "-my-command"
    ^done,result="cmd1"
    (gdb) python cmd1.installed = False
    (gdb) interpreter-exec mi "-my-command"
    ^error,msg="Undefined MI command: my-command",code="undefined-command"
    (gdb)

 3. The top level result name can be changed from 'result' to anything
    the user wants, here's an example session:

    (gdb) python
    >class MyCommand(gdb.MICommand):
    >  def __init__(self):
    >    super(MyCommand, self).__init__("-my-command", "greeting")
    >  def invoke(self, args):
    >    return "Hello World"
    >
    >end
    (gdb) python cmd = MyCommand()
    (gdb) interpreter-exec mi "-my-command"
    ^done,greeting="Hello World"
    (gdb)

I'd love to hear your feedback on this iteration.

Thanks,
Andrew

---

commit 965c93b835c7abc64b0e1baa1b9e194a037fe565
Author: Andrew Burgess <aburgess@redhat.com>
Date:   Tue Jun 23 14:45:38 2020 +0100

    [WIP] gdb: create MI commands using python
    
    This commit allows an user to create custom MI commands using Python
    similarly to what is possible for Python CLI commands.
    
    A new subclass of mi_command is defined for Python MI commands,
    mi_command_py. A new file, py-micmd.c contains the logic for Python MI
    commands.
    
    This commit is based on work linked too from this mailing list thread:
    
      https://sourceware.org/pipermail/gdb/2021-November/049774.html
    
    Which has also been previously posted to the mailing list here:
    
      https://sourceware.org/pipermail/gdb-patches/2019-May/158010.html
    
    And was recently reposted here:
    
      https://sourceware.org/pipermail/gdb-patches/2022-January/185190.html
    
    This patch takes some core code from the previous posted patches, but
    also has some significant differences.
    
    In this patch, I have changed how the lifetime of the Python
    gdb.MICommand objects is managed.  In the original patch, these object
    were kept alive by an owned reference within the mi_command_py object.
    As such, the Python object would not be deleted until the
    mi_command_py object itself was deleted.
    
    This caused a problem, the mi_command_py were held in the global mi
    command table (in mi/mi-cmds.c), which, as a global, was not cleared
    until program shutdown.  By this point the Python interpreter has
    already been shutdown.  Attempting to delete the mi_command_py object
    at this point was causing GDB to try and invoke Python code after
    finalising the Python interpreter, and we would crash.
    
    To work around this problem, the original patch added code in
    python/python.c that would search the mi command table, and delete the
    mi_command_py objects before the Python environment was finalised.
    
    In contrast, in this patch, I have added a new global dictionary to
    the gdb module, gdb.mi_commands.  We already have several such global
    data stores related to pretty printers, and frame unwinders.
    
    The MICommand objects are placed into the new gdb.mi_commands
    dictionary, and it is this reference that keeps the objects alive.
    When GDB's Python interpreter is shut down gdb.mi_commands is deleted,
    and any MICommand objects within it are deleted at this point.
    
    This change avoids having to make the mi_cmd_table global, and walk
    over it from within GDB's python related code.
    
    This patch handles command redefinition entirely within GDB's python
    code, though this does impose one small restriction which is not
    present in the original code (detailed below), I don't think this is a
    big issue.  However, the original patch relied on being able to
    finish executing the mi_command::do_invoke member function after the
    mi_command object had been deleted.  Though continuing to execute a
    member function after an object is deleted is well defined, it is
    also (IMHO) risky, its too easy for someone to later add a use of the
    object without realising that the object might sometimes, have been
    deleted.  The new patch avoids this issue.
    
    The one restriction that is added to avoid this, is that an MICommand
    object can't be reinitialised with a different command name, so:
    
      (gdb) python cmd = MyMICommand("-abc")
      (gdb) python cmd.__init__("-def")
      can't reinitialize object with a different command name
    
    This feels like a pretty weird edge case, and I'm happy to live with
    this restriction.
    
    I have also changed how the memory is managed for the command name.
    In the most recently posted patch series, the command name is moved
    into a subclass of mi_command, the python mi_command_py, which
    inherits from mi_command is then free to use a smart pointer to manage
    the memory for the name.
    
    In this patch, I leave the mi_command class unchanged, and instead
    hold the memory for the name within the Python object, as the lifetime
    of the Python object always exceeds the c++ object stored in the
    mi_cmd_table.  This adds a little more complexity in py-micmd.c, but
    leaves the mi_command class nice and simple.
    
    Next, this patch adds some extra functionality, there's a
    MICommand.name read-only attribute containing the name of the command,
    and a read-write MICommand.installed attribute that can be used to
    install (make the command available for use) and uninstall (remove the
    command from the mi_cmd_table so it can't be used) the command.  This
    attribute will be automatically updated if a second command replaces
    an earlier command.
    
    This patch adds additional error handling, and makes more use the
    gdbpy_handle_exception function.
    
    The gdb.python/py-mi-cmd.exp test script is the official tests for
    this patch, which is based on the original tests from the latest patch
    posted by Jan to the mailing list.
    
    While this patch is in development I have also included a second test
    script gdb.python/py-mi-cmd-orig.exp, this is Jan's tests almost
    unmodified, so I could compare functionality.
    
    I say almost unmodified, there are a few tests in the original test
    script that now fail, these I have marked with setup_kfail.  All of
    these failures are due to changes in error message text.
    
    Co-Authored-By: Jan Vrany <jan.vrany@labware.com>
    
    f#      new file:   gdb/testsuite/gdb.python/py-mi-cmd-orig.py

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 3efd2227698..4962178fa9b 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -409,6 +409,7 @@ SUBDIR_PYTHON_SRCS = \
 	python/py-lazy-string.c \
 	python/py-linetable.c \
 	python/py-membuf.c \
+	python/py-micmd.c \
 	python/py-newobjfileevent.c \
 	python/py-objfile.c \
 	python/py-param.c \
diff --git a/gdb/NEWS b/gdb/NEWS
index 8c13cefb22f..31189cd07dd 100644
--- a/gdb/NEWS
+++ b/gdb/NEWS
@@ -146,6 +146,8 @@ show debug lin-lwp
   ** New function gdb.host_charset(), returns a string, which is the
      name of the current host charset.
 
+  ** It is now possible to add GDB/MI commands implemented in Python.
+
 * New features in the GDB remote stub, GDBserver
 
   ** GDBserver is now supported on OpenRISC GNU/Linux.
diff --git a/gdb/doc/python.texi b/gdb/doc/python.texi
index 6730de05143..7c148bcd0a1 100644
--- a/gdb/doc/python.texi
+++ b/gdb/doc/python.texi
@@ -204,7 +204,8 @@
 * Events In Python::            Listening for events from @value{GDBN}.
 * Threads In Python::           Accessing inferior threads from Python.
 * Recordings In Python::        Accessing recordings from Python.
-* Commands In Python::          Implementing new commands in Python.
+* CLI Commands In Python::      Implementing new CLI commands in Python.
+* GDB/MI Commands In Python::   Implementing new @sc{GDB/MI} commands in Python.
 * Parameters In Python::        Adding new @value{GDBN} parameters.
 * Functions In Python::         Writing new convenience functions.
 * Progspaces In Python::        Program spaces.
@@ -388,7 +389,8 @@
 @code{gdb.Value}.
 
 This function can be useful when implementing a new command
-(@pxref{Commands In Python}), as it provides a way to parse the
+(@pxref{CLI Commands In Python}, @pxref{GDB/MI Commands In Python}),
+as it provides a way to parse the
 command's argument as an expression.  It is also useful simply to
 compute values.
 @end defun
@@ -2105,7 +2107,7 @@
 frame decorator.  If no frames are being elided this function may
 return an empty iterable, or @code{None}.  Elided frames are indented
 from normal frames in a @code{CLI} backtrace, or in the case of
-@code{GDB/MI}, are placed in the @code{children} field of the eliding
+@sc{GDB/MI}, are placed in the @code{children} field of the eliding
 frame.
 
 It is the frame filter's task to also filter out the elided frames from
@@ -3809,11 +3811,12 @@
     return count
 @end smallexample
 
-@node Commands In Python
-@subsubsection Commands In Python
+@node CLI Commands In Python
+@subsubsection CLI Commands In Python
 
-@cindex commands in python
-@cindex python commands
+@cindex CLI commands in python
+@cindex commands in python, CLI
+@cindex python commands, CLI
 You can implement new @value{GDBN} CLI commands in Python.  A CLI
 command is implemented using an instance of the @code{gdb.Command}
 class, most commonly using a subclass.
@@ -4092,6 +4095,141 @@
 Python code is read into @value{GDBN}, you may need to import the
 @code{gdb} module explicitly.
 
+@node GDB/MI Commands In Python
+@subsubsection @sc{GDB/MI} Commands In Python
+
+@cindex MI commands in python
+@cindex commands in python, GDB/MI
+@cindex python commands, GDB/MI
+It is possible to add @sc{GDB/MI} (@pxref{GDB/MI}) commands
+implemented in Python.  A @sc{GDB/MI} command is implemented using an
+instance of the @code{gdb.MICommand} class, most commonly using a
+subclass.
+
+@defun MICommand.__init__ (name @r{[}, toplevel@r{]})
+The object initializer for @code{MICommand} registers the new command
+with @value{GDBN}.  This initializer is normally invoked from the
+subclass' own @code{__init__} method.
+
+@var{name} is the name of the command.  It must be a valid name of a
+@sc{GDB/MI} command, and in particular must start with a hyphen
+(@code{-}).  Reusing the name of a built-in @sc{GDB/MI} is not
+allowed, and will @code{RuntimeError} will be raised.  Using the name
+of an @sc{GDB/MI} command previously defined in Python is allowed, the
+previous command will be replaced with the new command.
+
+@var{toplevel} specifies the toplevel name used for the result in the
+output of this MI command.  If this command doesn't return a result
+then any value passed for @var{toplevel} is ignored.  If
+@var{toplevel} is @code{None} then a default value of @code{result} is
+used, otherwise, @var{toplevel} should be a string.
+@end defun
+
+@defun MICommand.invoke (arguments)
+This method is called by @value{GDBN} when this command is invoked.
+
+@var{arguments} is a list of strings.  Note, that @code{--thread}
+and @code{--frame} arguments are handled by @value{GDBN} itself therefore
+they do not show up in @code{arguments}.
+
+If this method throws a @code{gdb.GdbError} exception, it is turned
+into a @sc{GDB/MI} @code{^error} response.  If this method returns
+@code{None}, then the @sc{GDB/MI} command will return a @code{^done}
+response with no additional value.  Otherwise, the return value is
+converted to a @sc{GDB/MI} value (@pxref{GDB/MI Output Syntax}) as
+follows:
+
+@itemize
+@item If the value is Python sequence or iterator, it is converted to
+@sc{GDB/MI} @emph{list} with elements converted recursively.
+
+@item If the value is Python dictionary, it is converted to
+@sc{GDB/MI} @emph{tuple}.  Keys in that dictionary must be strings.
+Values are converted recursively.
+
+@item Otherwise, value is first converted to Python string using
+@code{str ()} and then converted to @sc{GDB/MI} @emph{const}.
+@end itemize
+
+@end defun
+
+An instance of @code{MICommand} has the following attributes:
+
+@defvar MICommand.name
+A string, the name of this @sc{GDB/MI} command, as was passed to the
+@code{__init__} method.  This attribute is read-only.
+@end defvar
+
+@defvar MICommand.installed
+A boolean value indicating if this command is installed ready for a
+user to call from the command line.  Commands are automatically
+installed when they are instantiated, after which this attribute will
+be @code{True}.
+
+If later, a new command is created with the same name, then the
+original command will become uninstalled, and this attribute will be
+@code{False}.
+
+This attribute can be is read-write, setting this attribute to
+@code{False} will uninstall the command, removing it from the set of
+available commands.  Setting this attribute to @code{True} will
+install the command for use.  If there is already a Python command
+with this name installed, the currently installed command will be
+uninstalled, and this command installed in its place.
+@end defvar
+
+The following code snippet shows how a two trivial MI command can be
+implemented in Python:
+
+@smallexample
+class MIEcho(gdb.MICommand):
+    """Echo arguments passed to the command."""
+
+    def __init__(self, name, mode, toplevel = None):
+        self._mode = mode
+        super(MIEcho, self).__init__(name, toplevel)
+
+    def invoke(self, argv):
+        if self._mode == 'dict':
+            return @{ 'argv' : argv @}
+        elif self._mode == 'list':
+            return argv
+        else:
+            return ", ".join(argv)
+
+
+MIEcho("-echo-dict", "dict")
+MIEcho("-echo-list", "list")
+MIEcho("-echo-string", "string", "argv")
+@end smallexample
+
+The last three lines instantiate the class three times, creating three
+new @sc{GDB/MI} commands @code{-echo-dict}, @code{-echo-list}, and
+@code{-echo-string}.  Each time a subclass of @code{gdb.MICommand} is
+instantiated, the new command is automatically registered with
+@value{GDBN}.
+
+Depending on how the Python code is read into @value{GDBN}, you may
+need to import the @code{gdb} module explicitly.
+
+The following example shows a @value{GDBN} session in which the above
+commands have been added:
+
+@smallexample
+-echo-dict abc def ghi
+^done,result=@{argv=["abc","def","ghi"]@}
+(@value{GDBP})
+-echo-list abc def ghi
+^done,result=["abc","def","ghi"]
+(@value{GDBP})
+-echo-list abc def ghi
+^done,argv=["abc","def","ghi"]
+(@value{GDBP})
+@end smallexample
+
+Notice that for the @code{-echo-string} command the toplevel result
+name was changed from @samp{result} to @samp{argv}.
+
 @node Parameters In Python
 @subsubsection Parameters In Python
 
@@ -4129,7 +4267,7 @@
 can be found, an exception is raised.
 
 @var{command-class} should be one of the @samp{COMMAND_} constants
-(@pxref{Commands In Python}).  This argument tells @value{GDBN} how to
+(@pxref{CLI Commands In Python}).  This argument tells @value{GDBN} how to
 categorize the new parameter in the help system.
 
 @var{parameter-class} should be one of the @samp{PARAM_} constants
diff --git a/gdb/mi/mi-cmds.c b/gdb/mi/mi-cmds.c
index cd7cabdda9b..dd0243e5bfe 100644
--- a/gdb/mi/mi-cmds.c
+++ b/gdb/mi/mi-cmds.c
@@ -26,10 +26,6 @@
 #include <map>
 #include <string>
 
-/* A command held in the MI_CMD_TABLE.  */
-
-using mi_command_up = std::unique_ptr<struct mi_command>;
-
 /* MI command table (built at run time). */
 
 static std::map<std::string, mi_command_up> mi_cmd_table;
@@ -113,12 +109,12 @@ struct mi_command_cli : public mi_command
    not have been added to mi_cmd_table.  Otherwise, return true, and
    COMMAND was added to mi_cmd_table.  */
 
-static bool
+bool
 insert_mi_cmd_entry (mi_command_up command)
 {
   gdb_assert (command != nullptr);
 
-  const std::string &name = command->name ();
+  const std::string name (command->name ());
 
   if (mi_cmd_table.find (name) != mi_cmd_table.end ())
     return false;
@@ -127,6 +123,20 @@ insert_mi_cmd_entry (mi_command_up command)
   return true;
 }
 
+bool
+remove_mi_cmd_entry (mi_command *command)
+{
+  gdb_assert (command != nullptr);
+
+  const std::string name (command->name ());
+
+  if (mi_cmd_table.find (name) == mi_cmd_table.end ())
+    return false;
+
+  mi_cmd_table.erase (name);
+  return true;
+}
+
 /* Create and register a new MI command with an MI specific implementation.
    NAME must name an MI command that does not already exist, otherwise an
    assertion will trigger.  */
diff --git a/gdb/mi/mi-cmds.h b/gdb/mi/mi-cmds.h
index 2a93a9f5476..3f4fb854d68 100644
--- a/gdb/mi/mi-cmds.h
+++ b/gdb/mi/mi-cmds.h
@@ -187,6 +187,10 @@ struct mi_command
   int *m_suppress_notification;
 };
 
+/* A command held in the MI_CMD_TABLE.  */
+
+using mi_command_up = std::unique_ptr<struct mi_command>;
+
 /* Lookup a command in the MI command table, returns nullptr if COMMAND is
    not found.  */
 
@@ -194,4 +198,15 @@ extern mi_command *mi_cmd_lookup (const char *command);
 
 extern void mi_execute_command (const char *cmd, int from_tty);
 
+/* Insert a new mi-command into the command table.  Return true if
+   insertion was successful.  */
+
+extern bool insert_mi_cmd_entry (mi_command_up command);
+
+/* Remove a mi-command from the command table.  Return true if the removal
+   was success, otherwise return false.  */
+
+extern bool remove_mi_cmd_entry (mi_command *command);
+
+
 #endif /* MI_MI_CMDS_H */
diff --git a/gdb/python/lib/gdb/__init__.py b/gdb/python/lib/gdb/__init__.py
index 11a1b444bfd..a9197eb4ffe 100644
--- a/gdb/python/lib/gdb/__init__.py
+++ b/gdb/python/lib/gdb/__init__.py
@@ -81,6 +81,9 @@ frame_filters = {}
 # Initial frame unwinders.
 frame_unwinders = []
 
+# Hash containing all user created MI commands, the key is the command
+# name, and the value is the gdb.MICommand object.
+mi_commands = {}
 
 def _execute_unwinders(pending_frame):
     """Internal function called from GDB to execute all unwinders.
diff --git a/gdb/python/py-micmd.c b/gdb/python/py-micmd.c
new file mode 100644
index 00000000000..2c3c9fe267a
--- /dev/null
+++ b/gdb/python/py-micmd.c
@@ -0,0 +1,767 @@
+/* MI Command Set for GDB, the GNU debugger.
+
+   Copyright (C) 2019 Free Software Foundation, Inc.
+
+   This file is part of GDB.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+/* gdb MI commands implemented in Python  */
+
+#include "defs.h"
+#include "python-internal.h"
+#include "arch-utils.h"
+#include "charset.h"
+#include "language.h"
+#include "mi/mi-cmds.h"
+#include "mi/mi-parse.h"
+#include "cli/cli-cmds.h"
+
+#include <string>
+
+/* Debugging of Python mi commands.  */
+
+static bool pymicmd_debug;
+
+/* Implementation of "show debug py-micmd".  */
+
+static void
+show_pymicmd_debug (struct ui_file *file, int from_tty,
+		    struct cmd_list_element *c, const char *value)
+{
+  fprintf_filtered (file, _("Python mi command debugging is %s.\n"), value);
+}
+
+/* Print a "py-micmd" debug statement.  */
+
+#define pymicmd_debug_printf(fmt, ...) \
+  debug_prefixed_printf_cond (pymicmd_debug, "py-micmd", fmt, ##__VA_ARGS__)
+
+/* Print a "py-micmd" enter/exit debug statements.  */
+
+#define PYMICMD_SCOPED_DEBUG_ENTER_EXIT \
+  scoped_debug_enter_exit (pymicmd_debug, "py-micmd")
+
+struct mi_command_py;
+
+/* Representation of a python gdb.MICommand object.  */
+
+struct micmdpy_object
+{
+  PyObject_HEAD
+
+  /* The object representing this command in the mi command table.  This
+     pointer can be nullptr if the command is not currently installed into
+     the mi command table (see gdb.MICommand.installed property).  */
+  struct mi_command_py *mi_command;
+
+  /* The string representing the name of this command, without the leading
+     dash.  This string is never nullptr once the python object has been
+     initialised.
+
+     The memory for this string was allocated with malloc, and needs to be
+     deallocated with free when the python object is deallocated.
+
+     When the MI_COMMAND variable is not nullptr, then the mi_command_py
+     object's name will point back to this string.  */
+  char *mi_command_name;
+
+  /* The name used for the toplevel result.  This can be nullptr, in which
+     case the default value should be used.  If this is not nullptr, then
+     the string was allocated with malloc, and needs to be freed when the
+     python object is deallocated.  */
+  char *mi_result_name;
+};
+
+/* The mi command implemented in python.  */
+
+struct mi_command_py : public mi_command
+{
+  /* Constructs a new mi_command_py object.  NAME is command name without
+     leading dash.  OBJECT is a reference to a Python object implementing
+     the command.  This object should inherit from gdb.MICommand and should
+     implement method invoke (args). */
+
+  mi_command_py (const char *name, micmdpy_object *object)
+    : mi_command (name, nullptr),
+      m_pyobj (object)
+  {
+    pymicmd_debug_printf ("this = %p", this);
+  }
+
+  ~mi_command_py ()
+  {
+    /* The python object representing a mi command contains a pointer back
+       to this c++ object.  We can safely set this pointer back to nullptr
+       now, to indicate the python object no longer references a valid c++
+       object.
+
+       However, the python object also holds the storage for our name
+       string.  We can't clear that here as our parent's destructor might
+       still want to reference that string.  Instead we rely on the python
+       object deallocator to free that memory, and reset the pointer.  */
+    m_pyobj->mi_command = nullptr;
+
+    pymicmd_debug_printf ("this = %p", this);
+  };
+
+  /* Validate that CMD_OBJ, a non-nullptr pointer, is installed into the mi
+     command table correctly.  This function looks up the command in the mi
+     command table and checks that the object we get back references
+     CMD_OBJ.  This function is only intended for calling within a
+     gdb_assert.  This function performs many assertions internally, and
+     then always returns true.  */
+  static bool validate_installation (micmdpy_object *cmd_obj);
+
+  /* Update m_pyobj to NEW_PYOBJ.  The pointer from M_PYOBJ that points
+     back to this object is swapped with the pointer in NEW_PYOBJ, which
+     must be nullptr, so that NEW_PYOBJ now points back to this object.
+     Additionally our parent's name string is stored in m_pyobj, so we
+     swap the name string with NEW_PYOBJ.
+
+     Before this call m_pyobj is the python object representing this mi
+     command object.  After this call has completed, NEW_PYOBJ now
+     represents this mi command object.  */
+  void swap_python_object (micmdpy_object *new_pyobj)
+  {
+    gdb_assert (new_pyobj->mi_command == nullptr);
+    std::swap (new_pyobj->mi_command, m_pyobj->mi_command);
+    std::swap (new_pyobj->mi_command_name, m_pyobj->mi_command_name);
+    m_pyobj = new_pyobj;
+  }
+
+protected:
+  /* Called when the mi command is invoked.  */
+  virtual void do_invoke(struct mi_parse *parse) const override;
+
+private:
+  /* The python object representing this mi command.  */
+  micmdpy_object *m_pyobj;
+};
+
+extern PyTypeObject micmdpy_object_type
+	CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("micmdpy_object");
+
+/* Holds a python object containing the string 'invoke'.  */
+
+static PyObject *invoke_cst;
+
+/* Parse RESULT and print it in mi format to the current_uiout.  FIELD_NAME
+   is used as the name of this result field.
+
+   RESULT can be a dictionary, a sequence, an iterator, or an object that
+   can be converted to a string, these are converted to the matching mi
+   output format (dictionaries as tuples, sequences and iterators as lists,
+   and strings as named fields).
+
+   If anything goes wrong while formatting the output then an error is
+   thrown.  */
+
+static void
+parse_mi_result (PyObject *result, const char *field_name)
+{
+  struct ui_out *uiout = current_uiout;
+
+  if (PyDict_Check (result))
+    {
+      PyObject *key, *value;
+      Py_ssize_t pos = 0;
+      ui_out_emit_tuple tuple_emitter (uiout, field_name);
+      while (PyDict_Next (result, &pos, &key, &value))
+	{
+	  if (!PyString_Check (key))
+	    {
+	      gdbpy_ref<> key_repr (PyObject_Repr (key));
+	      gdb::unique_xmalloc_ptr<char> key_repr_string;
+	      if (key_repr != nullptr)
+		key_repr_string
+		  = python_string_to_target_string (key_repr.get ());
+
+	      if (PyErr_Occurred () != nullptr)
+		gdbpy_handle_exception ();
+              else
+		error (_("non-string object used as key: %s"),
+		       key_repr_string.get ());
+	    }
+
+	  gdb::unique_xmalloc_ptr<char> key_string
+	    = python_string_to_target_string (key);
+	  if (key_string == nullptr)
+	    gdbpy_handle_exception ();
+	  parse_mi_result (value, key_string.get ());
+	}
+    }
+  else if (PySequence_Check (result) && !PyString_Check (result))
+    {
+      ui_out_emit_list list_emitter (uiout, field_name);
+      Py_ssize_t len = PySequence_Size (result);
+      if (len == -1)
+	gdbpy_handle_exception ();
+      for (Py_ssize_t i = 0; i < len; ++i)
+	{
+          gdbpy_ref<> item (PySequence_ITEM (result, i));
+	  if (item == nullptr)
+	    gdbpy_handle_exception ();
+	  parse_mi_result (item.get (), nullptr);
+	}
+    }
+  else if (PyIter_Check (result))
+    {
+      gdbpy_ref<> item;
+      ui_out_emit_list list_emitter (uiout, field_name);
+      while (true)
+	{
+	  item.reset (PyIter_Next (result));
+	  if (item == nullptr)
+	    {
+	      if (PyErr_Occurred () != nullptr)
+		gdbpy_handle_exception ();
+	      break;
+	    }
+	  parse_mi_result (item.get (), nullptr);
+	}
+    }
+  else
+    {
+      gdb::unique_xmalloc_ptr<char> string (gdbpy_obj_to_string (result));
+      if (string == nullptr)
+	gdbpy_handle_exception ();
+      uiout->field_string (field_name, string.get ());
+    }
+}
+
+/* Called when the mi command is invoked.  PARSE contains the parsed
+   command line arguments from the user.  */
+
+void
+mi_command_py::do_invoke (struct mi_parse *parse) const
+{
+  PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
+
+  pymicmd_debug_printf ("this = %p, name = %s", this, name ());
+
+  mi_parse_argv (parse->args, parse);
+
+  if (parse->argv == nullptr)
+    error (_("Problem parsing arguments: %s %s"), parse->command, parse->args);
+
+  PyObject *obj = (PyObject *) this->m_pyobj;
+  gdb_assert (obj != nullptr);
+
+  gdbpy_enter enter_py (get_current_arch (), current_language);
+
+  if (!PyObject_HasAttr (obj, invoke_cst))
+      error (_("-%s: Python command object missing 'invoke' method."),
+	     name ());
+
+  /* Place all the arguments into a list which we pass as a single
+     argument to the mi command's invoke method.  */
+  gdbpy_ref<> argobj (PyList_New (parse->argc));
+  if (argobj == nullptr)
+    {
+      gdbpy_print_stack ();
+      error (_("-%s: failed to create the Python arguments list."),
+	     name ());
+    }
+
+  for (int i = 0; i < parse->argc; ++i)
+    {
+      gdbpy_ref<> str (PyUnicode_Decode (parse->argv[i],
+					 strlen (parse->argv[i]),
+					 host_charset (), nullptr));
+      if (PyList_SetItem (argobj.get (), i, str.release ()) < 0)
+	{
+	  gdbpy_print_stack ();
+	  error (_("-%s: failed to create the Python arguments list."),
+		 name ());
+	}
+    }
+
+  gdb_assert (PyErr_Occurred () == nullptr);
+  gdbpy_ref<> result (PyObject_CallMethodObjArgs (obj, invoke_cst,
+						  argobj.get (), nullptr));
+  if (result == nullptr)
+    gdbpy_handle_exception ();
+
+  if (result != Py_None)
+    {
+      micmdpy_object *cmd = (micmdpy_object *) obj;
+      const char *result_name
+	= (cmd->mi_result_name == nullptr ? "result" : cmd->mi_result_name);
+      parse_mi_result (result.get (), result_name);
+    }
+}
+
+/* See declaration above.  */
+
+bool
+mi_command_py::validate_installation (micmdpy_object *cmd_obj)
+{
+  gdb_assert (cmd_obj != nullptr);
+  mi_command_py *cmd = cmd_obj->mi_command;
+  gdb_assert (cmd != nullptr);
+  const char *name = cmd_obj->mi_command_name;
+  gdb_assert (name != nullptr);
+  gdb_assert (name == cmd->name ());
+  mi_command *mi_cmd = mi_cmd_lookup (name);
+  gdb_assert (mi_cmd == cmd);
+  gdb_assert (cmd->m_pyobj == cmd_obj);
+
+  return true;
+}
+
+/* Return a reference to the gdb.mi_commands dictionary.  */
+
+static gdbpy_ref<>
+micmdpy_global_command_dictionary ()
+{
+  if (gdb_python_module == nullptr
+      || ! PyObject_HasAttrString (gdb_python_module, "mi_commands"))
+    error (_("unable to find gdb.mi_commands dictionary"));
+
+  gdbpy_ref<> mi_cmd_dict (PyObject_GetAttrString (gdb_python_module,
+						   "mi_commands"));
+  if (mi_cmd_dict == nullptr || !PyDict_Check (mi_cmd_dict.get ()))
+    error (_("unable to fetch gdb.mi_commands dictionary"));
+
+  return mi_cmd_dict;
+}
+
+/* Uninstall OBJ, making the mi command represented by OBJ unavailable for
+   use by the user.  On success 0 is returned, otherwise -1 is returned
+   and a python exception will be set.  */
+
+static int
+micmdpy_uninstall_command (micmdpy_object *obj)
+{
+  PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
+
+  gdb_assert (obj->mi_command != nullptr);
+  gdb_assert (obj->mi_command_name != nullptr);
+
+  pymicmd_debug_printf ("name = %s", obj->mi_command_name);
+
+  /* Remove the command from the internal mi table of commands, this will
+     cause the c++ object to be deleted, which will clear the mi_command
+     member variable within the python object.  */
+  remove_mi_cmd_entry (obj->mi_command);
+  gdb_assert (obj->mi_command == nullptr);
+
+  gdbpy_ref<> mi_cmd_dict = micmdpy_global_command_dictionary ();
+
+  /* Grab the name for this command.  */
+  gdbpy_ref<> name_obj
+    = host_string_to_python_string (obj->mi_command_name);
+  if (name_obj == nullptr)
+    return -1;
+
+  /* Lookup the gdb.MICommand object in the dictionary of all python mi
+     commands, this is gdb.mi_command, and remove it.  */
+  PyObject *curr = PyDict_GetItemWithError (mi_cmd_dict.get (),
+					    name_obj.get ());
+
+  /* Did we encounter an error?  Failing to find the object in the
+     dictionary isn't an error, that's fine.  */
+  if (curr == nullptr && PyErr_Occurred ())
+    return -1;
+
+  /* Did we find this command in the gdb.mi_commands dictionary?  If so,
+     then remove it.  */
+  if (curr != nullptr)
+    {
+      /* Yes we did!  Remove it.  */
+      if (PyDict_DelItem (mi_cmd_dict.get (), name_obj.get ()) < 0)
+	return -1;
+    }
+
+  return 0;
+}
+
+/* Install OBJ as a usable mi command.  Return 0 on success, and -1 on
+   error, in which case, a python error will have been set.
+
+   After successful completion the command name associated with OBJ will
+   be installed in the mi command table (so it can be found if the user
+   enters that command name), additionally, OBJ will have been added to
+   the gdb.mi_commands dictionary (using the command name as its key),
+   this will ensure that OBJ remains live even if the user gives up all
+   references.  */
+
+static int
+micmdpy_install_command (micmdpy_object *obj)
+{
+  PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
+
+  gdb_assert (obj->mi_command == nullptr);
+  gdb_assert (obj->mi_command_name != nullptr);
+
+  pymicmd_debug_printf ("name = %s", obj->mi_command_name);
+
+  gdbpy_ref<> mi_cmd_dict = micmdpy_global_command_dictionary ();
+
+  /* Look up this command name in the gdb.mi_commands dictionary, a command
+     with this name may already exist.  */
+  gdbpy_ref<> name_obj
+    = host_string_to_python_string (obj->mi_command_name);
+
+  PyObject *curr = PyDict_GetItemWithError (mi_cmd_dict.get (),
+					    name_obj.get ());
+  if (curr == nullptr && PyErr_Occurred ())
+    return -1;
+  if (curr != nullptr)
+    {
+      /* There is a command with this name already in the gdb.mi_commands
+	 dictionary.  First, validate that the object in the dictionary is
+	 of the expected type, just in case something weird has happened.  */
+      if (!PyObject_IsInstance (curr, (PyObject *) &micmdpy_object_type))
+	{
+	  PyErr_SetString (PyExc_RuntimeError,
+			   _("unexpected object in gdb.mi_commands dictionary"));
+	  return -1;
+	}
+
+      /* To get to this function OBJ should not be installed, which should
+	 mean OBJ is not in the gdb.mi_commands dictionary.  If we find
+	 that OBJ is the thing in the dictionary, then something weird is
+	 going on, we should throw an error.  */
+      micmdpy_object *other = (micmdpy_object *) curr;
+      if (other == obj || other->mi_command == nullptr)
+	{
+	  PyErr_SetString (PyExc_RuntimeError,
+			   _("uninstalled command found in gdb.mi_commands dictionary"));
+	  return -1;
+	}
+
+      /* All python mi command object should always have a name set.  */
+      gdb_assert (other->mi_command_name != nullptr);
+
+      /* We always insert commands into the gdb.mi_commands dictionary
+	 using their name as a key, if this check fails then the dictionary
+	 is in some weird state.  */
+      if (other->mi_command_name != other->mi_command->name ()
+	  || strcmp (other->mi_command_name, obj->mi_command_name) != 0)
+	{
+	  PyErr_SetString (PyExc_RuntimeError,
+			   _("gdb.mi_commands dictionary is corrupted"));
+	  return -1;
+	}
+
+      /* Switch the state of the c++ object held in the mi command table
+	 so that it now references OBJ.  After this action the old python
+	 object that used to be referenced from the mi command table will
+	 now show as uninstalled, while the new python object will show as
+	 installed.  */
+      other->mi_command->swap_python_object (obj);
+
+      gdb_assert (other->mi_command == nullptr);
+      gdb_assert (obj->mi_command != nullptr);
+      gdb_assert (obj->mi_command->name () == obj->mi_command_name);
+
+      /* Remove the previous python object from the gdb.mi_commands
+	 dictionary, we'll install the new object below.  */
+      if (PyDict_DelItem (mi_cmd_dict.get (), name_obj.get ()) < 0)
+       return -1;
+    }
+  else
+    {
+      /* There's no python object for this command name in the
+	 gdb.mi_commands dictionary from which we can steal an existing
+	 object already held in the mi commands table, and so, we now
+	 create a new c++ object, and install it into the mi table.  */
+      obj->mi_command = new mi_command_py (obj->mi_command_name, obj);
+      mi_command_up micommand (obj->mi_command);
+
+      /* Add the command to the gdb internal mi command table.  */
+      bool result = insert_mi_cmd_entry (std::move (micommand));
+      if (!result)
+	{
+	  PyErr_SetString (PyExc_RuntimeError,
+			   _("unable to add command, name may already be in use"));
+	  return -1;
+	}
+    }
+
+  /* Finally, add the python object to the gdb.mi_commands dictionary.  */
+  if (PyDict_SetItem (mi_cmd_dict.get (), name_obj.get (), (PyObject *) obj) < 0)
+    return -1;
+
+  return 0;
+}
+
+/* Implement gdb.MICommand.__init__.  The init method takes the name of
+   the mi command as the first argument, which must be a string, starting
+   with a single dash.  */
+
+static int
+micmdpy_init (PyObject *self, PyObject *args, PyObject *kwargs)
+{
+  PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
+
+  micmdpy_object *cmd = (micmdpy_object *) self;
+
+  static const char *keywords[] = { "name", "toplevel", nullptr };
+  const char *name;
+  const char *toplevel = nullptr;
+
+  if (!gdb_PyArg_ParseTupleAndKeywords (args, kwargs, "s|z", keywords,
+					&name, &toplevel))
+    return -1;
+
+  /* Validate command name */
+  const int name_len = strlen (name);
+  if (name_len == 0)
+    {
+      error (_("MI command name is empty."));
+      return -1;
+    }
+  else if ((name_len < 2) || (name[0] != '-') || !isalnum (name[1]))
+    {
+      error (_("MI command name does not start with '-'"
+               " followed by at least one letter or digit."));
+      return -1;
+    }
+  else
+    {
+      for (int i = 2; i < name_len; i++)
+	{
+	  if (!isalnum (name[i]) && name[i] != '-')
+	    {
+	      error (_("MI command name contains invalid character: %c."),
+		     name[i]);
+	      return -1;
+	    }
+	}
+
+      /* Skip over the leading dash.  For the rest of this function the
+	 dash is not important.  */
+      ++name;
+    }
+
+  /* Validate the requested name for the toplevel result.  Also, if the
+     user has provided the default then we don't need to store that as a
+     separate string.  */
+  if (toplevel != nullptr && *toplevel == '\0')
+    error (_("-%s: Invalid name for toplevel result."), name);
+  if (toplevel != nullptr && strcmp (toplevel, "result") == 0)
+    toplevel = nullptr;
+
+  /* This command may have been previously initialised.  If it has, discard
+     the previous toplevel result name, and store the new name.  */
+  xfree (cmd->mi_result_name);
+  if (toplevel != nullptr)
+    cmd->mi_result_name = xstrdup (toplevel);
+  else
+    cmd->mi_result_name = nullptr;
+
+  /* Check that there's an 'invoke' method.  */
+  if (!PyObject_HasAttr (self, invoke_cst))
+    error (_("-%s: Python command object missing 'invoke' method."), name);
+
+  /* If this object already has a name set, then this object has been
+     initialized before.  We handle this case a little differently.  */
+  if (cmd->mi_command_name != nullptr)
+    {
+      /* First, we don't allow the user to change the mi command name.
+	 Supporting this would be tricky as we would need to delete the
+	 mi_command_py from the mi command table, however, the user might
+	 be trying to perform this reinitialization from within the very
+	 command we're about to delete... it all gets very messy.
+
+	 So, for now at least, we don't allow this.  This doesn't seem like
+	 an excessive restriction.  */
+      if (strcmp (cmd->mi_command_name, name) != 0)
+	error (_("can't reinitialize object with a different command name"));
+
+      /* If there's already an object registered with the mi command table,
+	 then we're done.  That object must be a mi_command_py, which
+	 should reference back to this micmdpy_object.  */
+      if (cmd->mi_command != nullptr)
+	{
+	  gdb_assert (mi_command_py::validate_installation (cmd));
+	  return 0;
+	}
+    }
+  else
+    cmd->mi_command_name = xstrdup (name);
+
+  /* Now we can install this mi_command_py in the mi command table.  */
+  return micmdpy_install_command (cmd);
+}
+
+/* Called when a gdb.MICommand object is deallocated.  */
+
+static void
+micmdpy_dealloc (PyObject *obj)
+{
+  PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
+
+  micmdpy_object *cmd = (micmdpy_object *) obj;
+
+  /* If the python object failed to initialize, then the name field might
+     be nullptr.  */
+  pymicmd_debug_printf ("obj = %p, name = %s", cmd,
+			(cmd->mi_command_name == nullptr
+			 ? "(null)" : cmd->mi_command_name));
+
+  /* Remove the command from the mi command table if needed.  This will
+     cause the mi_command_py object to be deleted, which, in turn, will
+     clear the cmd->mi_command member variable, hence the assert.  */
+  if (cmd->mi_command != nullptr)
+    remove_mi_cmd_entry (cmd->mi_command);
+  gdb_assert (cmd->mi_command == nullptr);
+
+  /* Free the memory that holds the command name.  */
+  xfree (cmd->mi_command_name);
+  cmd->mi_command_name = nullptr;
+
+  /* Free the toplevel result name.  */
+  xfree (cmd->mi_result_name);
+  cmd->mi_result_name = nullptr;
+
+  /* Finally, free the memory for this python object.  */
+  Py_TYPE (obj)->tp_free (obj);
+}
+
+/* Python initialization for the mi commands components.  */
+
+int
+gdbpy_initialize_micommands ()
+{
+  micmdpy_object_type.tp_new = PyType_GenericNew;
+  if (PyType_Ready (&micmdpy_object_type) < 0)
+    return -1;
+
+  if (gdb_pymodule_addobject (gdb_module, "MICommand",
+			      (PyObject *) &micmdpy_object_type)
+      < 0)
+    return -1;
+
+  invoke_cst = PyString_FromString ("invoke");
+  if (invoke_cst == nullptr)
+    return -1;
+
+  return 0;
+}
+
+/* Get the gdb.MICommand.name attribute, returns a string, the name of this
+   mi command.  */
+
+static PyObject *
+micmdpy_get_name (PyObject *self, void *closure)
+{
+  struct micmdpy_object *micmd_obj = (struct micmdpy_object *) self;
+
+  gdb_assert (micmd_obj->mi_command_name != nullptr);
+  std::string name_str = string_printf ("-%s", micmd_obj->mi_command_name);
+  return PyString_FromString (name_str.c_str ());
+}
+
+/* Get the gdb.MICommand.installed property.  Returns true if this mi
+   command is installed into the mi command table, otherwise returns
+   false.  */
+
+static PyObject *
+micmdpy_get_installed (PyObject *self, void *closure)
+{
+  struct micmdpy_object *micmd_obj = (struct micmdpy_object *) self;
+
+  if (micmd_obj->mi_command == nullptr)
+    Py_RETURN_FALSE;
+  Py_RETURN_TRUE;
+}
+
+/* Set the gdb.MICommand.installed property.  The property can be set to
+   either true or false.  Setting the property to true will cause the
+   command to be installed into the mi command table (if it isn't
+   already), while setting this property to false will cause the command
+   to be removed from the mi command table (if it is present).  */
+
+static int
+micmdpy_set_installed (PyObject *self, PyObject *newvalue, void *closure)
+{
+  struct micmdpy_object *micmd_obj = (struct micmdpy_object *) self;
+
+  bool installed_p = PyObject_IsTrue (newvalue);
+  if (installed_p == (micmd_obj->mi_command != nullptr))
+    return 0;
+
+  if (installed_p)
+    return micmdpy_install_command (micmd_obj);
+  else
+    return micmdpy_uninstall_command (micmd_obj);
+}
+
+/* The gdb.MICommand properties.   */
+
+static gdb_PyGetSetDef micmdpy_object_getset[] = {
+  { "name", micmdpy_get_name, nullptr, "The command's name.", nullptr },
+  { "installed", micmdpy_get_installed, micmdpy_set_installed,
+    "Is this command installed for use.", nullptr },
+  { nullptr }	/* Sentinel.  */
+};
+
+/* The gdb.MICommand descriptor.  */
+
+PyTypeObject micmdpy_object_type = {
+  PyVarObject_HEAD_INIT (nullptr, 0) "gdb.MICommand", /*tp_name */
+  sizeof (micmdpy_object),			   /*tp_basicsize */
+  0,						   /*tp_itemsize */
+  micmdpy_dealloc,				   /*tp_dealloc */
+  0,						   /*tp_print */
+  0,						   /*tp_getattr */
+  0,						   /*tp_setattr */
+  0,						   /*tp_compare */
+  0,						   /*tp_repr */
+  0,						   /*tp_as_number */
+  0,						   /*tp_as_sequence */
+  0,						   /*tp_as_mapping */
+  0,						   /*tp_hash */
+  0,						   /*tp_call */
+  0,						   /*tp_str */
+  0,						   /*tp_getattro */
+  0,						   /*tp_setattro */
+  0,						   /*tp_as_buffer */
+  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,	/*tp_flags */
+  "GDB mi-command object",			   /* tp_doc */
+  0,						   /* tp_traverse */
+  0,						   /* tp_clear */
+  0,						   /* tp_richcompare */
+  0,						   /* tp_weaklistoffset */
+  0,						   /* tp_iter */
+  0,						   /* tp_iternext */
+  0,						   /* tp_methods */
+  0,						   /* tp_members */
+  micmdpy_object_getset,			   /* tp_getset */
+  0,						   /* tp_base */
+  0,						   /* tp_dict */
+  0,						   /* tp_descr_get */
+  0,						   /* tp_descr_set */
+  0,						   /* tp_dictoffset */
+  micmdpy_init,					   /* tp_init */
+  0,						   /* tp_alloc */
+};
+
+void _initialize_py_micmd ();
+void
+_initialize_py_micmd ()
+{
+  add_setshow_boolean_cmd
+    ("py-micmd", class_maintenance, &pymicmd_debug,
+     _("Set Python micmd debugging."),
+     _("Show Python micmd debugging."),
+     _("When on, Python micmd debugging is enabled."),
+     nullptr,
+     show_pymicmd_debug,
+     &setdebuglist, &showdebuglist);
+}
diff --git a/gdb/python/python-internal.h b/gdb/python/python-internal.h
index 583989c5a6d..d5a0b4a4a91 100644
--- a/gdb/python/python-internal.h
+++ b/gdb/python/python-internal.h
@@ -561,6 +561,8 @@ int gdbpy_initialize_membuf ()
   CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION;
 int gdbpy_initialize_connection ()
   CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION;
+int gdbpy_initialize_micommands (void)
+  CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION;
 
 /* A wrapper for PyErr_Fetch that handles reference counting for the
    caller.  */
diff --git a/gdb/python/python.c b/gdb/python/python.c
index 4dcda53d9ab..f2b09916374 100644
--- a/gdb/python/python.c
+++ b/gdb/python/python.c
@@ -1887,7 +1887,8 @@ do_start_initialization ()
       || gdbpy_initialize_unwind () < 0
       || gdbpy_initialize_membuf () < 0
       || gdbpy_initialize_connection () < 0
-      || gdbpy_initialize_tui () < 0)
+      || gdbpy_initialize_tui () < 0
+      || gdbpy_initialize_micommands () < 0)
     return false;
 
 #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base)	\
diff --git a/gdb/testsuite/gdb.python/py-mi-cmd-orig.exp b/gdb/testsuite/gdb.python/py-mi-cmd-orig.exp
new file mode 100644
index 00000000000..d8ea8bbfdab
--- /dev/null
+++ b/gdb/testsuite/gdb.python/py-mi-cmd-orig.exp
@@ -0,0 +1,140 @@
+# Copyright (C) 2019-2021 Free Software Foundation, Inc.
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Test custom MI commands implemented in Python.
+
+load_lib gdb-python.exp
+load_lib mi-support.exp
+set MIFLAGS "-i=mi2"
+
+gdb_exit
+if {[mi_gdb_start]} {
+    continue
+}
+
+if {[lsearch -exact [mi_get_features] python] < 0} {
+    unsupported "python support is disabled"
+    return -1
+}
+
+standard_testfile
+
+#
+# Start here
+#
+
+
+mi_gdb_test "set python print-stack full" \
+  ".*\\^done" \
+  "set python print-stack full"
+
+mi_gdb_test "source ${srcdir}/${subdir}/${testfile}.py" \
+  ".*\\^done" \
+  "load python file"
+
+mi_gdb_test "python pycmd1('-pycmd')" \
+  ".*\\^done" \
+  "define -pycmd MI command"
+
+
+mi_gdb_test "-pycmd int" \
+  "\\^done,result=\"42\"" \
+  "-pycmd int"
+
+mi_gdb_test "-pycmd str" \
+  "\\^done,result=\"Hello world!\"" \
+  "-pycmd str"
+
+mi_gdb_test "-pycmd ary" \
+  "\\^done,result=\\\[\"Hello\",\"42\"\\\]" \
+  "-pycmd ary"
+
+mi_gdb_test "-pycmd dct" \
+  "\\^done,result={hello=\"world\",times=\"42\"}" \
+  "-pycmd dct"
+
+setup_kfail "small change to error message format" *-*-*
+mi_gdb_test "-pycmd bk1" \
+  "\\^error,msg=\"Non-string object used as key: Bad Key\\.\"" \
+  "-pycmd bk1"
+
+setup_kfail "small change to error message format" *-*-*
+mi_gdb_test "-pycmd bk2" \
+  "\\^error,msg=\"Non-string object used as key: 1\\.\"" \
+  "-pycmd bk2"
+
+setup_kfail "bigger change to error message format" *-*-*
+mi_gdb_test "-pycmd bk3" \
+  "\\^error,msg=\"Non-string object used as key: __repr__ returned non-string .*" \
+  "-pycmd bk3"
+
+mi_gdb_test "-pycmd tpl" \
+  "\\^done,result=\\\[\"42\",\"Hello\"\\\]" \
+  "-pycmd tpl"
+
+mi_gdb_test "-pycmd itr" \
+  "\\^done,result=\\\[\"1\",\"2\",\"3\"\\\]" \
+  "-pycmd itr"
+
+mi_gdb_test "-pycmd nn1" \
+  "\\^done" \
+  "-pycmd nn1"
+
+mi_gdb_test "-pycmd nn2" \
+  "\\^done,result=\\\[\"None\"\\\]" \
+  "-pycmd nn2"
+
+setup_kfail "no prefix on error messages" *-*-*
+mi_gdb_test "-pycmd bogus" \
+  "\\^error,msg=\"-pycmd: Invalid parameter: bogus\"" \
+  "-pycmd bogus"
+
+setup_kfail "no prefix on error messages" *-*-*
+mi_gdb_test "-pycmd exp" \
+  "\\^error,msg=\"-pycmd: failed to execute command\"" \
+  "-pycmd exp"
+
+mi_gdb_test "python pycmd2('-pycmd')" \
+  ".*\\^done" \
+  "redefine -pycmd MI command from CLI command"
+
+mi_gdb_test "-pycmd str" \
+  "\\^done,result=\"Ciao!\"" \
+  "-pycmd str - redefined from CLI"
+
+setup_kfail "no prefix on error messages" *-*-*
+mi_gdb_test "-pycmd int" \
+  "\\^error,msg=\"-pycmd: Invalid parameter: int\"" \
+  "-pycmd int - redefined from CLI"
+
+setup_kfail "no prefix on error messages" *-*-*
+mi_gdb_test "-pycmd red" \
+    "\\^error,msg=\"-pycmd: Command redefined but we failing anyway\"" \
+  "redefine -pycmd MI command from Python MI command"
+
+mi_gdb_test "-pycmd int" \
+  "\\^done,result=\"42\"" \
+  "-pycmd int - redefined from MI"
+
+mi_gdb_test "python pycmd1('')" \
+  ".*\\^error,msg=\"MI command name is empty.\"" \
+  "empty MI command name"
+
+mi_gdb_test "python pycmd1('-')" \
+  ".*\\^error,msg=\"MI command name does not start with '-' followed by at least one letter or digit\\.\"" \
+  "invalid MI command name"
+
+mi_gdb_test "python pycmd1('-bad-character-@')" \
+  ".*\\^error,msg=\"MI command name contains invalid character: @\\.\"" \
+  "invalid character in MI command name"
diff --git a/gdb/testsuite/gdb.python/py-mi-cmd-orig.py b/gdb/testsuite/gdb.python/py-mi-cmd-orig.py
new file mode 100644
index 00000000000..2f6ba2f8037
--- /dev/null
+++ b/gdb/testsuite/gdb.python/py-mi-cmd-orig.py
@@ -0,0 +1,68 @@
+# Copyright (C) 2019-2021 Free Software Foundation, Inc.
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+import gdb
+
+class BadKey:
+    def __repr__(self):
+        return "Bad Key"
+
+class ReallyBadKey:
+    def __repr__(self):
+        return BadKey()
+
+
+class pycmd1(gdb.MICommand):
+    def invoke(self, argv):
+        if argv[0] == 'int':
+            return 42
+        elif argv[0] == 'str':
+            return "Hello world!"
+        elif argv[0] == 'ary':
+            return [ 'Hello', 42 ]
+        elif argv[0] == "dct":
+            return { 'hello' : 'world', 'times' : 42}
+        elif argv[0] == "bk1":
+            return { BadKey() : 'world' }
+        elif argv[0] == "bk2":
+            return { 1 : 'world' }
+        elif argv[0] == "bk3":
+            return { ReallyBadKey() : 'world' }
+        elif argv[0] == 'tpl':
+            return ( 42 , 'Hello' )
+        elif argv[0] == 'itr':
+            return iter([1,2,3])
+        elif argv[0] == 'nn1':
+            return None
+        elif argv[0] == 'nn2':
+            return [ None ]
+        elif argv[0] == 'red':
+            pycmd2('-pycmd')
+            return None
+        elif argv[0] == 'exp':
+            raise gdb.GdbError()
+        else:
+            raise gdb.GdbError("Invalid parameter: %s" % argv[0])
+
+
+class pycmd2(gdb.MICommand):
+    def invoke(self, argv):
+        if argv[0] == 'str':
+            return "Ciao!"
+        elif argv[0] == 'red':
+            pycmd1('-pycmd')
+            raise gdb.GdbError("Command redefined but we failing anyway")
+        else:
+            raise gdb.GdbError("Invalid parameter: %s" % argv[0])
+
diff --git a/gdb/testsuite/gdb.python/py-mi-cmd.exp b/gdb/testsuite/gdb.python/py-mi-cmd.exp
new file mode 100644
index 00000000000..d680aaf7adb
--- /dev/null
+++ b/gdb/testsuite/gdb.python/py-mi-cmd.exp
@@ -0,0 +1,258 @@
+# Copyright (C) 2019-2022 Free Software Foundation, Inc.
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Test custom MI commands implemented in Python.
+
+load_lib gdb-python.exp
+load_lib mi-support.exp
+set MIFLAGS "-i=mi2"
+
+gdb_exit
+if {[mi_gdb_start]} {
+    continue
+}
+
+if {[lsearch -exact [mi_get_features] python] < 0} {
+    unsupported "python support is disabled"
+    return -1
+}
+
+standard_testfile
+
+#
+# Start here
+#
+
+
+mi_gdb_test "set python print-stack full" \
+    ".*\\^done" \
+    "set python print-stack full"
+
+mi_gdb_test "source ${srcdir}/${subdir}/${testfile}.py" \
+    ".*\\^done" \
+    "load python file"
+
+mi_gdb_test "python pycmd1('-pycmd')" \
+    ".*\\^done" \
+    "define -pycmd MI command"
+
+
+mi_gdb_test "-pycmd int" \
+    "\\^done,result=\"42\"" \
+    "-pycmd int"
+
+mi_gdb_test "-pycmd str" \
+    "\\^done,result=\"Hello world!\"" \
+    "-pycmd str"
+
+mi_gdb_test "-pycmd ary" \
+    "\\^done,result=\\\[\"Hello\",\"42\"\\\]" \
+    "-pycmd ary"
+
+mi_gdb_test "-pycmd dct" \
+    "\\^done,result={hello=\"world\",times=\"42\"}" \
+    "-pycmd dct"
+
+mi_gdb_test "-pycmd bk1" \
+    "\\^error,msg=\"non-string object used as key: Bad Key\"" \
+    "-pycmd bk1"
+
+mi_gdb_test "-pycmd bk2" \
+    "\\^error,msg=\"non-string object used as key: 1\"" \
+    "-pycmd bk2"
+
+mi_gdb_test "-pycmd bk3" \
+    [multi_line \
+	 "&\"TypeError: __repr__ returned non-string \\(type BadKey\\)..\"" \
+	 "\\^error,msg=\"Error occurred in Python: __repr__ returned non-string \\(type BadKey\\)\""] \
+    "-pycmd bk3"
+
+mi_gdb_test "-pycmd tpl" \
+    "\\^done,result=\\\[\"42\",\"Hello\"\\\]" \
+    "-pycmd tpl"
+
+mi_gdb_test "-pycmd itr" \
+    "\\^done,result=\\\[\"1\",\"2\",\"3\"\\\]" \
+    "-pycmd itr"
+
+mi_gdb_test "-pycmd nn1" \
+    "\\^done" \
+    "-pycmd nn1"
+
+mi_gdb_test "-pycmd nn2" \
+    "\\^done,result=\\\[\"None\"\\\]" \
+    "-pycmd nn2"
+
+mi_gdb_test "-pycmd bogus" \
+    "\\^error,msg=\"Invalid parameter: bogus\"" \
+    "-pycmd bogus"
+
+# With this argument the command raises a gdb.GdbError with no message
+# string.  GDB considers this a bug in the user program, so prints a
+# backtrace, and a generic error message.
+mi_gdb_test "-pycmd exp" \
+    [multi_line ".*&\"Traceback \\(most recent call last\\):..\"" \
+	 "&\"\[^\r\n\]+${testfile}.py\[^\r\n\]+\"" \
+	 "&\"\[^\r\n\]+raise gdb.GdbError\\(\\)..\"" \
+	 "&\"gdb.GdbError..\"" \
+	 "\\^error,msg=\"Error occurred in Python\\.\""] \
+    "-pycmd exp"
+
+mi_gdb_test "python pycmd2('-pycmd')" \
+    ".*\\^done" \
+    "redefine -pycmd MI command from CLI command"
+
+mi_gdb_test "-pycmd str" \
+    "\\^done,result=\"Ciao!\"" \
+    "-pycmd str - redefined from CLI"
+
+mi_gdb_test "-pycmd int" \
+    "\\^error,msg=\"Invalid parameter: int\"" \
+    "-pycmd int - redefined from CLI"
+
+mi_gdb_test "-pycmd new" \
+    "\\^done" \
+    "Define new command -pycmd-new MI command from Python MI command"
+
+mi_gdb_test "-pycmd red" \
+    "\\^error,msg=\"Command redefined but we failing anyway\"" \
+    "redefine -pycmd MI command from Python MI command"
+
+mi_gdb_test "-pycmd int" \
+    "\\^done,result=\"42\"" \
+    "-pycmd int - redefined from MI"
+
+mi_gdb_test "-pycmd-new int" \
+    "\\^done,result=\"42\"" \
+    "-pycmd-new int - defined from MI"
+
+mi_gdb_test "python pycmd1('')" \
+    ".*\\^error,msg=\"MI command name is empty.\"" \
+    "empty MI command name"
+
+mi_gdb_test "python pycmd1('-')" \
+    ".*\\^error,msg=\"MI command name does not start with '-' followed by at least one letter or digit\\.\"" \
+    "invalid MI command name"
+
+mi_gdb_test "python pycmd1('-bad-character-@')" \
+    ".*\\^error,msg=\"MI command name contains invalid character: @\\.\"" \
+    "invalid character in MI command name"
+
+mi_gdb_test "python cmd=pycmd1('-abc')" \
+    ".*\\^done" \
+    "create command -abc, stored in a python variable"
+
+mi_gdb_test "python print(cmd.name)" \
+    ".*\r\n~\"-abc\\\\n\"\r\n\\^done" \
+    "print the name of the stored mi command"
+
+mi_gdb_test "python print(cmd.installed)" \
+    ".*\r\n~\"True\\\\n\"\r\n\\^done" \
+    "print the installed status of the stored mi command"
+
+mi_gdb_test "-abc str" \
+    "\\^done,result=\"Hello world!\"" \
+    "-abc str"
+
+mi_gdb_test "python cmd.installed = False" \
+    ".*\\^done" \
+    "uninstall the mi command"
+
+mi_gdb_test "-abc str" \
+    "\\^error,msg=\"Undefined MI command: abc\",code=\"undefined-command\"" \
+    "-abc str, but now the command is gone"
+
+mi_gdb_test "python cmd.installed = True" \
+    ".*\\^done" \
+    "re-install the mi command"
+
+mi_gdb_test "-abc str" \
+    "\\^done,result=\"Hello world!\"" \
+    "-abc str, the command is back again"
+
+mi_gdb_test "python other=pycmd2('-abc')" \
+    ".*\\^done" \
+    "create another command called -abc, stored in a separate python variable"
+
+mi_gdb_test "python print(other.installed)" \
+    ".*\r\n~\"True\\\\n\"\r\n\\^done" \
+    "print the installed status of the other stored mi command"
+
+mi_gdb_test "python print(cmd.installed)" \
+    ".*\r\n~\"False\\\\n\"\r\n\\^done" \
+    "print the installed status of the original stored mi command"
+
+mi_gdb_test "-abc str" \
+    "\\^done,result=\"Ciao!\"" \
+    "-abc str, when the other command is in place"
+
+mi_gdb_test "python cmd.installed = True" \
+    ".*\\^done" \
+    "re-install the original mi command"
+
+mi_gdb_test "-abc str" \
+    "\\^done,result=\"Hello world!\"" \
+    "-abc str, the original command is back again"
+
+mi_gdb_test "python print(other.installed)" \
+    ".*\r\n~\"False\\\\n\"\r\n\\^done" \
+    "the other command is now not installed"
+
+mi_gdb_test "python print(cmd.installed)" \
+    ".*\r\n~\"True\\\\n\"\r\n\\^done" \
+    "the original command is now installed"
+
+mi_gdb_test "python aa=pycmd3('-aa', 'message one')" \
+    ".*\\^done" \
+    "created a new -aa command"
+
+mi_gdb_test "-aa" \
+    ".*\\^done,xxx={msg=\"message one\"}" \
+    "call the -aa command"
+
+mi_gdb_test "python aa.__init__('-aa', 'message two')" \
+    ".*\\^done" \
+    "reinitialise -aa command with a new message"
+
+mi_gdb_test "-aa" \
+    ".*\\^done,xxx={msg=\"message two\"}" \
+    "call the -aa command, get the new message"
+
+mi_gdb_test "python aa.__init__('-bb', 'message three')" \
+    ".*\\^error,msg=\"can't reinitialize object with a different command name\"" \
+    "attempt to reinitialise aa variable to a new command name"
+
+mi_gdb_test "-aa" \
+    ".*\\^done,xxx={msg=\"message two\"}" \
+    "check the aa object has not changed after failed initialization"
+
+mi_gdb_test "python aa.installed = False" \
+    ".*\\^done" \
+    "uninstall the -aa command"
+
+mi_gdb_test "python aa.__init__('-bb', 'message three')" \
+    ".*\\^error,msg=\"can't reinitialize object with a different command name\"" \
+    "attempt to reinitialise aa variable to a new command name while uninstalled"
+
+mi_gdb_test "python aa.__init__('-aa', 'message three')" \
+    ".*\\^done" \
+    "reinitialise -aa command with a new message while uninstalled"
+
+mi_gdb_test "python aa.installed = True" \
+    ".*\\^done" \
+    "install the -aa command"
+
+mi_gdb_test "-aa" \
+    ".*\\^done,xxx={msg=\"message three\"}" \
+    "call the -aa command looking for message three"
diff --git a/gdb/testsuite/gdb.python/py-mi-cmd.py b/gdb/testsuite/gdb.python/py-mi-cmd.py
new file mode 100644
index 00000000000..e47034ae4b5
--- /dev/null
+++ b/gdb/testsuite/gdb.python/py-mi-cmd.py
@@ -0,0 +1,82 @@
+# Copyright (C) 2019-2022 Free Software Foundation, Inc.
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+import gdb
+
+class BadKey:
+    def __repr__(self):
+        return "Bad Key"
+
+class ReallyBadKey:
+    def __repr__(self):
+        return BadKey()
+
+
+class pycmd1(gdb.MICommand):
+    def invoke(self, argv):
+        if argv[0] == 'int':
+            return 42
+        elif argv[0] == 'str':
+            return "Hello world!"
+        elif argv[0] == 'ary':
+            return [ 'Hello', 42 ]
+        elif argv[0] == "dct":
+            return { 'hello' : 'world', 'times' : 42}
+        elif argv[0] == "bk1":
+            return { BadKey() : 'world' }
+        elif argv[0] == "bk2":
+            return { 1 : 'world' }
+        elif argv[0] == "bk3":
+            return { ReallyBadKey() : 'world' }
+        elif argv[0] == 'tpl':
+            return ( 42 , 'Hello' )
+        elif argv[0] == 'itr':
+            return iter([1,2,3])
+        elif argv[0] == 'nn1':
+            return None
+        elif argv[0] == 'nn2':
+            return [ None ]
+        elif argv[0] == 'red':
+            pycmd2('-pycmd')
+            return None
+        elif argv[0] == 'exp':
+            raise gdb.GdbError()
+        else:
+            raise gdb.GdbError("Invalid parameter: %s" % argv[0])
+
+
+class pycmd2(gdb.MICommand):
+    def invoke(self, argv):
+        if argv[0] == 'str':
+            return "Ciao!"
+        elif argv[0] == 'red':
+            pycmd1('-pycmd')
+            raise gdb.GdbError("Command redefined but we failing anyway")
+        elif argv[0] == 'new':
+            pycmd1('-pycmd-new')
+            return None
+        else:
+            raise gdb.GdbError("Invalid parameter: %s" % argv[0])
+
+
+# This class creates a command that returns a string, which is passed
+# when the command is created.  This class also makes use of a custom
+# toplevel result name, 'xxx' in this case.
+class pycmd3(gdb.MICommand):
+    def __init__(self, name, msg):
+        super(pycmd3, self).__init__(name, 'xxx')
+        self._msg = msg
+
+    def invoke(self, args):
+        return { 'msg' : self._msg }



More information about the Gdb-patches mailing list