mirror of
https://sourceware.org/git/binutils-gdb.git
synced 2024-12-15 04:31:49 +08:00
740b42ceb7
This commit allows a 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, gdb/python/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 The version in this patch takes some core code from the previously posted patches, but also has some significant differences, especially after the feedback given here: https://sourceware.org/pipermail/gdb-patches/2022-February/185767.html A new MI command can be implemented in Python like this: class echo_args(gdb.MICommand): def invoke(self, args): return { 'args': args } echo_args("-echo-args") The 'args' parameter (to the invoke method) is a list containing (almost) all command line arguments passed to the MI command (--thread and --frame are handled before the Python code is called, and removed from the args list). This list can be empty if the MI command was passed no arguments. When used within gdb the above command produced output like this: (gdb) -echo-args a b c ^done,args=["a","b","c"] (gdb) The 'invoke' method of the new command must return a dictionary. The keys of this dictionary are then used as the field names in the mi command output (e.g. 'args' in the above). The values of the result returned by invoke can be dictionaries, lists, iterators, or an object that can be converted to a string. These are processed recursively to create the mi output. And so, this is valid: class new_command(gdb.MICommand): def invoke(self,args): return { 'result_one': { 'abc': 123, 'def': 'Hello' }, 'result_two': [ { 'a': 1, 'b': 2 }, { 'c': 3, 'd': 4 } ] } Which produces output like: (gdb) -new-command ^done,result_one={abc="123",def="Hello"},result_two=[{a="1",b="2"},{c="3",d="4"}] (gdb) I have required that the fields names used in mi result output must match the regexp: "^[a-zA-Z][-_a-zA-Z0-9]*$" (without the quotes). This restriction was never written down anywhere before, but seems sensible to me, and we can always loosen this rule later if it proves to be a problem. Much harder to try and add a restriction later, once people are already using the API. What follows are some details about how this implementation differs from the original patch that was posted to the mailing list. 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. Co-Authored-By: Jan Vrany <jan.vrany@labware.com>
121 lines
3.7 KiB
Python
121 lines
3.7 KiB
Python
# 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 {"result": 42}
|
|
elif argv[0] == "str":
|
|
return {"result": "Hello world!"}
|
|
elif argv[0] == "ary":
|
|
return {"result": ["Hello", 42]}
|
|
elif argv[0] == "dct":
|
|
return {"result": {"hello": "world", "times": 42}}
|
|
elif argv[0] == "bk1":
|
|
return {"result": {BadKey(): "world"}}
|
|
elif argv[0] == "bk2":
|
|
return {"result": {1: "world"}}
|
|
elif argv[0] == "bk3":
|
|
return {"result": {ReallyBadKey(): "world"}}
|
|
elif argv[0] == "tpl":
|
|
return {"result": (42, "Hello")}
|
|
elif argv[0] == "itr":
|
|
return {"result": iter([1, 2, 3])}
|
|
elif argv[0] == "nn1":
|
|
return None
|
|
elif argv[0] == "nn2":
|
|
return {"result": [None]}
|
|
elif argv[0] == "red":
|
|
pycmd2("-pycmd")
|
|
return None
|
|
elif argv[0] == "nd1":
|
|
return [1, 2, 3]
|
|
elif argv[0] == "nd2":
|
|
return 123
|
|
elif argv[0] == "nd3":
|
|
return "abc"
|
|
elif argv[0] == "ik1":
|
|
return {"xxx yyy": 123}
|
|
elif argv[0] == "ik2":
|
|
return {"result": {"xxx yyy": 123}}
|
|
elif argv[0] == "ik3":
|
|
return {"xxx+yyy": 123}
|
|
elif argv[0] == "ik4":
|
|
return {"xxx.yyy": 123}
|
|
elif argv[0] == "ik5":
|
|
return {"123xxxyyy": 123}
|
|
elif argv[0] == "empty_key":
|
|
return {"": 123}
|
|
elif argv[0] == "dash-key":
|
|
return {"the-key": 123}
|
|
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 {"result": "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.
|
|
class pycmd3(gdb.MICommand):
|
|
def __init__(self, name, msg, top_level):
|
|
super(pycmd3, self).__init__(name)
|
|
self._msg = msg
|
|
self._top_level = top_level
|
|
|
|
def invoke(self, args):
|
|
return {self._top_level: {"msg": self._msg}}
|
|
|
|
|
|
# A command that is missing it's invoke method.
|
|
class no_invoke(gdb.MICommand):
|
|
def __init__(self, name):
|
|
super(no_invoke, self).__init__(name)
|
|
|
|
|
|
def free_invoke(obj, args):
|
|
return {"result": args}
|
|
|
|
|
|
# Run some test involving catching exceptions. It's easier to write
|
|
# these as a Python function which is then called from the exp script.
|
|
def run_exception_tests():
|
|
print("PASS")
|