Skip to content

Commit a69ecb2

Browse files
authored
Add the ability to define a Python based command that uses CommandObjectParsed (#70734)
This allows you to specify options and arguments and their definitions and then have lldb handle the completions, help, etc. in the same way that lldb does for its parsed commands internally. This feature has some design considerations as well as the code, so I've also set up an RFC, but I did this one first and will put the RFC address in here once I've pushed it... Note, the lldb "ParsedCommand interface" doesn't actually do all the work that it should. For instance, saying the type of an option that has a completer doesn't automatically hook up the completer, and ditto for argument values. We also do almost no work to verify that the arguments match their definition, or do auto-completion for them. This patch allows you to make a command that's bug-for-bug compatible with built-in ones, but I didn't want to stall it on getting the auto-command checking to work all the way correctly. As an overall design note, my primary goal here was to make an interface that worked well in the script language. For that I needed, for instance, to have a property-based way to get all the option values that were specified. It was much more convenient to do that by making a fairly bare-bones C interface to define the options and arguments of a command, and set their values, and then wrap that in a Python class (installed along with the other bits of the lldb python module) which you can then derive from to make your new command. This approach will also make it easier to experiment. See the file test_commands.py in the test case for examples of how this works.
1 parent a04c636 commit a69ecb2

File tree

16 files changed

+1831
-106
lines changed

16 files changed

+1831
-106
lines changed

lldb/bindings/python/CMakeLists.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,13 +96,15 @@ function(finish_swig_python swig_target lldb_python_bindings_dir lldb_python_tar
9696
${lldb_python_target_dir}
9797
"utils"
9898
FILES "${LLDB_SOURCE_DIR}/examples/python/in_call_stack.py"
99-
"${LLDB_SOURCE_DIR}/examples/python/symbolication.py")
99+
"${LLDB_SOURCE_DIR}/examples/python/symbolication.py"
100+
)
100101

101102
create_python_package(
102103
${swig_target}
103104
${lldb_python_target_dir}
104105
"plugins"
105106
FILES
107+
"${LLDB_SOURCE_DIR}/examples/python/templates/parsed_cmd.py"
106108
"${LLDB_SOURCE_DIR}/examples/python/templates/scripted_process.py"
107109
"${LLDB_SOURCE_DIR}/examples/python/templates/scripted_platform.py"
108110
"${LLDB_SOURCE_DIR}/examples/python/templates/operating_system.py")

lldb/bindings/python/python-wrapper.swig

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -287,12 +287,12 @@ PythonObject lldb_private::python::SWIGBridge::LLDBSwigPythonCreateScriptedThrea
287287
}
288288

289289
bool lldb_private::python::SWIGBridge::LLDBSWIGPythonCallThreadPlan(
290-
void *implementor, const char *method_name, lldb_private::Event *event,
290+
void *implementer, const char *method_name, lldb_private::Event *event,
291291
bool &got_error) {
292292
got_error = false;
293293

294294
PyErr_Cleaner py_err_cleaner(false);
295-
PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementor));
295+
PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementer));
296296
auto pfunc = self.ResolveName<PythonCallable>(method_name);
297297

298298
if (!pfunc.IsAllocated())
@@ -325,12 +325,12 @@ bool lldb_private::python::SWIGBridge::LLDBSWIGPythonCallThreadPlan(
325325
}
326326

327327
bool lldb_private::python::SWIGBridge::LLDBSWIGPythonCallThreadPlan(
328-
void *implementor, const char *method_name, lldb_private::Stream *stream,
328+
void *implementer, const char *method_name, lldb_private::Stream *stream,
329329
bool &got_error) {
330330
got_error = false;
331331

332332
PyErr_Cleaner py_err_cleaner(false);
333-
PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementor));
333+
PythonObject self(PyRefType::Borrowed, static_cast<PyObject *>(implementer));
334334
auto pfunc = self.ResolveName<PythonCallable>(method_name);
335335

336336
if (!pfunc.IsAllocated())
@@ -831,6 +831,29 @@ bool lldb_private::python::SWIGBridge::LLDBSwigPythonCallCommandObject(
831831
return true;
832832
}
833833

