LLDB mainline
CommandObjectScripting.cpp
Go to the documentation of this file.
1//===-- CommandObjectScripting.cpp ----------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "lldb/Core/Debugger.h"
13#include "lldb/Host/Config.h"
14#include "lldb/Host/Host.h"
23#include "lldb/Utility/Args.h"
25#include "lldb/Utility/Log.h"
26
27#include "llvm/ADT/StringMap.h"
28
29using namespace lldb;
30using namespace lldb_private;
31
32#define LLDB_OPTIONS_scripting_run
33#include "CommandOptions.inc"
34
36public:
39 interpreter, "scripting run",
40 "Invoke the script interpreter with provided code and display any "
41 "results. Start the interactive interpreter if no code is "
42 "supplied.",
43 "scripting run [--language <scripting-language> --] "
44 "[<script-code>]") {}
45
46 ~CommandObjectScriptingRun() override = default;
47
48 Options *GetOptions() override { return &m_options; }
49
50 class CommandOptions : public Options {
51 public:
52 CommandOptions() = default;
53 ~CommandOptions() override = default;
54 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
55 ExecutionContext *execution_context) override {
57 const int short_option = m_getopt_table[option_idx].val;
58
59 switch (short_option) {
60 case 'l':
62 option_arg, GetDefinitions()[option_idx].enum_values,
64 if (!error.Success())
66 "unrecognized value for language '%s'", option_arg.str().c_str());
67 break;
68 default:
69 llvm_unreachable("Unimplemented option");
70 }
71
72 return error;
73 }
74
75 void OptionParsingStarting(ExecutionContext *execution_context) override {
77 }
78
79 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
80 return llvm::ArrayRef(g_scripting_run_options);
81 }
82
84 };
85
86protected:
87 void DoExecute(llvm::StringRef command,
88 CommandReturnObject &result) override {
89 // Try parsing the language option but when the command contains a raw part
90 // separated by the -- delimiter.
91 OptionsWithRaw raw_args(command);
92 if (raw_args.HasArgs()) {
93 if (!ParseOptions(raw_args.GetArgs(), result))
94 return;
95 command = raw_args.GetRawPart();
96 }
97
98 lldb::ScriptLanguage language =
100 ? m_interpreter.GetDebugger().GetScriptLanguage()
101 : m_options.language;
102
103 if (language == lldb::eScriptLanguageNone) {
104 result.AppendError(
105 "the script-lang setting is set to none - scripting not available");
106 return;
107 }
108
109 ScriptInterpreter *script_interpreter =
110 GetDebugger().GetScriptInterpreter(true, language);
111
112 if (script_interpreter == nullptr) {
113 result.AppendError("no script interpreter");
114 return;
115 }
116
117 // Script might change Python code we use for formatting. Make sure we keep
118 // up to date with it.
120
121 if (command.empty()) {
122 script_interpreter->ExecuteInterpreterLoop();
124 return;
125 }
126
127 // We can do better when reporting the status of one-liner script execution.
128 if (script_interpreter->ExecuteOneLine(command, &result))
130 else
132 }
133
134private:
136};
137
138#define LLDB_OPTIONS_scripting_extension_list
139#include "CommandOptions.inc"
140
142public:
145 interpreter, "scripting extension list",
146 "List all the available scripting extension templates. ",
147 "scripting extension list [--language <scripting-language> --] "
148 "[--json --] [<extension-name> ...]") {
150 }
151
153
154 Options *GetOptions() override { return &m_options; }
155
156 void
163
164 class CommandOptions : public Options {
165 public:
166 CommandOptions() = default;
167 ~CommandOptions() override = default;
168 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
169 ExecutionContext *execution_context) override {
171 const int short_option = m_getopt_table[option_idx].val;
172
173 switch (short_option) {
174 case 'l':
176 option_arg, GetDefinitions()[option_idx].enum_values,
178 if (!error.Success())
180 "unrecognized value for language '{0}'", option_arg);
181 break;
182 case 'j':
183 m_json_format = true;
184 break;
185 default:
186 llvm_unreachable("Unimplemented option");
187 }
188
189 return error;
190 }
191
192 void OptionParsingStarting(ExecutionContext *execution_context) override {
194 m_json_format = false;
195 }
196
197 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
198 return llvm::ArrayRef(g_scripting_extension_list_options);
199 }
200
202 bool m_json_format = false;
203 };
204
205protected:
206 void DoExecute(Args &command, CommandReturnObject &result) override {
207 llvm::StringMap<std::vector<size_t>> grouped_by_extension;
208 for (size_t i = 0; i < PluginManager::GetNumScriptedInterfaces(); i++) {
209 lldb::ScriptedExtension extension =
211 if (extension == eScriptedExtensionInvalid)
212 continue;
213
214 llvm::StringLiteral extension_name =
216 if (grouped_by_extension.contains(extension_name))
217 grouped_by_extension[extension_name].push_back(i);
218 else
219 grouped_by_extension[extension_name] = {i};
220 }
221
222 if (command.GetArgumentCount() > 0) {
223 llvm::StringMap<std::vector<size_t>> filtered;
224 for (const Args::ArgEntry &arg : command.entries()) {
225 lldb::ScriptedExtension extension =
227 if (extension == eScriptedExtensionInvalid) {
228 result.AppendErrorWithFormat("no scripted extension named '%s'",
229 arg.c_str());
230 return;
231 }
232 llvm::StringLiteral extension_name =
234 auto it = grouped_by_extension.find(extension_name);
235 if (it != grouped_by_extension.end())
236 filtered[extension_name] = it->second;
237 }
238 grouped_by_extension = std::move(filtered);
239 }
240
241 if (m_options.m_json_format)
242 OutputJsonFormat(grouped_by_extension, result);
243 else
244 OutputTextFormat(grouped_by_extension, result);
245 }
246
247private:
248 std::vector<std::string>
249 GetLanguagesForExtension(const std::vector<size_t> &indices) {
250 std::vector<std::string> languages;
251 for (const size_t idx : indices) {
254 if (lang != m_options.m_language)
255 continue;
256 languages.push_back(ScriptInterpreter::LanguageToString(lang));
257 }
258 return languages;
259 }
260
262 const llvm::StringMap<std::vector<size_t>> &grouped_by_extension,
263 CommandReturnObject &result) {
264 llvm::json::Array extensions;
265 for (const auto &extension_pair : grouped_by_extension) {
266 // llvm::json::Value's StringRef constructor does not copy the
267 // underlying characters, so every string handed to the JSON structure
268 // below must be an owned std::string -- otherwise it dangles by the
269 // time the object tree is serialized at the end of this function.
270 llvm::json::Array languages;
271 for (const std::string &lang :
272 GetLanguagesForExtension(extension_pair.second))
273 languages.push_back(lang);
274 if (languages.empty())
275 continue;
276
277 llvm::StringRef desc =
279 extension_pair.second[0]);
282 extension_pair.second[0]);
283
284 llvm::json::Array api_usages;
285 for (llvm::StringRef usage : usages.GetSBAPIUsages())
286 api_usages.push_back(usage.str());
287
288 llvm::json::Array cmd_usages;
289 for (llvm::StringRef usage : usages.GetCommandInterpreterUsages())
290 cmd_usages.push_back(usage.str());
291
292 extensions.push_back(llvm::json::Object{
293 {"name", extension_pair.first().str()},
294 {"description", desc.str()},
295 {"languages", std::move(languages)},
296 {"api_usages", std::move(api_usages)},
297 {"command_interpreter_usages", std::move(cmd_usages)},
298 });
299 }
300
301 std::string str;
302 llvm::raw_string_ostream os(str);
303 os << llvm::formatv("{0:2}", llvm::json::Value(std::move(extensions)));
304 result.AppendMessage(str);
306 }
307
309 const llvm::StringMap<std::vector<size_t>> &grouped_by_extension,
310 CommandReturnObject &result) {
311 Stream &s = result.GetOutputStream();
312 const bool use_color = s.AsRawOstream().colors_enabled();
313 auto ansi_code = [use_color](llvm::StringRef code) {
314 return ansi::FormatAnsiTerminalCodes(code, use_color);
315 };
316 const std::string label_color = ansi_code("${ansi.fg.green}${ansi.bold}");
317 const std::string name_color = ansi_code("${ansi.fg.cyan}${ansi.bold}");
318 const std::string sep_color = ansi_code("${ansi.faint}");
319 const std::string reset = ansi_code("${ansi.normal}");
320 const std::string separator(
321 std::min<uint64_t>(GetDebugger().GetTerminalWidth(), 80), '-');
322
323 s.PutCString("Available scripted extension templates:");
324
325 auto print_field = [&](llvm::StringRef key, llvm::StringRef value,
326 const std::string &value_color = std::string()) {
327 if (value.empty())
328 return;
329 s.IndentMore();
330 s.Indent();
331 s << label_color << key << ": " << reset;
332 if (!value_color.empty())
333 s << value_color << value << reset;
334 else
335 s << value;
336 s << '\n';
337 s.IndentLess();
338 };
339
340 size_t num_listed_interface = 0;
341 for (const auto &extension_pair : grouped_by_extension) {
342 std::vector<std::string> languages =
343 GetLanguagesForExtension(extension_pair.second);
344 if (languages.empty())
345 continue;
346 num_listed_interface++;
347
348 s.EOL();
349 s << sep_color << separator << reset;
350 s.EOL();
351
352 llvm::StringRef desc =
354 extension_pair.second[0]);
357 extension_pair.second[0]);
358
359 print_field("Name", extension_pair.first(), name_color);
360 print_field("Description", desc);
361 print_field("Language", llvm::join(languages, ""));
362 usages.Dump(s, ScriptedInterfaceUsages::UsageKind::API, use_color);
364 use_color);
365 }
366
367 if (!num_listed_interface)
368 s << " None\n";
369
371 }
372
373private:
375};
376
377#define LLDB_OPTIONS_scripting_extension_generate
378#include "CommandOptions.inc"
379
381public:
383 : CommandObjectParsed(interpreter, "scripting extension generate",
384 "Generate a scripting extension template. ",
385 "scripting extension generate") {
387 }
388
390
391 Options *GetOptions() override { return &m_options; }
392
393 class CommandOptions : public Options {
394 public:
395 CommandOptions() = default;
396 ~CommandOptions() override = default;
397 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
398 ExecutionContext *execution_context) override {
400 const char short_option =
401 g_scripting_extension_generate_options[option_idx].short_option;
402
403 switch (short_option) {
404 case 'a':
406 break;
407 case 'l':
409 option_arg, GetDefinitions()[option_idx].enum_values,
411 if (!error.Success())
413 "unrecognized value for language '{0}'", option_arg);
414 break;
415 case 'n':
416 m_generated_class_prefix = option_arg.str();
417 break;
418 case 'o':
419 m_output_filepath = option_arg.str();
420 break;
421 case 'e': {
422 bool success;
423 m_open_editor = OptionArgParser::ToBoolean(option_arg, true, &success)
425 : eLazyBoolNo;
426 if (!success)
428 "invalid boolean value for -e: '{0}'", option_arg);
429 } break;
430 default:
431 llvm_unreachable("Unimplemented option");
432 }
433
434 return error;
435 }
436
444
445 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
446 return llvm::ArrayRef(g_scripting_extension_generate_options);
447 }
448
452 std::string m_output_filepath;
454 };
455
456 void
458 OptionElementVector &opt_element_vector) override {
459 // If `-l <lang>` was already given, complete only extensions available
460 // in that language. Bare `-l` (no value yet) and any parse failures
461 // fall back to language-agnostic completion.
463 llvm::ArrayRef<OptionDefinition> defs = m_options.GetDefinitions();
464 for (const OptionArgElement &elem : opt_element_vector) {
465 if (elem.opt_defs_index < 0 ||
466 static_cast<size_t>(elem.opt_defs_index) >= defs.size())
467 continue;
468 if (defs[elem.opt_defs_index].short_option != 'l' ||
469 elem.opt_arg_pos <= 0)
470 continue;
471 llvm::StringRef value =
472 request.GetParsedLine().GetArgumentAtIndex(elem.opt_arg_pos);
474 auto candidate =
476 value, defs[elem.opt_defs_index].enum_values,
478 if (error.Success())
479 language = candidate;
480 break;
481 }
483 request.GetCursorArgumentPrefix(), request, language);
486 }
487
488protected:
489 void DoExecute(Args &command, CommandReturnObject &result) override {
490 if (command.GetArgumentCount() == 0) {
491 result.SetError(
492 Status::FromErrorString("specify extension name to generate"));
493 return;
494 }
495
496 std::vector<ScriptInterpreter::ExtensionTemplateRequest> extension_requests;
497
498 for (size_t i = 0; i < command.GetArgumentCount(); i++) {
499 llvm::StringRef extension_name = command.GetArgumentAtIndex(i);
500 llvm::SmallVector<llvm::StringRef> extension_components;
501 extension_name.split(extension_components, ".");
502 lldb::ScriptedExtension extension =
503 ScriptInterpreter::StringToExtension(extension_components.back());
504 if (extension == eScriptedExtensionInvalid) {
506 "unknown scripted extension: '{0}'", extension_name));
507 return;
508 }
509 extension_requests.push_back({extension_name, extension_components});
510 }
511
512 lldb::ScriptLanguage language =
514 ? m_interpreter.GetDebugger().GetScriptLanguage()
515 : m_options.m_language;
516
517 if (language == lldb::eScriptLanguageNone) {
518 result.AppendError(
519 "the script-lang setting is set to none - scripting not available");
520 return;
521 }
522
523 ScriptInterpreter *script_interpreter =
524 GetDebugger().GetScriptInterpreter(true, language);
525
526 if (script_interpreter == nullptr) {
527 result.AppendError("no script interpreter");
528 return;
529 }
530
531 auto generated_file_or_err = script_interpreter->GenerateExtensionTemplate(
532 m_options.m_generated_class_prefix, extension_requests,
533 m_options.m_generate_non_abstract_methods, m_options.m_output_filepath);
534 if (!generated_file_or_err) {
535 result.SetError(generated_file_or_err.takeError());
536 return;
537 }
538
539 bool should_open_editor = false;
540 switch (m_options.m_open_editor) {
541 case eLazyBoolYes:
542 should_open_editor = true;
543 break;
544 case eLazyBoolNo:
545 should_open_editor = false;
546 break;
548 should_open_editor = result.GetInteractive();
549 break;
550 }
551
552 if (should_open_editor) {
553 if (llvm::Error err = Host::OpenFileInExternalEditor(
554 "", *generated_file_or_err, 1, true)) {
555 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(err),
556 "OpenFileInExternalEditor failed: {0}");
557 }
558 }
560 "Generated scripting extension template: {0}",
561 generated_file_or_err->GetPath());
563 }
564
565private:
567};
568
570public:
573 interpreter, "scripting extension",
574 "Commands for operating on the scripting extensions.",
575 "scripting extension [<subcommand-options>]") {
577 "list",
579 LoadSubCommand("generate",
581 interpreter)));
582 }
583
585};
586
588 CommandInterpreter &interpreter)
590 interpreter, "scripting",
591 "Commands for operating on the scripting functionalities.",
592 "scripting <subcommand> [<subcommand-options>]") {
593 LoadSubCommand("run",
595 LoadSubCommand("extension",
597 interpreter)));
598}
599
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
CommandObjectMultiwordScriptingExtension(CommandInterpreter &interpreter)
~CommandObjectMultiwordScriptingExtension() override=default
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
~CommandObjectScriptingExtensionGenerate() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectScriptingExtensionGenerate(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
void DoExecute(Args &command, CommandReturnObject &result) override
std::vector< std::string > GetLanguagesForExtension(const std::vector< size_t > &indices)
void OutputJsonFormat(const llvm::StringMap< std::vector< size_t > > &grouped_by_extension, CommandReturnObject &result)
~CommandObjectScriptingExtensionList() override=default
void OutputTextFormat(const llvm::StringMap< std::vector< size_t > > &grouped_by_extension, CommandReturnObject &result)
CommandObjectScriptingExtensionList(CommandInterpreter &interpreter)
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
CommandObjectScriptingRun(CommandInterpreter &interpreter)
void DoExecute(llvm::StringRef command, CommandReturnObject &result) override
~CommandObjectScriptingRun() override=default
A command line argument class.
Definition Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
llvm::ArrayRef< ArgEntry > entries() const
Definition Args.h:132
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
CommandObjectMultiwordScripting(CommandInterpreter &interpreter)
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
CommandObjectMultiword(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help="", llvm::StringRef syntax="", uint32_t flags=0)
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
CommandInterpreter & GetCommandInterpreter()
CommandInterpreter & m_interpreter
bool ParseOptions(Args &args, CommandReturnObject &result)
void AppendMessage(llvm::StringRef in_string)
void AppendError(llvm::StringRef in_string)
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void void AppendMessageWithFormatv(const char *format, Args &&...args)
"lldb/Utility/ArgCompletionRequest.h"
llvm::StringRef GetCursorArgumentPrefix() const
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
static llvm::Error OpenFileInExternalEditor(llvm::StringRef editor, const FileSpec &file_spec, uint32_t line_no, bool foreground=false)
A pair of an option list with a 'raw' string as a suffix.
Definition Args.h:319
bool HasArgs() const
Returns true if there are any arguments before the raw suffix.
Definition Args.h:330
Args & GetArgs()
Returns the list of arguments.
Definition Args.h:335
const std::string & GetRawPart() const
Returns the raw suffix part of the parsed string.
Definition Args.h:368
A command line option parsing protocol class.
Definition Options.h:58
std::vector< Option > m_getopt_table
Definition Options.h:198
static void AutoCompleteScriptedExtension(llvm::StringRef partial_name, CompletionRequest &request, lldb::ScriptLanguage language=lldb::eScriptLanguageUnknown)
static lldb::ScriptLanguage GetScriptedInterfaceLanguageAtIndex(uint32_t idx)
static uint32_t GetNumScriptedInterfaces()
static lldb::ScriptedExtension GetScriptedInterfaceExtensionAtIndex(uint32_t idx)
static llvm::StringRef GetScriptedInterfaceDescriptionAtIndex(uint32_t idx)
static ScriptedInterfaceUsages GetScriptedInterfaceUsagesAtIndex(uint32_t idx)
virtual llvm::Expected< FileSpec > GenerateExtensionTemplate(const std::string &name, std::vector< ExtensionTemplateRequest > &extensions, bool generate_non_abstract_methods, std::string output_file)
virtual void ExecuteInterpreterLoop()=0
static llvm::StringLiteral ExtensionToString(lldb::ScriptedExtension extension)
static lldb::ScriptedExtension StringToExtension(llvm::StringRef string)
virtual bool ExecuteOneLine(llvm::StringRef command, CommandReturnObject *result, const ExecuteScriptOptions &options=ExecuteScriptOptions())=0
static std::string LanguageToString(lldb::ScriptLanguage language)
void Dump(Stream &s, UsageKind kind, bool use_color=false) const
const std::vector< llvm::StringRef > & GetCommandInterpreterUsages() const
const std::vector< llvm::StringRef > & GetSBAPIUsages() const
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
A stream class that can stream formatted output to a file.
Definition Stream.h:28
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:155
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:204
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:201
std::string FormatAnsiTerminalCodes(llvm::StringRef format, bool do_color=true)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::vector< OptionArgElement > OptionElementVector
Definition Options.h:43
@ eScriptedExtensionCompletion
ScriptLanguage
Script interpreter types.
@ eScriptLanguageUnknown
@ eScriptLanguageDefault
@ eScriptLanguageNone
ScriptedExtension
Scripting extension types.
@ eScriptedExtensionInvalid
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
@ eReturnStatusFailed
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeScriptedExtension
static int64_t ToOptionEnum(llvm::StringRef s, const OptionEnumValues &enum_values, int32_t fail_value, Status &error)
static bool ToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr)