1 //===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 #include "CommandObjectScript.h"
15 #include "lldb/Interpreter/CommandObjectRegexCommand.h"
17 #include "../Commands/CommandObjectApropos.h"
18 #include "../Commands/CommandObjectArgs.h"
19 #include "../Commands/CommandObjectBreakpoint.h"
20 #include "../Commands/CommandObjectBugreport.h"
21 #include "../Commands/CommandObjectCommands.h"
22 #include "../Commands/CommandObjectDisassemble.h"
23 #include "../Commands/CommandObjectExpression.h"
24 #include "../Commands/CommandObjectFrame.h"
25 #include "../Commands/CommandObjectGUI.h"
26 #include "../Commands/CommandObjectHelp.h"
27 #include "../Commands/CommandObjectLanguage.h"
28 #include "../Commands/CommandObjectLog.h"
29 #include "../Commands/CommandObjectMemory.h"
30 #include "../Commands/CommandObjectPlatform.h"
31 #include "../Commands/CommandObjectPlugin.h"
32 #include "../Commands/CommandObjectProcess.h"
33 #include "../Commands/CommandObjectQuit.h"
34 #include "../Commands/CommandObjectRegister.h"
35 #include "../Commands/CommandObjectSettings.h"
36 #include "../Commands/CommandObjectSource.h"
37 #include "../Commands/CommandObjectSyntax.h"
38 #include "../Commands/CommandObjectTarget.h"
39 #include "../Commands/CommandObjectThread.h"
40 #include "../Commands/CommandObjectType.h"
41 #include "../Commands/CommandObjectVersion.h"
42 #include "../Commands/CommandObjectWatchpoint.h"
44 #include "lldb/Core/Debugger.h"
45 #include "lldb/Core/PluginManager.h"
46 #include "lldb/Core/State.h"
47 #include "lldb/Core/StreamFile.h"
48 #include "lldb/Utility/Log.h"
49 #include "lldb/Utility/Stream.h"
50 #include "lldb/Utility/Timer.h"
52 #ifndef LLDB_DISABLE_LIBEDIT
53 #include "lldb/Host/Editline.h"
55 #include "lldb/Host/Host.h"
56 #include "lldb/Host/HostInfo.h"
58 #include "lldb/Interpreter/Args.h"
59 #include "lldb/Interpreter/CommandCompletions.h"
60 #include "lldb/Interpreter/CommandInterpreter.h"
61 #include "lldb/Interpreter/CommandReturnObject.h"
62 #include "lldb/Interpreter/OptionValueProperties.h"
63 #include "lldb/Interpreter/Options.h"
64 #include "lldb/Interpreter/Property.h"
66 #include "lldb/Target/Process.h"
67 #include "lldb/Target/TargetList.h"
68 #include "lldb/Target/Thread.h"
70 #include "lldb/Utility/CleanUp.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallString.h"
74 #include "llvm/Support/Path.h"
75 #include "llvm/Support/PrettyStackTrace.h"
78 using namespace lldb_private;
80 static const char *k_white_space = " \t\v";
82 static PropertyDefinition g_properties[] = {
83 {"expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr,
84 nullptr, "If true, regular expression alias commands will show the "
85 "expanded command that will be executed. This can be used to "
86 "debug new regular expression alias commands."},
87 {"prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
88 "If true, LLDB will prompt you before quitting if there are any live "
89 "processes being debugged. If false, LLDB will quit without asking in any "
91 {"stop-command-source-on-error", OptionValue::eTypeBoolean, true, true,
92 nullptr, nullptr, "If true, LLDB will stop running a 'command source' "
93 "script upon encountering an error."},
94 {"space-repl-prompts", OptionValue::eTypeBoolean, true, false, nullptr,
96 "If true, blank lines will be printed between between REPL submissions."},
97 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
100 ePropertyExpandRegexAliases = 0,
101 ePropertyPromptOnQuit = 1,
102 ePropertyStopCmdSourceOnError = 2,
103 eSpaceReplPrompts = 3
106 ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
107 static ConstString class_name("lldb.commandInterpreter");
111 CommandInterpreter::CommandInterpreter(Debugger &debugger,
112 ScriptLanguage script_language,
113 bool synchronous_execution)
114 : Broadcaster(debugger.GetBroadcasterManager(),
115 CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
116 Properties(OptionValuePropertiesSP(
117 new OptionValueProperties(ConstString("interpreter")))),
118 IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
119 m_debugger(debugger), m_synchronous_execution(synchronous_execution),
120 m_skip_lldbinit_files(false), m_skip_app_init_files(false),
121 m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
122 m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
123 m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
124 m_stopped_for_crash(false) {
125 debugger.SetScriptLanguage(script_language);
126 SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
127 SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
128 SetEventName(eBroadcastBitQuitCommandReceived, "quit");
129 CheckInWithManager();
130 m_collection_sp->Initialize(g_properties);
133 bool CommandInterpreter::GetExpandRegexAliases() const {
134 const uint32_t idx = ePropertyExpandRegexAliases;
135 return m_collection_sp->GetPropertyAtIndexAsBoolean(
136 nullptr, idx, g_properties[idx].default_uint_value != 0);
139 bool CommandInterpreter::GetPromptOnQuit() const {
140 const uint32_t idx = ePropertyPromptOnQuit;
141 return m_collection_sp->GetPropertyAtIndexAsBoolean(
142 nullptr, idx, g_properties[idx].default_uint_value != 0);
145 void CommandInterpreter::SetPromptOnQuit(bool b) {
146 const uint32_t idx = ePropertyPromptOnQuit;
147 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
150 void CommandInterpreter::ResolveCommand(const char *command_line,
151 CommandReturnObject &result) {
152 std::string command = command_line;
153 if (ResolveCommandImpl(command, result) != nullptr) {
154 result.AppendMessageWithFormat("%s", command.c_str());
155 result.SetStatus(eReturnStatusSuccessFinishResult);
159 bool CommandInterpreter::GetStopCmdSourceOnError() const {
160 const uint32_t idx = ePropertyStopCmdSourceOnError;
161 return m_collection_sp->GetPropertyAtIndexAsBoolean(
162 nullptr, idx, g_properties[idx].default_uint_value != 0);
165 bool CommandInterpreter::GetSpaceReplPrompts() const {
166 const uint32_t idx = eSpaceReplPrompts;
167 return m_collection_sp->GetPropertyAtIndexAsBoolean(
168 nullptr, idx, g_properties[idx].default_uint_value != 0);
171 void CommandInterpreter::Initialize() {
172 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
173 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
175 CommandReturnObject result;
177 LoadCommandDictionary();
179 // An alias arguments vector to reuse - reset it before use...
180 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
182 // Set up some initial aliases.
183 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
185 AddAlias("q", cmd_obj_sp);
186 AddAlias("exit", cmd_obj_sp);
189 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
191 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
193 cmd_obj_sp = GetCommandSPExact("process detach", false);
195 AddAlias("detach", cmd_obj_sp);
198 cmd_obj_sp = GetCommandSPExact("process continue", false);
200 AddAlias("c", cmd_obj_sp);
201 AddAlias("continue", cmd_obj_sp);
204 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
206 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
208 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
210 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
212 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
214 AddAlias("stepi", cmd_obj_sp);
215 AddAlias("si", cmd_obj_sp);
218 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
220 AddAlias("nexti", cmd_obj_sp);
221 AddAlias("ni", cmd_obj_sp);
224 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
226 AddAlias("s", cmd_obj_sp);
227 AddAlias("step", cmd_obj_sp);
228 CommandAlias *sif_alias = AddAlias(
229 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
231 sif_alias->SetHelp("Step through the current block, stopping if you step "
232 "directly into a function whose name matches the "
233 "TargetFunctionName.");
234 sif_alias->SetSyntax("sif <TargetFunctionName>");
238 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
240 AddAlias("n", cmd_obj_sp);
241 AddAlias("next", cmd_obj_sp);
244 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
246 AddAlias("finish", cmd_obj_sp);
249 cmd_obj_sp = GetCommandSPExact("frame select", false);
251 AddAlias("f", cmd_obj_sp);
254 cmd_obj_sp = GetCommandSPExact("thread select", false);
256 AddAlias("t", cmd_obj_sp);
259 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
261 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
262 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
265 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
267 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
268 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
271 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
273 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
275 cmd_obj_sp = GetCommandSPExact("memory read", false);
277 AddAlias("x", cmd_obj_sp);
279 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
281 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
283 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
285 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
287 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
289 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
291 cmd_obj_sp = GetCommandSPExact("disassemble", false);
293 AddAlias("dis", cmd_obj_sp);
295 cmd_obj_sp = GetCommandSPExact("disassemble", false);
297 AddAlias("di", cmd_obj_sp);
299 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
301 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
303 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
305 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
307 cmd_obj_sp = GetCommandSPExact("target create", false);
309 AddAlias("file", cmd_obj_sp);
311 cmd_obj_sp = GetCommandSPExact("target modules", false);
313 AddAlias("image", cmd_obj_sp);
315 alias_arguments_vector_sp.reset(new OptionArgVector);
317 cmd_obj_sp = GetCommandSPExact("expression", false);
319 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
320 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
321 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
322 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
323 po->SetHelp("Evaluate an expression on the current thread. Displays any "
324 "returned value with formatting "
325 "controlled by the type's author.");
328 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
329 AddAlias("poarray", cmd_obj_sp,
330 "--object-description --element-count %1 --")
334 cmd_obj_sp = GetCommandSPExact("process kill", false);
336 AddAlias("kill", cmd_obj_sp);
339 cmd_obj_sp = GetCommandSPExact("process launch", false);
341 alias_arguments_vector_sp.reset(new OptionArgVector);
342 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
343 AddAlias("r", cmd_obj_sp, "--");
344 AddAlias("run", cmd_obj_sp, "--");
346 #if defined(__APPLE__)
347 std::string shell_option;
348 shell_option.append("--shell-expand-args");
349 shell_option.append(" true");
350 shell_option.append(" --");
351 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
352 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
354 StreamString defaultshell;
355 defaultshell.Printf("--shell=%s --",
356 HostInfo::GetDefaultShell().GetPath().c_str());
357 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
358 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
363 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
365 AddAlias("add-dsym", cmd_obj_sp);
368 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
370 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
374 void CommandInterpreter::Clear() {
375 m_command_io_handler_sp.reset();
377 if (m_script_interpreter_sp)
378 m_script_interpreter_sp->Clear();
381 const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
382 // This function has not yet been implemented.
384 // Look for any embedded script command
386 // get interpreter object from the command dictionary,
387 // call execute_one_command on it,
388 // get the results as a string,
389 // substitute that string for current stuff.
394 void CommandInterpreter::LoadCommandDictionary() {
395 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
396 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
398 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
400 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
401 m_command_dict["breakpoint"] =
402 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
403 m_command_dict["bugreport"] =
404 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
405 m_command_dict["command"] =
406 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
407 m_command_dict["disassemble"] =
408 CommandObjectSP(new CommandObjectDisassemble(*this));
409 m_command_dict["expression"] =
410 CommandObjectSP(new CommandObjectExpression(*this));
411 m_command_dict["frame"] =
412 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
413 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
414 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
415 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
416 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
417 m_command_dict["platform"] =
418 CommandObjectSP(new CommandObjectPlatform(*this));
419 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
420 m_command_dict["process"] =
421 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
422 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
423 m_command_dict["register"] =
424 CommandObjectSP(new CommandObjectRegister(*this));
425 m_command_dict["script"] =
426 CommandObjectSP(new CommandObjectScript(*this, script_language));
427 m_command_dict["settings"] =
428 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
429 m_command_dict["source"] =
430 CommandObjectSP(new CommandObjectMultiwordSource(*this));
431 m_command_dict["target"] =
432 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
433 m_command_dict["thread"] =
434 CommandObjectSP(new CommandObjectMultiwordThread(*this));
435 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
436 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
437 m_command_dict["watchpoint"] =
438 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
439 m_command_dict["language"] =
440 CommandObjectSP(new CommandObjectLanguage(*this));
442 const char *break_regexes[][2] = {
443 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
444 "breakpoint set --file '%1' --line %2"},
445 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
446 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
447 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
448 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
449 "breakpoint set --name '%1'"},
450 {"^(-.*)$", "breakpoint set %1"},
451 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
452 "breakpoint set --name '%2' --shlib '%1'"},
453 {"^\\&(.*[^[:space:]])[[:space:]]*$",
454 "breakpoint set --name '%1' --skip-prologue=0"},
455 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
456 "breakpoint set --name '%1'"}};
458 size_t num_regexes = llvm::array_lengthof(break_regexes);
460 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
461 new CommandObjectRegexCommand(
462 *this, "_regexp-break",
463 "Set a breakpoint using one of several shorthand formats.\n",
465 "_regexp-break <filename>:<linenum>\n"
466 " main.c:12 // Break at line 12 of "
468 "_regexp-break <linenum>\n"
469 " 12 // Break at line 12 of current "
471 "_regexp-break 0x<address>\n"
472 " 0x1234000 // Break at address "
474 "_regexp-break <name>\n"
475 " main // Break in 'main' after the "
477 "_regexp-break &<name>\n"
478 " &main // Break at first instruction "
480 "_regexp-break <module>`<name>\n"
481 " libc.so`malloc // Break in 'malloc' from "
483 "_regexp-break /<source-regex>/\n"
484 " /break here/ // Break on source lines in "
486 " // containing text 'break "
488 2, CommandCompletions::eSymbolCompletion |
489 CommandCompletions::eSourceFileCompletion,
492 if (break_regex_cmd_ap.get()) {
494 for (size_t i = 0; i < num_regexes; i++) {
495 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
496 break_regexes[i][1]);
501 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
504 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
505 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
509 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
510 new CommandObjectRegexCommand(
511 *this, "_regexp-tbreak",
512 "Set a one-shot breakpoint using one of several shorthand formats.\n",
514 "_regexp-break <filename>:<linenum>\n"
515 " main.c:12 // Break at line 12 of "
517 "_regexp-break <linenum>\n"
518 " 12 // Break at line 12 of current "
520 "_regexp-break 0x<address>\n"
521 " 0x1234000 // Break at address "
523 "_regexp-break <name>\n"
524 " main // Break in 'main' after the "
526 "_regexp-break &<name>\n"
527 " &main // Break at first instruction "
529 "_regexp-break <module>`<name>\n"
530 " libc.so`malloc // Break in 'malloc' from "
532 "_regexp-break /<source-regex>/\n"
533 " /break here/ // Break on source lines in "
535 " // containing text 'break "
537 2, CommandCompletions::eSymbolCompletion |
538 CommandCompletions::eSourceFileCompletion,
541 if (tbreak_regex_cmd_ap.get()) {
543 for (size_t i = 0; i < num_regexes; i++) {
544 // If you add a resultant command string longer than 1024 characters be
545 // sure to increase the size of this buffer.
548 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
549 assert(num_printed < 1024);
550 UNUSED_IF_ASSERT_DISABLED(num_printed);
552 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
557 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
560 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
561 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
566 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
567 new CommandObjectRegexCommand(
568 *this, "_regexp-attach", "Attach to process by ID or name.",
569 "_regexp-attach <pid> | <process-name>", 2, 0, false));
570 if (attach_regex_cmd_ap.get()) {
571 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
572 "process attach --pid %1") &&
573 attach_regex_cmd_ap->AddRegexCommand(
574 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
575 // specified get passed to
577 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
578 "process attach --name '%1'") &&
579 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
580 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
581 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
586 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
587 new CommandObjectRegexCommand(*this, "_regexp-down",
588 "Select a newer stack frame. Defaults to "
589 "moving one frame, a numeric argument can "
590 "specify an arbitrary number.",
591 "_regexp-down [<count>]", 2, 0, false));
592 if (down_regex_cmd_ap.get()) {
593 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
594 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
595 "frame select -r -%1")) {
596 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
597 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
601 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
602 new CommandObjectRegexCommand(
604 "Select an older stack frame. Defaults to moving one "
605 "frame, a numeric argument can specify an arbitrary number.",
606 "_regexp-up [<count>]", 2, 0, false));
607 if (up_regex_cmd_ap.get()) {
608 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
609 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
610 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
611 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
615 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
616 new CommandObjectRegexCommand(
617 *this, "_regexp-display",
618 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
619 "_regexp-display expression", 2, 0, false));
620 if (display_regex_cmd_ap.get()) {
621 if (display_regex_cmd_ap->AddRegexCommand(
622 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
623 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
624 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
625 display_regex_cmd_sp;
629 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
630 new CommandObjectRegexCommand(
631 *this, "_regexp-undisplay", "Stop displaying expression at every "
632 "stop (specified by stop-hook index.)",
633 "_regexp-undisplay stop-hook-number", 2, 0, false));
634 if (undisplay_regex_cmd_ap.get()) {
635 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
636 "target stop-hook delete %1")) {
637 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
638 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
639 undisplay_regex_cmd_sp;
643 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
644 new CommandObjectRegexCommand(
645 *this, "gdb-remote", "Connect to a process via remote GDB server. "
646 "If no host is specifed, localhost is assumed.",
647 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
648 if (connect_gdb_remote_cmd_ap.get()) {
649 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
650 "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
651 "process connect --plugin gdb-remote connect://%1:%2") &&
652 connect_gdb_remote_cmd_ap->AddRegexCommand(
654 "process connect --plugin gdb-remote connect://localhost:%1")) {
655 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
656 m_command_dict[command_sp->GetCommandName()] = command_sp;
660 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
661 new CommandObjectRegexCommand(
662 *this, "kdp-remote", "Connect to a process via remote KDP server. "
663 "If no UDP port is specified, port 41139 is "
665 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
666 if (connect_kdp_remote_cmd_ap.get()) {
667 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
668 "^([^:]+:[[:digit:]]+)$",
669 "process connect --plugin kdp-remote udp://%1") &&
670 connect_kdp_remote_cmd_ap->AddRegexCommand(
671 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
672 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
673 m_command_dict[command_sp->GetCommandName()] = command_sp;
677 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
678 new CommandObjectRegexCommand(
680 "Show the current thread's call stack. Any numeric argument "
681 "displays at most that many "
682 "frames. The argument 'all' displays all threads.",
683 "bt [<digit> | all]", 2, 0, false));
684 if (bt_regex_cmd_ap.get()) {
685 // accept but don't document "bt -c <number>" -- before bt was a regex
686 // command if you wanted to backtrace
687 // three frames you would do "bt -c 3" but the intention is to have this
688 // emulate the gdb "bt" command and
689 // so now "bt 3" is the preferred form, in line with gdb.
690 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
691 "thread backtrace -c %1") &&
692 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
693 "thread backtrace -c %1") &&
694 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
695 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
696 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
697 m_command_dict[command_sp->GetCommandName()] = command_sp;
701 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
702 new CommandObjectRegexCommand(
703 *this, "_regexp-list",
704 "List relevant source code using one of several shorthand formats.",
706 "_regexp-list <file>:<line> // List around specific file/line\n"
707 "_regexp-list <line> // List current file around specified "
709 "_regexp-list <function-name> // List specified function\n"
710 "_regexp-list 0x<address> // List around specified address\n"
711 "_regexp-list -[<count>] // List previous <count> lines\n"
712 "_regexp-list // List subsequent lines",
713 2, CommandCompletions::eSourceFileCompletion, false));
714 if (list_regex_cmd_ap.get()) {
715 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
716 "source list --line %1") &&
717 list_regex_cmd_ap->AddRegexCommand(
718 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
720 "source list --file '%1' --line %2") &&
721 list_regex_cmd_ap->AddRegexCommand(
722 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
723 "source list --address %1") &&
724 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
725 "source list --reverse") &&
726 list_regex_cmd_ap->AddRegexCommand(
727 "^-([[:digit:]]+)[[:space:]]*$",
728 "source list --reverse --count %1") &&
729 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
730 "source list --name \"%1\"") &&
731 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
732 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
733 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
737 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
738 new CommandObjectRegexCommand(
739 *this, "_regexp-env",
740 "Shorthand for viewing and setting environment variables.",
742 "_regexp-env // Show enrivonment\n"
743 "_regexp-env <name>=<value> // Set an environment variable",
745 if (env_regex_cmd_ap.get()) {
746 if (env_regex_cmd_ap->AddRegexCommand("^$",
747 "settings show target.env-vars") &&
748 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
749 "settings set target.env-vars %1")) {
750 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
751 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
755 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
756 new CommandObjectRegexCommand(
757 *this, "_regexp-jump", "Set the program counter to a new address.",
759 "_regexp-jump <line>\n"
760 "_regexp-jump +<line-offset> | -<line-offset>\n"
761 "_regexp-jump <file>:<line>\n"
762 "_regexp-jump *<addr>\n",
764 if (jump_regex_cmd_ap.get()) {
765 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
766 "thread jump --addr %1") &&
767 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
768 "thread jump --line %1") &&
769 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
770 "thread jump --file %1 --line %2") &&
771 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
772 "thread jump --by %1")) {
773 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
774 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
779 int CommandInterpreter::GetCommandNamesMatchingPartialString(
780 const char *cmd_str, bool include_aliases, StringList &matches) {
781 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches);
783 if (include_aliases) {
784 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches);
787 return matches.GetSize();
790 CommandObjectSP CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str,
791 bool include_aliases,
793 StringList *matches) const {
794 CommandObjectSP command_sp;
796 std::string cmd = cmd_str;
799 auto pos = m_command_dict.find(cmd);
800 if (pos != m_command_dict.end())
801 command_sp = pos->second;
804 if (include_aliases && HasAliases()) {
805 auto alias_pos = m_alias_dict.find(cmd);
806 if (alias_pos != m_alias_dict.end())
807 command_sp = alias_pos->second;
810 if (HasUserCommands()) {
811 auto pos = m_user_dict.find(cmd);
812 if (pos != m_user_dict.end())
813 command_sp = pos->second;
816 if (!exact && !command_sp) {
817 // We will only get into here if we didn't find any exact matches.
819 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
821 StringList local_matches;
822 if (matches == nullptr)
823 matches = &local_matches;
825 unsigned int num_cmd_matches = 0;
826 unsigned int num_alias_matches = 0;
827 unsigned int num_user_matches = 0;
829 // Look through the command dictionaries one by one, and if we get only one
831 // them in toto, then return that, otherwise return an empty CommandObjectSP
832 // and the list of matches.
836 AddNamesMatchingPartialString(m_command_dict, cmd_str, *matches);
839 if (num_cmd_matches == 1) {
840 cmd.assign(matches->GetStringAtIndex(0));
841 auto pos = m_command_dict.find(cmd);
842 if (pos != m_command_dict.end())
843 real_match_sp = pos->second;
846 if (include_aliases && HasAliases()) {
848 AddNamesMatchingPartialString(m_alias_dict, cmd_str, *matches);
851 if (num_alias_matches == 1) {
852 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
853 auto alias_pos = m_alias_dict.find(cmd);
854 if (alias_pos != m_alias_dict.end())
855 alias_match_sp = alias_pos->second;
858 if (HasUserCommands()) {
860 AddNamesMatchingPartialString(m_user_dict, cmd_str, *matches);
863 if (num_user_matches == 1) {
865 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
867 auto pos = m_user_dict.find(cmd);
868 if (pos != m_user_dict.end())
869 user_match_sp = pos->second;
872 // If we got exactly one match, return that, otherwise return the match
875 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
877 return real_match_sp;
878 else if (num_alias_matches)
879 return alias_match_sp;
881 return user_match_sp;
883 } else if (matches && command_sp) {
884 matches->AppendString(cmd_str);
890 bool CommandInterpreter::AddCommand(llvm::StringRef name,
891 const lldb::CommandObjectSP &cmd_sp,
894 assert((this == &cmd_sp->GetCommandInterpreter()) &&
895 "tried to add a CommandObject from a different interpreter");
900 std::string name_sstr(name);
901 auto name_iter = m_command_dict.find(name_sstr);
902 if (name_iter != m_command_dict.end()) {
903 if (!can_replace || !name_iter->second->IsRemovable())
905 name_iter->second = cmd_sp;
907 m_command_dict[name_sstr] = cmd_sp;
912 bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
913 const lldb::CommandObjectSP &cmd_sp,
916 assert((this == &cmd_sp->GetCommandInterpreter()) &&
917 "tried to add a CommandObject from a different interpreter");
920 // do not allow replacement of internal commands
921 if (CommandExists(name)) {
922 if (can_replace == false)
924 if (m_command_dict[name]->IsRemovable() == false)
928 if (UserCommandExists(name)) {
929 if (can_replace == false)
931 if (m_user_dict[name]->IsRemovable() == false)
935 m_user_dict[name] = cmd_sp;
941 CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
942 bool include_aliases) const {
943 Args cmd_words(cmd_str); // Break up the command string into words, in case
944 // it's a multi-word command.
945 CommandObjectSP ret_val; // Possibly empty return value.
950 if (cmd_words.GetArgumentCount() == 1)
951 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
953 // We have a multi-word command (seemingly), so we need to do more work.
954 // First, get the cmd_obj_sp for the first word in the command.
955 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
956 include_aliases, true, nullptr);
957 if (cmd_obj_sp.get() != nullptr) {
958 // Loop through the rest of the words in the command (everything passed in
959 // was supposed to be part of a
960 // command name), and find the appropriate sub-command SP for each command
962 size_t end = cmd_words.GetArgumentCount();
963 for (size_t j = 1; j < end; ++j) {
964 if (cmd_obj_sp->IsMultiwordObject()) {
966 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
967 if (cmd_obj_sp.get() == nullptr)
968 // The sub-command name was invalid. Fail and return the empty
972 // We have more words in the command name, but we don't have a
973 // multiword object. Fail and return empty 'ret_val'.
976 // We successfully looped through all the command words and got valid
977 // command objects for them. Assign the last object retrieved to
979 ret_val = cmd_obj_sp;
985 CommandObject *CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
986 StringList *matches) const {
987 CommandObject *command_obj =
988 GetCommandSP(cmd_str, false, true, matches).get();
990 // If we didn't find an exact match to the command string in the commands,
997 command_obj = GetCommandSP(cmd_str, true, true, matches).get();
1002 // If there wasn't an exact match then look for an inexact one in just the
1004 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
1006 // Finally, if there wasn't an inexact match among the commands, look for an
1008 // match in both the commands and aliases.
1012 matches->AppendString(command_obj->GetCommandName());
1016 return GetCommandSP(cmd_str, true, false, matches).get();
1019 bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
1020 return m_command_dict.find(cmd) != m_command_dict.end();
1023 bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1024 std::string &full_name) const {
1025 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1027 full_name.assign(cmd);
1031 size_t num_alias_matches;
1033 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1034 if (num_alias_matches == 1) {
1035 // Make sure this isn't shadowing a command in the regular command space:
1036 StringList regular_matches;
1037 const bool include_aliases = false;
1038 const bool exact = false;
1039 CommandObjectSP cmd_obj_sp(
1040 GetCommandSP(cmd, include_aliases, exact, ®ular_matches));
1041 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1044 full_name.assign(matches.GetStringAtIndex(0));
1052 bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
1053 return m_alias_dict.find(cmd) != m_alias_dict.end();
1056 bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
1057 return m_user_dict.find(cmd) != m_user_dict.end();
1061 CommandInterpreter::AddAlias(llvm::StringRef alias_name,
1062 lldb::CommandObjectSP &command_obj_sp,
1063 llvm::StringRef args_string) {
1064 if (command_obj_sp.get())
1065 assert((this == &command_obj_sp->GetCommandInterpreter()) &&
1066 "tried to add a CommandObject from a different interpreter");
1068 std::unique_ptr<CommandAlias> command_alias_up(
1069 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1071 if (command_alias_up && command_alias_up->IsValid()) {
1072 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1073 return command_alias_up.release();
1079 bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
1080 auto pos = m_alias_dict.find(alias_name);
1081 if (pos != m_alias_dict.end()) {
1082 m_alias_dict.erase(pos);
1088 bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
1089 auto pos = m_command_dict.find(cmd);
1090 if (pos != m_command_dict.end()) {
1091 if (pos->second->IsRemovable()) {
1092 // Only regular expression objects or python commands are removable
1093 m_command_dict.erase(pos);
1099 bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
1100 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1101 if (pos != m_user_dict.end()) {
1102 m_user_dict.erase(pos);
1108 void CommandInterpreter::GetHelp(CommandReturnObject &result,
1109 uint32_t cmd_types) {
1110 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1111 if (!help_prologue.empty()) {
1112 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1116 CommandObject::CommandMap::const_iterator pos;
1117 size_t max_len = FindLongestCommandWord(m_command_dict);
1119 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1120 result.AppendMessage("Debugger commands:");
1121 result.AppendMessage("");
1123 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1124 if (!(cmd_types & eCommandTypesHidden) &&
1125 (pos->first.compare(0, 1, "_") == 0))
1128 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1129 pos->second->GetHelp(), max_len);
1131 result.AppendMessage("");
1134 if (!m_alias_dict.empty() &&
1135 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1136 result.AppendMessageWithFormat(
1137 "Current command abbreviations "
1138 "(type '%shelp command alias' for more info):\n",
1139 GetCommandPrefix());
1140 result.AppendMessage("");
1141 max_len = FindLongestCommandWord(m_alias_dict);
1143 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1145 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
1146 alias_pos->second->GetHelp(), max_len);
1148 result.AppendMessage("");
1151 if (!m_user_dict.empty() &&
1152 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1153 result.AppendMessage("Current user-defined commands:");
1154 result.AppendMessage("");
1155 max_len = FindLongestCommandWord(m_user_dict);
1156 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
1157 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1158 pos->second->GetHelp(), max_len);
1160 result.AppendMessage("");
1163 result.AppendMessageWithFormat(
1164 "For more information on any command, type '%shelp <command-name>'.\n",
1165 GetCommandPrefix());
1168 CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1169 llvm::StringRef &command_string) {
1170 // This function finds the final, lowest-level, alias-resolved command object
1171 // whose 'Execute' function will
1172 // eventually be invoked by the given command line.
1174 CommandObject *cmd_obj = nullptr;
1175 size_t start = command_string.find_first_not_of(k_white_space);
1179 if (start != std::string::npos) {
1180 // Get the next word from command_string.
1181 end = command_string.find_first_of(k_white_space, start);
1182 if (end == std::string::npos)
1183 end = command_string.size();
1184 std::string cmd_word = command_string.substr(start, end - start);
1186 if (cmd_obj == nullptr)
1187 // Since cmd_obj is NULL we are on our first time through this loop.
1188 // Check to see if cmd_word is a valid command or alias.
1189 cmd_obj = GetCommandObject(cmd_word);
1190 else if (cmd_obj->IsMultiwordObject()) {
1191 // Our current object is a multi-word object; see if the cmd_word is a
1192 // valid sub-command for our object.
1193 CommandObject *sub_cmd_obj =
1194 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1196 cmd_obj = sub_cmd_obj;
1197 else // cmd_word was not a valid sub-command word, so we are done
1200 // We have a cmd_obj and it is not a multi-word object, so we are done.
1203 // If we didn't find a valid command object, or our command object is not
1204 // a multi-word object, or we are at the end of the command_string, then
1205 // we are done. Otherwise, find the start of the next word.
1207 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1208 end >= command_string.size())
1211 start = command_string.find_first_not_of(k_white_space, end);
1213 // Unable to find any more words.
1217 command_string = command_string.substr(end);
1221 static const char *k_valid_command_chars =
1222 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1223 static void StripLeadingSpaces(std::string &s) {
1225 size_t pos = s.find_first_not_of(k_white_space);
1226 if (pos == std::string::npos)
1234 static size_t FindArgumentTerminator(const std::string &s) {
1235 const size_t s_len = s.size();
1237 while (offset < s_len) {
1238 size_t pos = s.find("--", offset);
1239 if (pos == std::string::npos)
1242 if (isspace(s[pos - 1])) {
1243 // Check if the string ends "\s--" (where \s is a space character)
1244 // or if we have "\s--\s".
1245 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1252 return std::string::npos;
1255 static bool ExtractCommand(std::string &command_string, std::string &command,
1256 std::string &suffix, char "e_char) {
1259 StripLeadingSpaces(command_string);
1261 bool result = false;
1264 if (!command_string.empty()) {
1265 const char first_char = command_string[0];
1266 if (first_char == '\'' || first_char == '"') {
1267 quote_char = first_char;
1268 const size_t end_quote_pos = command_string.find(quote_char, 1);
1269 if (end_quote_pos == std::string::npos) {
1270 command.swap(command_string);
1271 command_string.erase();
1273 command.assign(command_string, 1, end_quote_pos - 1);
1274 if (end_quote_pos + 1 < command_string.size())
1275 command_string.erase(0, command_string.find_first_not_of(
1276 k_white_space, end_quote_pos + 1));
1278 command_string.erase();
1281 const size_t first_space_pos =
1282 command_string.find_first_of(k_white_space);
1283 if (first_space_pos == std::string::npos) {
1284 command.swap(command_string);
1285 command_string.erase();
1287 command.assign(command_string, 0, first_space_pos);
1288 command_string.erase(0, command_string.find_first_not_of(
1289 k_white_space, first_space_pos));
1295 if (!command.empty()) {
1296 // actual commands can't start with '-' or '_'
1297 if (command[0] != '-' && command[0] != '_') {
1298 size_t pos = command.find_first_not_of(k_valid_command_chars);
1299 if (pos > 0 && pos != std::string::npos) {
1300 suffix.assign(command.begin() + pos, command.end());
1309 CommandObject *CommandInterpreter::BuildAliasResult(
1310 llvm::StringRef alias_name, std::string &raw_input_string,
1311 std::string &alias_result, CommandReturnObject &result) {
1312 CommandObject *alias_cmd_obj = nullptr;
1313 Args cmd_args(raw_input_string);
1314 alias_cmd_obj = GetCommandObject(alias_name);
1315 StreamString result_str;
1317 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1318 alias_result.clear();
1319 return alias_cmd_obj;
1321 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1322 ((CommandAlias *)alias_cmd_obj)->Desugar();
1323 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1324 alias_cmd_obj = desugared.first.get();
1325 std::string alias_name_str = alias_name;
1326 if ((cmd_args.GetArgumentCount() == 0) ||
1327 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1328 cmd_args.Unshift(alias_name_str);
1330 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
1332 if (!option_arg_vector_sp.get()) {
1333 alias_result = result_str.GetString();
1334 return alias_cmd_obj;
1336 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1341 for (const auto &entry : *option_arg_vector) {
1342 std::tie(option, value_type, value) = entry;
1343 if (option == "<argument>") {
1344 result_str.Printf(" %s", value.c_str());
1348 result_str.Printf(" %s", option.c_str());
1349 if (value_type == OptionParser::eNoArgument)
1352 if (value_type != OptionParser::eOptionalArgument)
1353 result_str.Printf(" ");
1354 int index = GetOptionArgumentPosition(value.c_str());
1356 result_str.Printf("%s", value.c_str());
1357 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1359 result.AppendErrorWithFormat("Not enough arguments provided; you "
1360 "need at least %d arguments to use "
1363 result.SetStatus(eReturnStatusFailed);
1366 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1367 if (strpos != std::string::npos)
1368 raw_input_string = raw_input_string.erase(
1369 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1370 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
1374 alias_result = result_str.GetString();
1375 return alias_cmd_obj;
1378 Status CommandInterpreter::PreprocessCommand(std::string &command) {
1379 // The command preprocessor needs to do things to the command
1380 // line before any parsing of arguments or anything else is done.
1381 // The only current stuff that gets preprocessed is anything enclosed
1382 // in backtick ('`') characters is evaluated as an expression and
1383 // the result of the expression must be a scalar that can be substituted
1384 // into the command. An example would be:
1385 // (lldb) memory read `$rsp + 20`
1386 Status error; // Status for any expressions that might not evaluate
1387 size_t start_backtick;
1389 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1390 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
1391 // The backtick was preceded by a '\' character, remove the slash
1392 // and don't treat the backtick as the start of an expression
1393 command.erase(start_backtick - 1, 1);
1394 // No need to add one to start_backtick since we just deleted a char
1395 pos = start_backtick;
1397 const size_t expr_content_start = start_backtick + 1;
1398 const size_t end_backtick = command.find('`', expr_content_start);
1399 if (end_backtick == std::string::npos)
1401 else if (end_backtick == expr_content_start) {
1402 // Empty expression (two backticks in a row)
1403 command.erase(start_backtick, 2);
1405 std::string expr_str(command, expr_content_start,
1406 end_backtick - expr_content_start);
1408 ExecutionContext exe_ctx(GetExecutionContext());
1409 Target *target = exe_ctx.GetTargetPtr();
1410 // Get a dummy target to allow for calculator mode while processing
1412 // This also helps break the infinite loop caused when target is null.
1414 target = m_debugger.GetDummyTarget();
1416 ValueObjectSP expr_result_valobj_sp;
1418 EvaluateExpressionOptions options;
1419 options.SetCoerceToId(false);
1420 options.SetUnwindOnError(true);
1421 options.SetIgnoreBreakpoints(true);
1422 options.SetKeepInMemory(false);
1423 options.SetTryAllThreads(true);
1424 options.SetTimeout(llvm::None);
1426 ExpressionResults expr_result = target->EvaluateExpression(
1427 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1430 if (expr_result == eExpressionCompleted) {
1432 if (expr_result_valobj_sp)
1433 expr_result_valobj_sp =
1434 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1435 expr_result_valobj_sp->GetDynamicValueType(), true);
1436 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1437 command.erase(start_backtick, end_backtick - start_backtick + 1);
1438 StreamString value_strm;
1439 const bool show_type = false;
1440 scalar.GetValue(&value_strm, show_type);
1441 size_t value_string_size = value_strm.GetSize();
1442 if (value_string_size) {
1443 command.insert(start_backtick, value_strm.GetString());
1444 pos = start_backtick + value_string_size;
1447 error.SetErrorStringWithFormat("expression value didn't result "
1448 "in a scalar value for the "
1453 error.SetErrorStringWithFormat("expression value didn't result "
1454 "in a scalar value for the "
1459 if (expr_result_valobj_sp)
1460 error = expr_result_valobj_sp->GetError();
1461 if (error.Success()) {
1463 switch (expr_result) {
1464 case eExpressionSetupError:
1465 error.SetErrorStringWithFormat(
1466 "expression setup error for the expression '%s'",
1469 case eExpressionParseError:
1470 error.SetErrorStringWithFormat(
1471 "expression parse error for the expression '%s'",
1474 case eExpressionResultUnavailable:
1475 error.SetErrorStringWithFormat(
1476 "expression error fetching result for the expression '%s'",
1479 case eExpressionCompleted:
1481 case eExpressionDiscarded:
1482 error.SetErrorStringWithFormat(
1483 "expression discarded for the expression '%s'",
1486 case eExpressionInterrupted:
1487 error.SetErrorStringWithFormat(
1488 "expression interrupted for the expression '%s'",
1491 case eExpressionHitBreakpoint:
1492 error.SetErrorStringWithFormat(
1493 "expression hit breakpoint for the expression '%s'",
1496 case eExpressionTimedOut:
1497 error.SetErrorStringWithFormat(
1498 "expression timed out for the expression '%s'",
1501 case eExpressionStoppedForDebug:
1502 error.SetErrorStringWithFormat("expression stop at entry point "
1503 "for debugging for the "
1519 bool CommandInterpreter::HandleCommand(const char *command_line,
1520 LazyBool lazy_add_to_history,
1521 CommandReturnObject &result,
1522 ExecutionContext *override_context,
1523 bool repeat_on_empty_command,
1524 bool no_context_switching)
1528 std::string command_string(command_line);
1529 std::string original_command_string(command_line);
1531 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
1532 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
1536 log->Printf("Processing command: %s", command_line);
1538 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1539 Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
1541 if (!no_context_switching)
1542 UpdateExecutionContext(override_context);
1544 bool add_to_history;
1545 if (lazy_add_to_history == eLazyBoolCalculate)
1546 add_to_history = (m_command_source_depth == 0);
1548 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1550 bool empty_command = false;
1551 bool comment_command = false;
1552 if (command_string.empty())
1553 empty_command = true;
1555 const char *k_space_characters = "\t\n\v\f\r ";
1557 size_t non_space = command_string.find_first_not_of(k_space_characters);
1558 // Check for empty line or comment line (lines whose first
1559 // non-space character is the comment character for this interpreter)
1560 if (non_space == std::string::npos)
1561 empty_command = true;
1562 else if (command_string[non_space] == m_comment_char)
1563 comment_command = true;
1564 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
1565 llvm::StringRef search_str(command_string);
1566 search_str = search_str.drop_front(non_space);
1567 if (auto hist_str = m_command_history.FindString(search_str)) {
1568 add_to_history = false;
1569 command_string = *hist_str;
1570 original_command_string = *hist_str;
1572 result.AppendErrorWithFormat("Could not find entry: %s in history",
1573 command_string.c_str());
1574 result.SetStatus(eReturnStatusFailed);
1580 if (empty_command) {
1581 if (repeat_on_empty_command) {
1582 if (m_command_history.IsEmpty()) {
1583 result.AppendError("empty command");
1584 result.SetStatus(eReturnStatusFailed);
1587 command_line = m_repeat_command.c_str();
1588 command_string = command_line;
1589 original_command_string = command_line;
1590 if (m_repeat_command.empty()) {
1591 result.AppendErrorWithFormat("No auto repeat.\n");
1592 result.SetStatus(eReturnStatusFailed);
1596 add_to_history = false;
1598 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1601 } else if (comment_command) {
1602 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1606 Status error(PreprocessCommand(command_string));
1609 result.AppendError(error.AsCString());
1610 result.SetStatus(eReturnStatusFailed);
1616 // Before we do ANY kind of argument processing, we need to figure out what
1617 // the real/final command object is for the specified command. This gets
1618 // complicated by the fact that the user could have specified an alias, and,
1619 // in translating the alias, there may also be command options and/or even
1620 // data (including raw text strings) that need to be found and inserted into
1621 // the command line as part of the translation. So this first step is plain
1622 // look-up and replacement, resulting in:
1623 // 1. the command object whose Execute method will actually be called
1624 // 2. a revised command string, with all substitutions and replacements
1626 // From 1 above, we can determine whether the Execute function wants raw
1629 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1631 // Although the user may have abbreviated the command, the command_string now
1632 // has the command expanded to the full name. For example, if the input
1633 // was "br s -n main", command_string is now "breakpoint set -n main".
1635 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1636 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
1637 log->Printf("HandleCommand, (revised) command_string: '%s'",
1638 command_string.c_str());
1639 const bool wants_raw_input =
1640 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1641 log->Printf("HandleCommand, wants_raw_input:'%s'",
1642 wants_raw_input ? "True" : "False");
1646 // Take care of things like setting up the history command & calling the
1647 // appropriate Execute method on the
1648 // CommandObject, with the appropriate arguments.
1650 if (cmd_obj != nullptr) {
1651 if (add_to_history) {
1652 Args command_args(command_string);
1653 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1654 if (repeat_command != nullptr)
1655 m_repeat_command.assign(repeat_command);
1657 m_repeat_command.assign(original_command_string);
1659 m_command_history.AppendString(original_command_string);
1662 std::string remainder;
1663 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
1664 if (actual_cmd_name_len < command_string.length())
1665 remainder = command_string.substr(actual_cmd_name_len);
1667 // Remove any initial spaces
1668 size_t pos = remainder.find_first_not_of(k_white_space);
1669 if (pos != 0 && pos != std::string::npos)
1670 remainder.erase(0, pos);
1674 "HandleCommand, command line after removing command name(s): '%s'",
1677 cmd_obj->Execute(remainder.c_str(), result);
1679 // We didn't find the first command object, so complete the first argument.
1680 Args command_args(command_string);
1683 int cursor_index = 0;
1684 int cursor_char_position = strlen(command_args.GetArgumentAtIndex(0));
1686 num_matches = HandleCompletionMatches(command_args, cursor_index,
1687 cursor_char_position, 0, -1,
1688 word_complete, matches);
1690 if (num_matches > 0) {
1691 std::string error_msg;
1692 error_msg.assign("ambiguous command '");
1693 error_msg.append(command_args.GetArgumentAtIndex(0));
1694 error_msg.append("'.");
1696 error_msg.append(" Possible completions:");
1697 for (int i = 0; i < num_matches; i++) {
1698 error_msg.append("\n\t");
1699 error_msg.append(matches.GetStringAtIndex(i));
1701 error_msg.append("\n");
1702 result.AppendRawError(error_msg.c_str());
1704 result.AppendErrorWithFormat("Unrecognized command '%s'.\n",
1705 command_args.GetArgumentAtIndex(0));
1707 result.SetStatus(eReturnStatusFailed);
1711 log->Printf("HandleCommand, command %s",
1712 (result.Succeeded() ? "succeeded" : "did not succeed"));
1714 return result.Succeeded();
1717 int CommandInterpreter::HandleCompletionMatches(
1718 Args &parsed_line, int &cursor_index, int &cursor_char_position,
1719 int match_start_point, int max_return_elements, bool &word_complete,
1720 StringList &matches) {
1721 int num_command_matches = 0;
1722 bool look_for_subcommand = false;
1724 // For any of the command completions a unique match will be a complete word.
1725 word_complete = true;
1727 if (cursor_index == -1) {
1728 // We got nothing on the command line, so return the list of commands
1729 bool include_aliases = true;
1730 num_command_matches =
1731 GetCommandNamesMatchingPartialString("", include_aliases, matches);
1732 } else if (cursor_index == 0) {
1733 // The cursor is in the first argument, so just do a lookup in the
1735 CommandObject *cmd_obj =
1736 GetCommandObject(parsed_line.GetArgumentAtIndex(0), &matches);
1737 num_command_matches = matches.GetSize();
1739 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1740 matches.GetStringAtIndex(0) != nullptr &&
1741 strcmp(parsed_line.GetArgumentAtIndex(0),
1742 matches.GetStringAtIndex(0)) == 0) {
1743 if (parsed_line.GetArgumentCount() == 1) {
1744 word_complete = true;
1746 look_for_subcommand = true;
1747 num_command_matches = 0;
1748 matches.DeleteStringAtIndex(0);
1749 parsed_line.AppendArgument(llvm::StringRef());
1751 cursor_char_position = 0;
1756 if (cursor_index > 0 || look_for_subcommand) {
1757 // We are completing further on into a commands arguments, so find the
1758 // command and tell it
1759 // to complete the command.
1760 // First see if there is a matching initial command:
1761 CommandObject *command_object =
1762 GetCommandObject(parsed_line.GetArgumentAtIndex(0));
1763 if (command_object == nullptr) {
1766 parsed_line.Shift();
1768 num_command_matches = command_object->HandleCompletion(
1769 parsed_line, cursor_index, cursor_char_position, match_start_point,
1770 max_return_elements, word_complete, matches);
1774 return num_command_matches;
1777 int CommandInterpreter::HandleCompletion(
1778 const char *current_line, const char *cursor, const char *last_char,
1779 int match_start_point, int max_return_elements, StringList &matches) {
1780 // We parse the argument up to the cursor, so the last argument in parsed_line
1782 // the one containing the cursor, and the cursor is after the last character.
1784 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
1785 Args partial_parsed_line(
1786 llvm::StringRef(current_line, cursor - current_line));
1788 // Don't complete comments, and if the line we are completing is just the
1789 // history repeat character,
1790 // substitute the appropriate history line.
1791 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1793 if (first_arg[0] == m_comment_char)
1795 else if (first_arg[0] == CommandHistory::g_repeat_char) {
1796 if (auto hist_str = m_command_history.FindString(first_arg)) {
1798 matches.InsertStringAtIndex(0, *hist_str);
1805 int num_args = partial_parsed_line.GetArgumentCount();
1806 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1807 int cursor_char_position;
1809 if (cursor_index == -1)
1810 cursor_char_position = 0;
1812 cursor_char_position =
1813 strlen(partial_parsed_line.GetArgumentAtIndex(cursor_index));
1815 if (cursor > current_line && cursor[-1] == ' ') {
1816 // We are just after a space. If we are in an argument, then we will
1818 // parsing, but if we are between arguments, then we have to complete
1819 // whatever the next
1820 // element would be.
1821 // We can distinguish the two cases because if we are in an argument (e.g.
1822 // because the space is
1823 // protected by a quote) then the space will also be in the parsed
1826 const char *current_elem =
1827 partial_parsed_line.GetArgumentAtIndex(cursor_index);
1828 if (cursor_char_position == 0 ||
1829 current_elem[cursor_char_position - 1] != ' ') {
1830 parsed_line.InsertArgumentAtIndex(cursor_index + 1, llvm::StringRef(),
1833 cursor_char_position = 0;
1837 int num_command_matches;
1841 // Only max_return_elements == -1 is supported at present:
1842 assert(max_return_elements == -1);
1844 num_command_matches = HandleCompletionMatches(
1845 parsed_line, cursor_index, cursor_char_position, match_start_point,
1846 max_return_elements, word_complete, matches);
1848 if (num_command_matches <= 0)
1849 return num_command_matches;
1851 if (num_args == 0) {
1852 // If we got an empty string, insert nothing.
1853 matches.InsertStringAtIndex(0, "");
1855 // Now figure out if there is a common substring, and if so put that in
1856 // element 0, otherwise
1857 // put an empty string in element 0.
1858 std::string command_partial_str;
1859 if (cursor_index >= 0)
1860 command_partial_str =
1861 parsed_line[cursor_index].ref.take_front(cursor_char_position);
1863 std::string common_prefix;
1864 matches.LongestCommonPrefix(common_prefix);
1865 const size_t partial_name_len = command_partial_str.size();
1866 common_prefix.erase(0, partial_name_len);
1868 // If we matched a unique single command, add a space...
1869 // Only do this if the completer told us this was a complete word,
1871 if (num_command_matches == 1 && word_complete) {
1872 char quote_char = parsed_line[cursor_index].quote;
1874 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1875 if (quote_char != '\0')
1876 common_prefix.push_back(quote_char);
1877 common_prefix.push_back(' ');
1879 matches.InsertStringAtIndex(0, common_prefix.c_str());
1881 return num_command_matches;
1884 CommandInterpreter::~CommandInterpreter() {}
1886 void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
1887 EventSP prompt_change_event_sp(
1888 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1890 BroadcastEvent(prompt_change_event_sp);
1891 if (m_command_io_handler_sp)
1892 m_command_io_handler_sp->SetPrompt(new_prompt);
1895 bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
1896 // Check AutoConfirm first:
1897 if (m_debugger.GetAutoConfirm())
1898 return default_answer;
1900 IOHandlerConfirm *confirm =
1901 new IOHandlerConfirm(m_debugger, message, default_answer);
1902 IOHandlerSP io_handler_sp(confirm);
1903 m_debugger.RunIOHandler(io_handler_sp);
1904 return confirm->GetResponse();
1907 const CommandAlias *
1908 CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
1909 OptionArgVectorSP ret_val;
1911 auto pos = m_alias_dict.find(alias_name);
1912 if (pos != m_alias_dict.end())
1913 return (CommandAlias *)pos->second.get();
1918 bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
1920 bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
1922 bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
1924 bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
1926 void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1927 const char *alias_name,
1929 std::string &raw_input_string,
1930 CommandReturnObject &result) {
1931 OptionArgVectorSP option_arg_vector_sp =
1932 GetAlias(alias_name)->GetOptionArguments();
1934 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1936 // Make sure that the alias name is the 0th element in cmd_args
1937 std::string alias_name_str = alias_name;
1938 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
1939 cmd_args.Unshift(alias_name_str);
1941 Args new_args(alias_cmd_obj->GetCommandName());
1942 if (new_args.GetArgumentCount() == 2)
1945 if (option_arg_vector_sp.get()) {
1946 if (wants_raw_input) {
1947 // We have a command that both has command options and takes raw input.
1948 // Make *sure* it has a
1949 // " -- " in the right place in the raw_input_string.
1950 size_t pos = raw_input_string.find(" -- ");
1951 if (pos == std::string::npos) {
1952 // None found; assume it goes at the beginning of the raw input string
1953 raw_input_string.insert(0, " -- ");
1957 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1958 const size_t old_size = cmd_args.GetArgumentCount();
1959 std::vector<bool> used(old_size + 1, false);
1966 for (const auto &option_entry : *option_arg_vector) {
1967 std::tie(option, value_type, value) = option_entry;
1968 if (option == "<argument>") {
1969 if (!wants_raw_input || (value != "--")) {
1970 // Since we inserted this above, make sure we don't insert it twice
1971 new_args.AppendArgument(value);
1976 if (value_type != OptionParser::eOptionalArgument)
1977 new_args.AppendArgument(option);
1979 if (value == "<no-argument>")
1982 int index = GetOptionArgumentPosition(value.c_str());
1984 // value was NOT a positional argument; must be a real value
1985 if (value_type != OptionParser::eOptionalArgument)
1986 new_args.AppendArgument(value);
1989 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1991 new_args.AppendArgument(llvm::StringRef(buffer));
1994 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1995 result.AppendErrorWithFormat("Not enough arguments provided; you "
1996 "need at least %d arguments to use "
1999 result.SetStatus(eReturnStatusFailed);
2002 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2004 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2005 if (strpos != std::string::npos) {
2006 raw_input_string = raw_input_string.erase(
2007 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2010 if (value_type != OptionParser::eOptionalArgument)
2011 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2014 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2015 cmd_args.GetArgumentAtIndex(index));
2016 new_args.AppendArgument(buffer);
2022 for (auto entry : llvm::enumerate(cmd_args.entries())) {
2023 if (!used[entry.index()] && !wants_raw_input)
2024 new_args.AppendArgument(entry.value().ref);
2028 cmd_args.SetArguments(new_args.GetArgumentCount(),
2029 new_args.GetConstArgumentVector());
2031 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2032 // This alias was not created with any options; nothing further needs to be
2033 // done, unless it is a command that
2034 // wants raw input, in which case we need to clear the rest of the data from
2035 // cmd_args, since its in the raw
2037 if (wants_raw_input) {
2039 cmd_args.SetArguments(new_args.GetArgumentCount(),
2040 new_args.GetConstArgumentVector());
2045 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2049 int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2050 int position = 0; // Any string that isn't an argument position, i.e. '%'
2051 // followed by an integer, gets a position
2054 const char *cptr = in_string;
2056 // Does it start with '%'
2057 if (cptr[0] == '%') {
2060 // Is the rest of it entirely digits?
2061 if (isdigit(cptr[0])) {
2062 const char *start = cptr;
2063 while (isdigit(cptr[0]))
2066 // We've gotten to the end of the digits; are we at the end of the string?
2067 if (cptr[0] == '\0')
2068 position = atoi(start);
2075 void CommandInterpreter::SourceInitFile(bool in_cwd,
2076 CommandReturnObject &result) {
2079 ExecutionContext exe_ctx(GetExecutionContext());
2080 Target *target = exe_ctx.GetTargetPtr();
2082 // In the current working directory we don't load any program specific
2083 // .lldbinit files, we only look for a ".lldbinit" file.
2084 if (m_skip_lldbinit_files)
2087 LoadCWDlldbinitFile should_load =
2088 target->TargetProperties::GetLoadCWDlldbinitFile();
2089 if (should_load == eLoadCWDlldbinitWarn) {
2090 FileSpec dot_lldb(".lldbinit", true);
2091 llvm::SmallString<64> home_dir_path;
2092 llvm::sys::path::home_directory(home_dir_path);
2093 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2094 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2095 homedir_dot_lldb.ResolvePath();
2096 if (dot_lldb.Exists() &&
2097 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2098 result.AppendErrorWithFormat(
2099 "There is a .lldbinit file in the current directory which is not "
2101 "To silence this warning without sourcing in the local "
2103 "add the following to the lldbinit file in your home directory:\n"
2104 " settings set target.load-cwd-lldbinit false\n"
2105 "To allow lldb to source .lldbinit files in the current working "
2107 "set the value of this variable to true. Only do so if you "
2109 "accept the security risk.");
2110 result.SetStatus(eReturnStatusFailed);
2113 } else if (should_load == eLoadCWDlldbinitTrue) {
2114 init_file.SetFile("./.lldbinit", true);
2118 // If we aren't looking in the current working directory we are looking
2119 // in the home directory. We will first see if there is an application
2120 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2121 // "-" and the name of the program. If this file doesn't exist, we fall
2122 // back to just the "~/.lldbinit" file. We also obey any requests to not
2123 // load the init files.
2124 llvm::SmallString<64> home_dir_path;
2125 llvm::sys::path::home_directory(home_dir_path);
2126 FileSpec profilePath(home_dir_path.c_str(), false);
2127 profilePath.AppendPathComponent(".lldbinit");
2128 std::string init_file_path = profilePath.GetPath();
2130 if (m_skip_app_init_files == false) {
2131 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2132 const char *program_name = program_file_spec.GetFilename().AsCString();
2135 char program_init_file_name[PATH_MAX];
2136 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2137 "%s-%s", init_file_path.c_str(), program_name);
2138 init_file.SetFile(program_init_file_name, true);
2139 if (!init_file.Exists())
2144 if (!init_file && !m_skip_lldbinit_files)
2145 init_file.SetFile(init_file_path, false);
2148 // If the file exists, tell HandleCommand to 'source' it; this will do the
2149 // actual broadcasting
2150 // of the commands back to any appropriate listener (see
2151 // CommandObjectSource::Execute for more details).
2153 if (init_file.Exists()) {
2154 const bool saved_batch = SetBatchCommandMode(true);
2155 CommandInterpreterRunOptions options;
2156 options.SetSilent(true);
2157 options.SetStopOnError(false);
2158 options.SetStopOnContinue(true);
2160 HandleCommandsFromFile(init_file,
2161 nullptr, // Execution context
2163 SetBatchCommandMode(saved_batch);
2165 // nothing to be done if the file doesn't exist
2166 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2170 const char *CommandInterpreter::GetCommandPrefix() {
2171 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2172 return prefix == NULL ? "" : prefix;
2175 PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2176 PlatformSP platform_sp;
2177 if (prefer_target_platform) {
2178 ExecutionContext exe_ctx(GetExecutionContext());
2179 Target *target = exe_ctx.GetTargetPtr();
2181 platform_sp = target->GetPlatform();
2185 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2189 void CommandInterpreter::HandleCommands(const StringList &commands,
2190 ExecutionContext *override_context,
2191 CommandInterpreterRunOptions &options,
2192 CommandReturnObject &result) {
2193 size_t num_lines = commands.GetSize();
2195 // If we are going to continue past a "continue" then we need to run the
2196 // commands synchronously.
2197 // Make sure you reset this value anywhere you return from the function.
2199 bool old_async_execution = m_debugger.GetAsyncExecution();
2201 // If we've been given an execution context, set it at the start, but don't
2202 // keep resetting it or we will
2203 // cause series of commands that change the context, then do an operation that
2204 // relies on that context to fail.
2206 if (override_context != nullptr)
2207 UpdateExecutionContext(override_context);
2209 if (!options.GetStopOnContinue()) {
2210 m_debugger.SetAsyncExecution(false);
2213 for (size_t idx = 0; idx < num_lines; idx++) {
2214 const char *cmd = commands.GetStringAtIndex(idx);
2218 if (options.GetEchoCommands()) {
2219 // TODO: Add Stream support.
2220 result.AppendMessageWithFormat("%s %s\n",
2221 m_debugger.GetPrompt().str().c_str(), cmd);
2224 CommandReturnObject tmp_result;
2225 // If override_context is not NULL, pass no_context_switching = true for
2226 // HandleCommand() since we updated our context already.
2228 // We might call into a regex or alias command, in which case the
2229 // add_to_history will get lost. This
2230 // m_command_source_depth dingus is the way we turn off adding to the
2231 // history in that case, so set it up here.
2232 if (!options.GetAddToHistory())
2233 m_command_source_depth++;
2235 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2236 nullptr, /* override_context */
2237 true, /* repeat_on_empty_command */
2238 override_context != nullptr /* no_context_switching */);
2239 if (!options.GetAddToHistory())
2240 m_command_source_depth--;
2242 if (options.GetPrintResults()) {
2243 if (tmp_result.Succeeded())
2244 result.AppendMessage(tmp_result.GetOutputData());
2247 if (!success || !tmp_result.Succeeded()) {
2248 llvm::StringRef error_msg = tmp_result.GetErrorData();
2249 if (error_msg.empty())
2250 error_msg = "<unknown error>.\n";
2251 if (options.GetStopOnError()) {
2252 result.AppendErrorWithFormat(
2253 "Aborting reading of commands after command #%" PRIu64
2254 ": '%s' failed with %s",
2255 (uint64_t)idx, cmd, error_msg.str().c_str());
2256 result.SetStatus(eReturnStatusFailed);
2257 m_debugger.SetAsyncExecution(old_async_execution);
2259 } else if (options.GetPrintResults()) {
2260 result.AppendMessageWithFormat(
2261 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2262 error_msg.str().c_str());
2266 if (result.GetImmediateOutputStream())
2267 result.GetImmediateOutputStream()->Flush();
2269 if (result.GetImmediateErrorStream())
2270 result.GetImmediateErrorStream()->Flush();
2272 // N.B. Can't depend on DidChangeProcessState, because the state coming into
2273 // the command execution
2274 // could be running (for instance in Breakpoint Commands.
2275 // So we check the return value to see if it is has running in it.
2276 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2277 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2278 if (options.GetStopOnContinue()) {
2279 // If we caused the target to proceed, and we're going to stop in that
2281 // status in our real result before returning. This is an error if the
2282 // continue was not the
2283 // last command in the set of commands to be run.
2284 if (idx != num_lines - 1)
2285 result.AppendErrorWithFormat(
2286 "Aborting reading of commands after command #%" PRIu64
2287 ": '%s' continued the target.\n",
2288 (uint64_t)idx + 1, cmd);
2290 result.AppendMessageWithFormat("Command #%" PRIu64
2291 " '%s' continued the target.\n",
2292 (uint64_t)idx + 1, cmd);
2294 result.SetStatus(tmp_result.GetStatus());
2295 m_debugger.SetAsyncExecution(old_async_execution);
2301 // Also check for "stop on crash here:
2302 bool should_stop = false;
2303 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2304 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2306 ProcessSP process_sp(target_sp->GetProcessSP());
2308 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2309 StopReason reason = thread_sp->GetStopReason();
2310 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2311 reason == eStopReasonInstrumentation) {
2319 if (idx != num_lines - 1)
2320 result.AppendErrorWithFormat(
2321 "Aborting reading of commands after command #%" PRIu64
2322 ": '%s' stopped with a signal or exception.\n",
2323 (uint64_t)idx + 1, cmd);
2325 result.AppendMessageWithFormat(
2326 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2327 (uint64_t)idx + 1, cmd);
2329 result.SetStatus(tmp_result.GetStatus());
2330 m_debugger.SetAsyncExecution(old_async_execution);
2337 result.SetStatus(eReturnStatusSuccessFinishResult);
2338 m_debugger.SetAsyncExecution(old_async_execution);
2343 // Make flags that we can pass into the IOHandler so our delegates can do the
2346 eHandleCommandFlagStopOnContinue = (1u << 0),
2347 eHandleCommandFlagStopOnError = (1u << 1),
2348 eHandleCommandFlagEchoCommand = (1u << 2),
2349 eHandleCommandFlagPrintResult = (1u << 3),
2350 eHandleCommandFlagStopOnCrash = (1u << 4)
2353 void CommandInterpreter::HandleCommandsFromFile(
2354 FileSpec &cmd_file, ExecutionContext *context,
2355 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2356 if (cmd_file.Exists()) {
2357 StreamFileSP input_file_sp(new StreamFile());
2359 std::string cmd_file_path = cmd_file.GetPath();
2360 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2361 File::eOpenOptionRead);
2363 if (error.Success()) {
2364 Debugger &debugger = GetDebugger();
2368 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2369 if (m_command_source_flags.empty()) {
2370 // Stop on continue by default
2371 flags |= eHandleCommandFlagStopOnContinue;
2372 } else if (m_command_source_flags.back() &
2373 eHandleCommandFlagStopOnContinue) {
2374 flags |= eHandleCommandFlagStopOnContinue;
2376 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2377 flags |= eHandleCommandFlagStopOnContinue;
2380 if (options.m_stop_on_error == eLazyBoolCalculate) {
2381 if (m_command_source_flags.empty()) {
2382 if (GetStopCmdSourceOnError())
2383 flags |= eHandleCommandFlagStopOnError;
2384 } else if (m_command_source_flags.back() &
2385 eHandleCommandFlagStopOnError) {
2386 flags |= eHandleCommandFlagStopOnError;
2388 } else if (options.m_stop_on_error == eLazyBoolYes) {
2389 flags |= eHandleCommandFlagStopOnError;
2392 if (options.GetStopOnCrash()) {
2393 if (m_command_source_flags.empty()) {
2394 // Echo command by default
2395 flags |= eHandleCommandFlagStopOnCrash;
2396 } else if (m_command_source_flags.back() &
2397 eHandleCommandFlagStopOnCrash) {
2398 flags |= eHandleCommandFlagStopOnCrash;
2402 if (options.m_echo_commands == eLazyBoolCalculate) {
2403 if (m_command_source_flags.empty()) {
2404 // Echo command by default
2405 flags |= eHandleCommandFlagEchoCommand;
2406 } else if (m_command_source_flags.back() &
2407 eHandleCommandFlagEchoCommand) {
2408 flags |= eHandleCommandFlagEchoCommand;
2410 } else if (options.m_echo_commands == eLazyBoolYes) {
2411 flags |= eHandleCommandFlagEchoCommand;
2414 if (options.m_print_results == eLazyBoolCalculate) {
2415 if (m_command_source_flags.empty()) {
2416 // Print output by default
2417 flags |= eHandleCommandFlagPrintResult;
2418 } else if (m_command_source_flags.back() &
2419 eHandleCommandFlagPrintResult) {
2420 flags |= eHandleCommandFlagPrintResult;
2422 } else if (options.m_print_results == eLazyBoolYes) {
2423 flags |= eHandleCommandFlagPrintResult;
2426 if (flags & eHandleCommandFlagPrintResult) {
2427 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2428 cmd_file_path.c_str());
2431 // Used for inheriting the right settings when "command source" might have
2432 // nested "command source" commands
2433 lldb::StreamFileSP empty_stream_sp;
2434 m_command_source_flags.push_back(flags);
2435 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2436 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2437 empty_stream_sp, // Pass in an empty stream so we inherit the top
2438 // input reader output stream
2439 empty_stream_sp, // Pass in an empty stream so we inherit the top
2440 // input reader error stream
2442 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2444 debugger.GetPrompt(), llvm::StringRef(),
2445 false, // Not multi-line
2446 debugger.GetUseColor(), 0, *this));
2447 const bool old_async_execution = debugger.GetAsyncExecution();
2449 // Set synchronous execution if we are not stopping on continue
2450 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2451 debugger.SetAsyncExecution(false);
2453 m_command_source_depth++;
2455 debugger.RunIOHandler(io_handler_sp);
2456 if (!m_command_source_flags.empty())
2457 m_command_source_flags.pop_back();
2458 m_command_source_depth--;
2459 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2460 debugger.SetAsyncExecution(old_async_execution);
2462 result.AppendErrorWithFormat(
2463 "error: an error occurred read file '%s': %s\n",
2464 cmd_file_path.c_str(), error.AsCString());
2465 result.SetStatus(eReturnStatusFailed);
2469 result.AppendErrorWithFormat(
2470 "Error reading commands from file %s - file not found.\n",
2471 cmd_file.GetFilename().AsCString("<Unknown>"));
2472 result.SetStatus(eReturnStatusFailed);
2477 ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
2478 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
2479 if (!m_script_interpreter_sp) {
2482 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2483 m_script_interpreter_sp =
2484 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2486 return m_script_interpreter_sp.get();
2489 bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2491 void CommandInterpreter::SetSynchronous(bool value) {
2492 m_synchronous_execution = value;
2495 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2496 llvm::StringRef prefix,
2497 llvm::StringRef help_text) {
2498 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2500 size_t line_width_max = max_columns - prefix.size();
2501 if (line_width_max < 16)
2502 line_width_max = help_text.size() + prefix.size();
2504 strm.IndentMore(prefix.size());
2505 bool prefixed_yet = false;
2506 while (!help_text.empty()) {
2507 // Prefix the first line, indent subsequent lines to line up
2508 if (!prefixed_yet) {
2510 prefixed_yet = true;
2514 // Never print more than the maximum on one line.
2515 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2517 // Always break on an explicit newline.
2518 std::size_t first_newline = this_line.find_first_of("\n");
2520 // Don't break on space/tab unless the text is too long to fit on one line.
2521 std::size_t last_space = llvm::StringRef::npos;
2522 if (this_line.size() != help_text.size())
2523 last_space = this_line.find_last_of(" \t");
2525 // Break at whichever condition triggered first.
2526 this_line = this_line.substr(0, std::min(first_newline, last_space));
2527 strm.PutCString(this_line);
2530 // Remove whitespace / newlines after breaking.
2531 help_text = help_text.drop_front(this_line.size()).ltrim();
2533 strm.IndentLess(prefix.size());
2536 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2537 llvm::StringRef word_text,
2538 llvm::StringRef separator,
2539 llvm::StringRef help_text,
2540 size_t max_word_len) {
2541 StreamString prefix_stream;
2542 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2543 (int)separator.size(), separator.data());
2544 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2547 void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2548 llvm::StringRef separator,
2549 llvm::StringRef help_text,
2550 uint32_t max_word_len) {
2551 int indent_size = max_word_len + separator.size() + 2;
2553 strm.IndentMore(indent_size);
2555 StreamString text_strm;
2556 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2557 text_strm << separator << " " << help_text;
2559 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2561 llvm::StringRef text = text_strm.GetString();
2563 uint32_t chars_left = max_columns;
2565 auto nextWordLength = [](llvm::StringRef S) {
2566 size_t pos = S.find_first_of(' ');
2567 return pos == llvm::StringRef::npos ? S.size() : pos;
2570 while (!text.empty()) {
2571 if (text.front() == '\n' ||
2572 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) < chars_left)) {
2575 chars_left = max_columns - indent_size;
2576 if (text.front() == '\n')
2577 text = text.drop_front();
2579 text = text.ltrim(' ');
2581 strm.PutChar(text.front());
2583 text = text.drop_front();
2588 strm.IndentLess(indent_size);
2591 void CommandInterpreter::FindCommandsForApropos(
2592 llvm::StringRef search_word, StringList &commands_found,
2593 StringList &commands_help, CommandObject::CommandMap &command_map) {
2594 CommandObject::CommandMap::const_iterator pos;
2596 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
2597 llvm::StringRef command_name = pos->first;
2598 CommandObject *cmd_obj = pos->second.get();
2600 const bool search_short_help = true;
2601 const bool search_long_help = false;
2602 const bool search_syntax = false;
2603 const bool search_options = false;
2604 if (command_name.contains_lower(search_word) ||
2605 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2606 search_long_help, search_syntax,
2608 commands_found.AppendString(cmd_obj->GetCommandName());
2609 commands_help.AppendString(cmd_obj->GetHelp());
2612 if (cmd_obj->IsMultiwordObject()) {
2613 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2614 FindCommandsForApropos(search_word, commands_found, commands_help,
2615 cmd_multiword->GetSubcommandDictionary());
2620 void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
2621 StringList &commands_found,
2622 StringList &commands_help,
2623 bool search_builtin_commands,
2624 bool search_user_commands,
2625 bool search_alias_commands) {
2626 CommandObject::CommandMap::const_iterator pos;
2628 if (search_builtin_commands)
2629 FindCommandsForApropos(search_word, commands_found, commands_help,
2632 if (search_user_commands)
2633 FindCommandsForApropos(search_word, commands_found, commands_help,
2636 if (search_alias_commands)
2637 FindCommandsForApropos(search_word, commands_found, commands_help,
2641 void CommandInterpreter::UpdateExecutionContext(
2642 ExecutionContext *override_context) {
2643 if (override_context != nullptr) {
2644 m_exe_ctx_ref = *override_context;
2646 const bool adopt_selected = true;
2647 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2652 size_t CommandInterpreter::GetProcessOutput() {
2653 // The process has stuff waiting for stderr; get it and write it out to the
2654 // appropriate place.
2655 char stdio_buffer[1024];
2657 size_t total_bytes = 0;
2659 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2661 ProcessSP process_sp(target_sp->GetProcessSP());
2663 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2665 size_t bytes_written = len;
2666 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2669 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2671 size_t bytes_written = len;
2672 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2680 void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2681 std::string &line) {
2682 const bool is_interactive = io_handler.GetIsInteractive();
2683 if (is_interactive == false) {
2684 // When we are not interactive, don't execute blank lines. This will happen
2685 // sourcing a commands file. We don't want blank lines to repeat the
2687 // command and cause any errors to occur (like redefining an alias, get an
2689 // and stop parsing the commands file).
2693 // When using a non-interactive file handle (like when sourcing commands
2695 // we need to echo the command out so we don't just see the command output
2698 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2699 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2703 lldb_private::CommandReturnObject result;
2704 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2706 // Now emit the command output text from the command we just executed
2707 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2708 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2711 if (!result.GetImmediateOutputStream()) {
2712 llvm::StringRef output = result.GetOutputData();
2713 if (!output.empty())
2714 io_handler.GetOutputStreamFile()->PutCString(output);
2717 // Now emit the command error text from the command we just executed
2718 if (!result.GetImmediateErrorStream()) {
2719 llvm::StringRef error = result.GetErrorData();
2721 io_handler.GetErrorStreamFile()->PutCString(error);
2725 switch (result.GetStatus()) {
2726 case eReturnStatusInvalid:
2727 case eReturnStatusSuccessFinishNoResult:
2728 case eReturnStatusSuccessFinishResult:
2729 case eReturnStatusStarted:
2732 case eReturnStatusSuccessContinuingNoResult:
2733 case eReturnStatusSuccessContinuingResult:
2734 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2735 io_handler.SetIsDone(true);
2738 case eReturnStatusFailed:
2740 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2741 io_handler.SetIsDone(true);
2744 case eReturnStatusQuit:
2745 m_quit_requested = true;
2746 io_handler.SetIsDone(true);
2750 // Finally, if we're going to stop on crash, check that here:
2751 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2752 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2753 bool should_stop = false;
2754 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2756 ProcessSP process_sp(target_sp->GetProcessSP());
2758 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2759 StopReason reason = thread_sp->GetStopReason();
2760 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2761 reason == eStopReasonInstrumentation) &&
2762 !result.GetAbnormalStopWasExpected()) {
2770 io_handler.SetIsDone(true);
2771 m_stopped_for_crash = true;
2776 bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2777 ExecutionContext exe_ctx(GetExecutionContext());
2778 Process *process = exe_ctx.GetProcessPtr();
2781 StateType state = process->GetState();
2782 if (StateIsRunningState(state)) {
2784 return true; // Don't do any updating when we are running
2788 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2789 if (script_interpreter) {
2790 if (script_interpreter->Interrupt())
2796 void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2797 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2799 Debugger &debugger = GetDebugger();
2800 IOHandlerSP io_handler_sp(
2801 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2802 "lldb", // Name of input reader for history
2803 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2804 llvm::StringRef(), // Continuation prompt
2805 true, // Get multiple lines
2806 debugger.GetUseColor(),
2807 0, // Don't show line numbers
2808 delegate)); // IOHandlerDelegate
2810 if (io_handler_sp) {
2811 io_handler_sp->SetUserData(baton);
2813 debugger.PushIOHandler(io_handler_sp);
2815 debugger.RunIOHandler(io_handler_sp);
2819 void CommandInterpreter::GetPythonCommandsFromIOHandler(
2820 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2822 Debugger &debugger = GetDebugger();
2823 IOHandlerSP io_handler_sp(
2824 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2825 "lldb-python", // Name of input reader for history
2826 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2827 llvm::StringRef(), // Continuation prompt
2828 true, // Get multiple lines
2829 debugger.GetUseColor(),
2830 0, // Don't show line numbers
2831 delegate)); // IOHandlerDelegate
2833 if (io_handler_sp) {
2834 io_handler_sp->SetUserData(baton);
2836 debugger.PushIOHandler(io_handler_sp);
2838 debugger.RunIOHandler(io_handler_sp);
2842 bool CommandInterpreter::IsActive() {
2843 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2847 CommandInterpreter::GetIOHandler(bool force_create,
2848 CommandInterpreterRunOptions *options) {
2849 // Always re-create the IOHandlerEditline in case the input
2850 // changed. The old instance might have had a non-interactive
2851 // input and now it does or vice versa.
2852 if (force_create || !m_command_io_handler_sp) {
2853 // Always re-create the IOHandlerEditline in case the input
2854 // changed. The old instance might have had a non-interactive
2855 // input and now it does or vice versa.
2859 if (options->m_stop_on_continue == eLazyBoolYes)
2860 flags |= eHandleCommandFlagStopOnContinue;
2861 if (options->m_stop_on_error == eLazyBoolYes)
2862 flags |= eHandleCommandFlagStopOnError;
2863 if (options->m_stop_on_crash == eLazyBoolYes)
2864 flags |= eHandleCommandFlagStopOnCrash;
2865 if (options->m_echo_commands != eLazyBoolNo)
2866 flags |= eHandleCommandFlagEchoCommand;
2867 if (options->m_print_results != eLazyBoolNo)
2868 flags |= eHandleCommandFlagPrintResult;
2870 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2873 m_command_io_handler_sp.reset(new IOHandlerEditline(
2874 m_debugger, IOHandler::Type::CommandInterpreter,
2875 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2876 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
2877 llvm::StringRef(), // Continuation prompt
2878 false, // Don't enable multiple line input, just single line commands
2879 m_debugger.GetUseColor(),
2880 0, // Don't show line numbers
2883 return m_command_io_handler_sp;
2886 void CommandInterpreter::RunCommandInterpreter(
2887 bool auto_handle_events, bool spawn_thread,
2888 CommandInterpreterRunOptions &options) {
2889 // Always re-create the command interpreter when we run it in case
2890 // any file handles have changed.
2891 bool force_create = true;
2892 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2893 m_stopped_for_crash = false;
2895 if (auto_handle_events)
2896 m_debugger.StartEventHandlerThread();
2899 m_debugger.StartIOHandlerThread();
2901 m_debugger.ExecuteIOHandlers();
2903 if (auto_handle_events)
2904 m_debugger.StopEventHandlerThread();
2909 CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2910 CommandReturnObject &result) {
2911 std::string scratch_command(command_line); // working copy so we don't modify
2912 // command_line unless we succeed
2913 CommandObject *cmd_obj = nullptr;
2914 StreamString revised_command_line;
2915 bool wants_raw_input = false;
2916 size_t actual_cmd_name_len = 0;
2917 std::string next_word;
2921 char quote_char = '\0';
2923 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2924 if (cmd_obj == nullptr) {
2925 std::string full_name;
2926 bool is_alias = GetAliasFullName(next_word, full_name);
2927 cmd_obj = GetCommandObject(next_word, &matches);
2928 bool is_real_command =
2929 (is_alias == false) ||
2930 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2931 if (!is_real_command) {
2933 std::string alias_result;
2935 BuildAliasResult(full_name, scratch_command, alias_result, result);
2936 revised_command_line.Printf("%s", alias_result.c_str());
2938 wants_raw_input = cmd_obj->WantsRawCommandString();
2939 actual_cmd_name_len = cmd_obj->GetCommandName().size();
2943 cmd_obj = GetCommandObject(next_word, &matches);
2945 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2946 actual_cmd_name_len += cmd_name.size();
2947 revised_command_line.Printf("%s", cmd_name.str().c_str());
2948 wants_raw_input = cmd_obj->WantsRawCommandString();
2950 revised_command_line.Printf("%s", next_word.c_str());
2954 if (cmd_obj->IsMultiwordObject()) {
2955 CommandObject *sub_cmd_obj =
2956 cmd_obj->GetSubcommandObject(next_word.c_str());
2958 // The subcommand's name includes the parent command's name,
2959 // so restart rather than append to the revised_command_line.
2960 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
2961 actual_cmd_name_len = sub_cmd_name.size() + 1;
2962 revised_command_line.Clear();
2963 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
2964 cmd_obj = sub_cmd_obj;
2965 wants_raw_input = cmd_obj->WantsRawCommandString();
2968 revised_command_line.Printf(" %c%s%s%c", quote_char,
2969 next_word.c_str(), suffix.c_str(),
2972 revised_command_line.Printf(" %s%s", next_word.c_str(),
2978 revised_command_line.Printf(" %c%s%s%c", quote_char,
2979 next_word.c_str(), suffix.c_str(),
2982 revised_command_line.Printf(" %s%s", next_word.c_str(),
2988 if (cmd_obj == nullptr) {
2989 const size_t num_matches = matches.GetSize();
2990 if (matches.GetSize() > 1) {
2991 StreamString error_msg;
2992 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
2995 for (uint32_t i = 0; i < num_matches; ++i) {
2996 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
2998 result.AppendRawError(error_msg.GetString());
3000 // We didn't have only one match, otherwise we wouldn't get here.
3001 assert(num_matches == 0);
3002 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3005 result.SetStatus(eReturnStatusFailed);
3009 if (cmd_obj->IsMultiwordObject()) {
3010 if (!suffix.empty()) {
3011 result.AppendErrorWithFormat(
3012 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3013 "might be invalid).\n",
3014 cmd_obj->GetCommandName().str().c_str(),
3015 next_word.empty() ? "" : next_word.c_str(),
3016 next_word.empty() ? " -- " : " ", suffix.c_str());
3017 result.SetStatus(eReturnStatusFailed);
3021 // If we found a normal command, we are done
3023 if (!suffix.empty()) {
3024 switch (suffix[0]) {
3026 // GDB format suffixes
3028 Options *command_options = cmd_obj->GetOptions();
3029 if (command_options &&
3030 command_options->SupportsLongOption("gdb-format")) {
3031 std::string gdb_format_option("--gdb-format=");
3032 gdb_format_option += (suffix.c_str() + 1);
3034 std::string cmd = revised_command_line.GetString();
3035 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3036 if (arg_terminator_idx != std::string::npos) {
3037 // Insert the gdb format option before the "--" that terminates
3039 gdb_format_option.append(1, ' ');
3040 cmd.insert(arg_terminator_idx, gdb_format_option);
3041 revised_command_line.Clear();
3042 revised_command_line.PutCString(cmd);
3044 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3046 if (wants_raw_input &&
3047 FindArgumentTerminator(cmd) == std::string::npos)
3048 revised_command_line.PutCString(" --");
3050 result.AppendErrorWithFormat(
3051 "the '%s' command doesn't support the --gdb-format option\n",
3052 cmd_obj->GetCommandName().str().c_str());
3053 result.SetStatus(eReturnStatusFailed);
3060 result.AppendErrorWithFormat(
3061 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3062 result.SetStatus(eReturnStatusFailed);
3067 if (scratch_command.empty())
3071 if (!scratch_command.empty())
3072 revised_command_line.Printf(" %s", scratch_command.c_str());
3074 if (cmd_obj != NULL)
3075 command_line = revised_command_line.GetString();