834+
#include "lldb/Interpreter/CommandReturnObject.h"
835+
836+
bool lldb_private::python::SWIGBridge::LLDBSwigPythonCallParsedCommandObject(
837+
PyObject *implementor, lldb::DebuggerSP debugger, lldb_private::StructuredDataImpl &args_impl,
838+
lldb_private::CommandReturnObject &cmd_retobj,
839+
lldb::ExecutionContextRefSP exe_ctx_ref_sp) {
840+
841+
PyErr_Cleaner py_err_cleaner(true);
842+
843+
PythonObject self(PyRefType::Borrowed, implementor);
844+
auto pfunc = self.ResolveName<PythonCallable>("__call__");
845+
846+
if (!pfunc.IsAllocated()) {
847+
cmd_retobj.AppendError("Could not find '__call__' method in implementation class");
848+
return false;
849+
}
850+
851+
pfunc(SWIGBridge::ToSWIGWrapper(std::move(debugger)), SWIGBridge::ToSWIGWrapper(args_impl),
852+
SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp), SWIGBridge::ToSWIGWrapper(cmd_retobj).obj());
853+
854+
return true;
855+
}
856+
834857
PythonObject lldb_private::python::SWIGBridge::LLDBSWIGPythonCreateOSPlugin(
835858
const char *python_class_name, const char *session_dictionary_name,
836859
const lldb::ProcessSP &process_sp) {

lldb/examples/python/cmdtemplate.py

Lines changed: 49 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -11,115 +11,84 @@
1111

1212
import inspect
1313
import lldb
14-
import optparse
15-
import shlex
1614
import sys
15+
from lldb.plugins.parsed_cmd import ParsedCommand
1716

18-
19-
class FrameStatCommand:
17+
class FrameStatCommand(ParsedCommand):
2018
program = "framestats"
2119

2220
@classmethod
2321
def register_lldb_command(cls, debugger, module_name):
24-
parser = cls.create_options()
25-
cls.__doc__ = parser.format_help()
26-
# Add any commands contained in this module to LLDB
27-
command = "command script add -o -c %s.%s %s" % (
28-
module_name,
29-
cls.__name__,
30-
cls.program,
31-
)
32-
debugger.HandleCommand(command)
22+
ParsedCommandBase.do_register_cmd(cls, debugger, module_name)
3323
print(
3424
'The "{0}" command has been installed, type "help {0}" or "{0} '
3525
'--help" for detailed help.'.format(cls.program)
3626
)
3727

38-
@classmethod
39-
def create_options(cls):
40-
usage = "usage: %prog [options]"
41-
description = (
42-
"This command is meant to be an example of how to make "
43-
"an LLDB command that does something useful, follows "
44-
"best practices, and exploits the SB API. "
45-
"Specifically, this command computes the aggregate "
46-
"and average size of the variables in the current "
47-
"frame and allows you to tweak exactly which variables "
48-
"are to be accounted in the computation."
49-
)
28+
def setup_command_definition(self):
5029

51-
# Pass add_help_option = False, since this keeps the command in line
52-
# with lldb commands, and we wire up "help command" to work by
53-
# providing the long & short help methods below.
54-
parser = optparse.OptionParser(
55-
description=description,
56-
prog=cls.program,
57-
usage=usage,
58-
add_help_option=False,
30+
self.ov_parser.add_option(
31+
"i",
32+
"in-scope",
33+
help = "in_scope_only = True",
34+
value_type = lldb.eArgTypeBoolean,
35+
dest = "bool_arg",
36+
default = True,
5937
)
6038

61-
parser.add_option(
62-
"-i",
63-
"--in-scope",
64-
action="store_true",
65-
dest="inscope",
66-
help="in_scope_only = True",
39+
self.ov_parser.add_option(
40+
"i",
41+
"in-scope",
42+
help = "in_scope_only = True",
43+
value_type = lldb.eArgTypeBoolean,
44+
dest = "inscope",
6745
default=True,
6846
)
69-
70-
parser.add_option(
71-
"-a",
72-
"--arguments",
73-
action="store_true",
74-
dest="arguments",
75-
help="arguments = True",
76-
default=True,
47+
48+
self.ov_parser.add_option(
49+
"a",
50+
"arguments",
51+
help = "arguments = True",
52+
value_type = lldb.eArgTypeBoolean,
53+
dest = "arguments",
54+
default = True,
7755
)
7856

79-
parser.add_option(
80-
"-l",
81-
"--locals",
82-
action="store_true",
83-
dest="locals",
84-
help="locals = True",
85-
default=True,
57+
self.ov_parser.add_option(
58+
"l",
59+
"locals",
60+
help = "locals = True",
61+
value_type = lldb.eArgTypeBoolean,
62+
dest = "locals",
63+
default = True,
8664
)
8765

88-
parser.add_option(
89-
"-s",
90-
"--statics",
91-
action="store_true",
92-
dest="statics",
93-
help="statics = True",
94-
default=True,
66+
self.ov_parser.add_option(
67+
"s",
68+
"statics",
69+
help = "statics = True",
70+
value_type = lldb.eArgTypeBoolean,
71+
dest = "statics",
72+
default = True,
9573
)
9674

97-
return parser
98-
9975
def get_short_help(self):
10076
return "Example command for use in debugging"
10177

10278
def get_long_help(self):
103-
return self.help_string
79+
return ("This command is meant to be an example of how to make "
80+
"an LLDB command that does something useful, follows "
81+
"best practices, and exploits the SB API. "
82+
"Specifically, this command computes the aggregate "
83+
"and average size of the variables in the current "
84+
"frame and allows you to tweak exactly which variables "
85+
"are to be accounted in the computation.")
86+
10487

10588
def __init__(self, debugger, unused):
106-
self.parser = self.create_options()
107-
self.help_string = self.parser.format_help()
89+
super().__init__(debugger, unused)
10890

10991
def __call__(self, debugger, command, exe_ctx, result):
110-
# Use the Shell Lexer to properly parse up command options just like a
111-
# shell would
112-
command_args = shlex.split(command)
113-
114-
try:
115-
(options, args) = self.parser.parse_args(command_args)
116-
except:
117-
# if you don't handle exceptions, passing an incorrect argument to
118-
# the OptionParser will cause LLDB to exit (courtesy of OptParse
119-
# dealing with argument errors by throwing SystemExit)
120-
result.SetError("option parsing failed")
121-
return
122-
12392
# Always get program state from the lldb.SBExecutionContext passed
12493
# in as exe_ctx
12594
frame = exe_ctx.GetFrame()
@@ -128,7 +97,7 @@ def __call__(self, debugger, command, exe_ctx, result):
12897
return
12998

13099
variables_list = frame.GetVariables(
131-
options.arguments, options.locals, options.statics, options.inscope
100+
self.ov_parser.arguments, self.ov_parser.locals, self.ov_parser.statics, self.ov_parser.inscope
132101
)
133102
variables_count = variables_list.GetSize()
134103
if variables_count == 0:

0 commit comments

Comments
 (0)