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 lldbassert(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 lldbassert((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 lldbassert((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 lldbassert((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 if (WasInterrupted()) {
1545 result.AppendError("interrupted");
1546 result.SetStatus(eReturnStatusFailed);
1550 bool add_to_history;
1551 if (lazy_add_to_history == eLazyBoolCalculate)
1552 add_to_history = (m_command_source_depth == 0);
1554 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1556 bool empty_command = false;
1557 bool comment_command = false;
1558 if (command_string.empty())
1559 empty_command = true;
1561 const char *k_space_characters = "\t\n\v\f\r ";
1563 size_t non_space = command_string.find_first_not_of(k_space_characters);
1564 // Check for empty line or comment line (lines whose first
1565 // non-space character is the comment character for this interpreter)
1566 if (non_space == std::string::npos)
1567 empty_command = true;
1568 else if (command_string[non_space] == m_comment_char)
1569 comment_command = true;
1570 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
1571 llvm::StringRef search_str(command_string);
1572 search_str = search_str.drop_front(non_space);
1573 if (auto hist_str = m_command_history.FindString(search_str)) {
1574 add_to_history = false;
1575 command_string = *hist_str;
1576 original_command_string = *hist_str;
1578 result.AppendErrorWithFormat("Could not find entry: %s in history",
1579 command_string.c_str());
1580 result.SetStatus(eReturnStatusFailed);
1586 if (empty_command) {
1587 if (repeat_on_empty_command) {
1588 if (m_command_history.IsEmpty()) {
1589 result.AppendError("empty command");
1590 result.SetStatus(eReturnStatusFailed);
1593 command_line = m_repeat_command.c_str();
1594 command_string = command_line;
1595 original_command_string = command_line;
1596 if (m_repeat_command.empty()) {
1597 result.AppendErrorWithFormat("No auto repeat.\n");
1598 result.SetStatus(eReturnStatusFailed);
1602 add_to_history = false;
1604 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1607 } else if (comment_command) {
1608 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1612 Status error(PreprocessCommand(command_string));
1615 result.AppendError(error.AsCString());
1616 result.SetStatus(eReturnStatusFailed);
1622 // Before we do ANY kind of argument processing, we need to figure out what
1623 // the real/final command object is for the specified command. This gets
1624 // complicated by the fact that the user could have specified an alias, and,
1625 // in translating the alias, there may also be command options and/or even
1626 // data (including raw text strings) that need to be found and inserted into
1627 // the command line as part of the translation. So this first step is plain
1628 // look-up and replacement, resulting in:
1629 // 1. the command object whose Execute method will actually be called
1630 // 2. a revised command string, with all substitutions and replacements
1632 // From 1 above, we can determine whether the Execute function wants raw
1635 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1637 // Although the user may have abbreviated the command, the command_string now
1638 // has the command expanded to the full name. For example, if the input
1639 // was "br s -n main", command_string is now "breakpoint set -n main".
1641 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1642 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
1643 log->Printf("HandleCommand, (revised) command_string: '%s'",
1644 command_string.c_str());
1645 const bool wants_raw_input =
1646 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1647 log->Printf("HandleCommand, wants_raw_input:'%s'",
1648 wants_raw_input ? "True" : "False");
1652 // Take care of things like setting up the history command & calling the
1653 // appropriate Execute method on the
1654 // CommandObject, with the appropriate arguments.
1656 if (cmd_obj != nullptr) {
1657 if (add_to_history) {
1658 Args command_args(command_string);
1659 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1660 if (repeat_command != nullptr)
1661 m_repeat_command.assign(repeat_command);
1663 m_repeat_command.assign(original_command_string);
1665 m_command_history.AppendString(original_command_string);
1668 std::string remainder;
1669 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
1670 if (actual_cmd_name_len < command_string.length())
1671 remainder = command_string.substr(actual_cmd_name_len);
1673 // Remove any initial spaces
1674 size_t pos = remainder.find_first_not_of(k_white_space);
1675 if (pos != 0 && pos != std::string::npos)
1676 remainder.erase(0, pos);
1680 "HandleCommand, command line after removing command name(s): '%s'",
1683 cmd_obj->Execute(remainder.c_str(), result);
1685 // We didn't find the first command object, so complete the first argument.
1686 Args command_args(command_string);
1689 int cursor_index = 0;
1690 int cursor_char_position = strlen(command_args.GetArgumentAtIndex(0));
1692 num_matches = HandleCompletionMatches(command_args, cursor_index,
1693 cursor_char_position, 0, -1,
1694 word_complete, matches);
1696 if (num_matches > 0) {
1697 std::string error_msg;
1698 error_msg.assign("ambiguous command '");
1699 error_msg.append(command_args.GetArgumentAtIndex(0));
1700 error_msg.append("'.");
1702 error_msg.append(" Possible completions:");
1703 for (int i = 0; i < num_matches; i++) {
1704 error_msg.append("\n\t");
1705 error_msg.append(matches.GetStringAtIndex(i));
1707 error_msg.append("\n");
1708 result.AppendRawError(error_msg.c_str());
1710 result.AppendErrorWithFormat("Unrecognized command '%s'.\n",
1711 command_args.GetArgumentAtIndex(0));
1713 result.SetStatus(eReturnStatusFailed);
1717 log->Printf("HandleCommand, command %s",
1718 (result.Succeeded() ? "succeeded" : "did not succeed"));
1720 return result.Succeeded();
1723 int CommandInterpreter::HandleCompletionMatches(
1724 Args &parsed_line, int &cursor_index, int &cursor_char_position,
1725 int match_start_point, int max_return_elements, bool &word_complete,
1726 StringList &matches) {
1727 int num_command_matches = 0;
1728 bool look_for_subcommand = false;
1730 // For any of the command completions a unique match will be a complete word.
1731 word_complete = true;
1733 if (cursor_index == -1) {
1734 // We got nothing on the command line, so return the list of commands
1735 bool include_aliases = true;
1736 num_command_matches =
1737 GetCommandNamesMatchingPartialString("", include_aliases, matches);
1738 } else if (cursor_index == 0) {
1739 // The cursor is in the first argument, so just do a lookup in the
1741 CommandObject *cmd_obj =
1742 GetCommandObject(parsed_line.GetArgumentAtIndex(0), &matches);
1743 num_command_matches = matches.GetSize();
1745 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1746 matches.GetStringAtIndex(0) != nullptr &&
1747 strcmp(parsed_line.GetArgumentAtIndex(0),
1748 matches.GetStringAtIndex(0)) == 0) {
1749 if (parsed_line.GetArgumentCount() == 1) {
1750 word_complete = true;
1752 look_for_subcommand = true;
1753 num_command_matches = 0;
1754 matches.DeleteStringAtIndex(0);
1755 parsed_line.AppendArgument(llvm::StringRef());
1757 cursor_char_position = 0;
1762 if (cursor_index > 0 || look_for_subcommand) {
1763 // We are completing further on into a commands arguments, so find the
1764 // command and tell it
1765 // to complete the command.
1766 // First see if there is a matching initial command:
1767 CommandObject *command_object =
1768 GetCommandObject(parsed_line.GetArgumentAtIndex(0));
1769 if (command_object == nullptr) {
1772 parsed_line.Shift();
1774 num_command_matches = command_object->HandleCompletion(
1775 parsed_line, cursor_index, cursor_char_position, match_start_point,
1776 max_return_elements, word_complete, matches);
1780 return num_command_matches;
1783 int CommandInterpreter::HandleCompletion(
1784 const char *current_line, const char *cursor, const char *last_char,
1785 int match_start_point, int max_return_elements, StringList &matches) {
1786 // We parse the argument up to the cursor, so the last argument in parsed_line
1788 // the one containing the cursor, and the cursor is after the last character.
1790 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
1791 Args partial_parsed_line(
1792 llvm::StringRef(current_line, cursor - current_line));
1794 // Don't complete comments, and if the line we are completing is just the
1795 // history repeat character,
1796 // substitute the appropriate history line.
1797 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1799 if (first_arg[0] == m_comment_char)
1801 else if (first_arg[0] == CommandHistory::g_repeat_char) {
1802 if (auto hist_str = m_command_history.FindString(first_arg)) {
1804 matches.InsertStringAtIndex(0, *hist_str);
1811 int num_args = partial_parsed_line.GetArgumentCount();
1812 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1813 int cursor_char_position;
1815 if (cursor_index == -1)
1816 cursor_char_position = 0;
1818 cursor_char_position =
1819 strlen(partial_parsed_line.GetArgumentAtIndex(cursor_index));
1821 if (cursor > current_line && cursor[-1] == ' ') {
1822 // We are just after a space. If we are in an argument, then we will
1824 // parsing, but if we are between arguments, then we have to complete
1825 // whatever the next
1826 // element would be.
1827 // We can distinguish the two cases because if we are in an argument (e.g.
1828 // because the space is
1829 // protected by a quote) then the space will also be in the parsed
1832 const char *current_elem =
1833 partial_parsed_line.GetArgumentAtIndex(cursor_index);
1834 if (cursor_char_position == 0 ||
1835 current_elem[cursor_char_position - 1] != ' ') {
1836 parsed_line.InsertArgumentAtIndex(cursor_index + 1, llvm::StringRef(),
1839 cursor_char_position = 0;
1843 int num_command_matches;
1847 // Only max_return_elements == -1 is supported at present:
1848 lldbassert(max_return_elements == -1);
1850 num_command_matches = HandleCompletionMatches(
1851 parsed_line, cursor_index, cursor_char_position, match_start_point,
1852 max_return_elements, word_complete, matches);
1854 if (num_command_matches <= 0)
1855 return num_command_matches;
1857 if (num_args == 0) {
1858 // If we got an empty string, insert nothing.
1859 matches.InsertStringAtIndex(0, "");
1861 // Now figure out if there is a common substring, and if so put that in
1862 // element 0, otherwise
1863 // put an empty string in element 0.
1864 std::string command_partial_str;
1865 if (cursor_index >= 0)
1866 command_partial_str =
1867 parsed_line[cursor_index].ref.take_front(cursor_char_position);
1869 std::string common_prefix;
1870 matches.LongestCommonPrefix(common_prefix);
1871 const size_t partial_name_len = command_partial_str.size();
1872 common_prefix.erase(0, partial_name_len);
1874 // If we matched a unique single command, add a space...
1875 // Only do this if the completer told us this was a complete word,
1877 if (num_command_matches == 1 && word_complete) {
1878 char quote_char = parsed_line[cursor_index].quote;
1880 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1881 if (quote_char != '\0')
1882 common_prefix.push_back(quote_char);
1883 common_prefix.push_back(' ');
1885 matches.InsertStringAtIndex(0, common_prefix.c_str());
1887 return num_command_matches;
1890 CommandInterpreter::~CommandInterpreter() {}
1892 void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
1893 EventSP prompt_change_event_sp(
1894 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1896 BroadcastEvent(prompt_change_event_sp);
1897 if (m_command_io_handler_sp)
1898 m_command_io_handler_sp->SetPrompt(new_prompt);
1901 bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
1902 // Check AutoConfirm first:
1903 if (m_debugger.GetAutoConfirm())
1904 return default_answer;
1906 IOHandlerConfirm *confirm =
1907 new IOHandlerConfirm(m_debugger, message, default_answer);
1908 IOHandlerSP io_handler_sp(confirm);
1909 m_debugger.RunIOHandler(io_handler_sp);
1910 return confirm->GetResponse();
1913 const CommandAlias *
1914 CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
1915 OptionArgVectorSP ret_val;
1917 auto pos = m_alias_dict.find(alias_name);
1918 if (pos != m_alias_dict.end())
1919 return (CommandAlias *)pos->second.get();
1924 bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
1926 bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
1928 bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
1930 bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
1932 void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1933 const char *alias_name,
1935 std::string &raw_input_string,
1936 CommandReturnObject &result) {
1937 OptionArgVectorSP option_arg_vector_sp =
1938 GetAlias(alias_name)->GetOptionArguments();
1940 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1942 // Make sure that the alias name is the 0th element in cmd_args
1943 std::string alias_name_str = alias_name;
1944 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
1945 cmd_args.Unshift(alias_name_str);
1947 Args new_args(alias_cmd_obj->GetCommandName());
1948 if (new_args.GetArgumentCount() == 2)
1951 if (option_arg_vector_sp.get()) {
1952 if (wants_raw_input) {
1953 // We have a command that both has command options and takes raw input.
1954 // Make *sure* it has a
1955 // " -- " in the right place in the raw_input_string.
1956 size_t pos = raw_input_string.find(" -- ");
1957 if (pos == std::string::npos) {
1958 // None found; assume it goes at the beginning of the raw input string
1959 raw_input_string.insert(0, " -- ");
1963 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1964 const size_t old_size = cmd_args.GetArgumentCount();
1965 std::vector<bool> used(old_size + 1, false);
1972 for (const auto &option_entry : *option_arg_vector) {
1973 std::tie(option, value_type, value) = option_entry;
1974 if (option == "<argument>") {
1975 if (!wants_raw_input || (value != "--")) {
1976 // Since we inserted this above, make sure we don't insert it twice
1977 new_args.AppendArgument(value);
1982 if (value_type != OptionParser::eOptionalArgument)
1983 new_args.AppendArgument(option);
1985 if (value == "<no-argument>")
1988 int index = GetOptionArgumentPosition(value.c_str());
1990 // value was NOT a positional argument; must be a real value
1991 if (value_type != OptionParser::eOptionalArgument)
1992 new_args.AppendArgument(value);
1995 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1997 new_args.AppendArgument(llvm::StringRef(buffer));
2000 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
2001 result.AppendErrorWithFormat("Not enough arguments provided; you "
2002 "need at least %d arguments to use "
2005 result.SetStatus(eReturnStatusFailed);
2008 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2010 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2011 if (strpos != std::string::npos) {
2012 raw_input_string = raw_input_string.erase(
2013 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2016 if (value_type != OptionParser::eOptionalArgument)
2017 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2020 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2021 cmd_args.GetArgumentAtIndex(index));
2022 new_args.AppendArgument(buffer);
2028 for (auto entry : llvm::enumerate(cmd_args.entries())) {
2029 if (!used[entry.index()] && !wants_raw_input)
2030 new_args.AppendArgument(entry.value().ref);
2034 cmd_args.SetArguments(new_args.GetArgumentCount(),
2035 new_args.GetConstArgumentVector());
2037 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2038 // This alias was not created with any options; nothing further needs to be
2039 // done, unless it is a command that
2040 // wants raw input, in which case we need to clear the rest of the data from
2041 // cmd_args, since its in the raw
2043 if (wants_raw_input) {
2045 cmd_args.SetArguments(new_args.GetArgumentCount(),
2046 new_args.GetConstArgumentVector());
2051 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2055 int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2056 int position = 0; // Any string that isn't an argument position, i.e. '%'
2057 // followed by an integer, gets a position
2060 const char *cptr = in_string;
2062 // Does it start with '%'
2063 if (cptr[0] == '%') {
2066 // Is the rest of it entirely digits?
2067 if (isdigit(cptr[0])) {
2068 const char *start = cptr;
2069 while (isdigit(cptr[0]))
2072 // We've gotten to the end of the digits; are we at the end of the string?
2073 if (cptr[0] == '\0')
2074 position = atoi(start);
2081 void CommandInterpreter::SourceInitFile(bool in_cwd,
2082 CommandReturnObject &result) {
2085 ExecutionContext exe_ctx(GetExecutionContext());
2086 Target *target = exe_ctx.GetTargetPtr();
2088 // In the current working directory we don't load any program specific
2089 // .lldbinit files, we only look for a ".lldbinit" file.
2090 if (m_skip_lldbinit_files)
2093 LoadCWDlldbinitFile should_load =
2094 target->TargetProperties::GetLoadCWDlldbinitFile();
2095 if (should_load == eLoadCWDlldbinitWarn) {
2096 FileSpec dot_lldb(".lldbinit", true);
2097 llvm::SmallString<64> home_dir_path;
2098 llvm::sys::path::home_directory(home_dir_path);
2099 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2100 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2101 homedir_dot_lldb.ResolvePath();
2102 if (dot_lldb.Exists() &&
2103 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2104 result.AppendErrorWithFormat(
2105 "There is a .lldbinit file in the current directory which is not "
2107 "To silence this warning without sourcing in the local "
2109 "add the following to the lldbinit file in your home directory:\n"
2110 " settings set target.load-cwd-lldbinit false\n"
2111 "To allow lldb to source .lldbinit files in the current working "
2113 "set the value of this variable to true. Only do so if you "
2115 "accept the security risk.");
2116 result.SetStatus(eReturnStatusFailed);
2119 } else if (should_load == eLoadCWDlldbinitTrue) {
2120 init_file.SetFile("./.lldbinit", true);
2124 // If we aren't looking in the current working directory we are looking
2125 // in the home directory. We will first see if there is an application
2126 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2127 // "-" and the name of the program. If this file doesn't exist, we fall
2128 // back to just the "~/.lldbinit" file. We also obey any requests to not
2129 // load the init files.
2130 llvm::SmallString<64> home_dir_path;
2131 llvm::sys::path::home_directory(home_dir_path);
2132 FileSpec profilePath(home_dir_path.c_str(), false);
2133 profilePath.AppendPathComponent(".lldbinit");
2134 std::string init_file_path = profilePath.GetPath();
2136 if (m_skip_app_init_files == false) {
2137 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2138 const char *program_name = program_file_spec.GetFilename().AsCString();
2141 char program_init_file_name[PATH_MAX];
2142 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2143 "%s-%s", init_file_path.c_str(), program_name);
2144 init_file.SetFile(program_init_file_name, true);
2145 if (!init_file.Exists())
2150 if (!init_file && !m_skip_lldbinit_files)
2151 init_file.SetFile(init_file_path, false);
2154 // If the file exists, tell HandleCommand to 'source' it; this will do the
2155 // actual broadcasting
2156 // of the commands back to any appropriate listener (see
2157 // CommandObjectSource::Execute for more details).
2159 if (init_file.Exists()) {
2160 const bool saved_batch = SetBatchCommandMode(true);
2161 CommandInterpreterRunOptions options;
2162 options.SetSilent(true);
2163 options.SetStopOnError(false);
2164 options.SetStopOnContinue(true);
2166 HandleCommandsFromFile(init_file,
2167 nullptr, // Execution context
2169 SetBatchCommandMode(saved_batch);
2171 // nothing to be done if the file doesn't exist
2172 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2176 const char *CommandInterpreter::GetCommandPrefix() {
2177 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2178 return prefix == NULL ? "" : prefix;
2181 PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2182 PlatformSP platform_sp;
2183 if (prefer_target_platform) {
2184 ExecutionContext exe_ctx(GetExecutionContext());
2185 Target *target = exe_ctx.GetTargetPtr();
2187 platform_sp = target->GetPlatform();
2191 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2195 void CommandInterpreter::HandleCommands(const StringList &commands,
2196 ExecutionContext *override_context,
2197 CommandInterpreterRunOptions &options,
2198 CommandReturnObject &result) {
2199 size_t num_lines = commands.GetSize();
2201 // If we are going to continue past a "continue" then we need to run the
2202 // commands synchronously.
2203 // Make sure you reset this value anywhere you return from the function.
2205 bool old_async_execution = m_debugger.GetAsyncExecution();
2207 // If we've been given an execution context, set it at the start, but don't
2208 // keep resetting it or we will
2209 // cause series of commands that change the context, then do an operation that
2210 // relies on that context to fail.
2212 if (override_context != nullptr)
2213 UpdateExecutionContext(override_context);
2215 if (!options.GetStopOnContinue()) {
2216 m_debugger.SetAsyncExecution(false);
2219 for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
2220 const char *cmd = commands.GetStringAtIndex(idx);
2224 if (options.GetEchoCommands()) {
2225 // TODO: Add Stream support.
2226 result.AppendMessageWithFormat("%s %s\n",
2227 m_debugger.GetPrompt().str().c_str(), cmd);
2230 CommandReturnObject tmp_result;
2231 // If override_context is not NULL, pass no_context_switching = true for
2232 // HandleCommand() since we updated our context already.
2234 // We might call into a regex or alias command, in which case the
2235 // add_to_history will get lost. This
2236 // m_command_source_depth dingus is the way we turn off adding to the
2237 // history in that case, so set it up here.
2238 if (!options.GetAddToHistory())
2239 m_command_source_depth++;
2241 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2242 nullptr, /* override_context */
2243 true, /* repeat_on_empty_command */
2244 override_context != nullptr /* no_context_switching */);
2245 if (!options.GetAddToHistory())
2246 m_command_source_depth--;
2248 if (options.GetPrintResults()) {
2249 if (tmp_result.Succeeded())
2250 result.AppendMessage(tmp_result.GetOutputData());
2253 if (!success || !tmp_result.Succeeded()) {
2254 llvm::StringRef error_msg = tmp_result.GetErrorData();
2255 if (error_msg.empty())
2256 error_msg = "<unknown error>.\n";
2257 if (options.GetStopOnError()) {
2258 result.AppendErrorWithFormat(
2259 "Aborting reading of commands after command #%" PRIu64
2260 ": '%s' failed with %s",
2261 (uint64_t)idx, cmd, error_msg.str().c_str());
2262 result.SetStatus(eReturnStatusFailed);
2263 m_debugger.SetAsyncExecution(old_async_execution);
2265 } else if (options.GetPrintResults()) {
2266 result.AppendMessageWithFormat(
2267 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2268 error_msg.str().c_str());
2272 if (result.GetImmediateOutputStream())
2273 result.GetImmediateOutputStream()->Flush();
2275 if (result.GetImmediateErrorStream())
2276 result.GetImmediateErrorStream()->Flush();
2278 // N.B. Can't depend on DidChangeProcessState, because the state coming into
2279 // the command execution
2280 // could be running (for instance in Breakpoint Commands.
2281 // So we check the return value to see if it is has running in it.
2282 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2283 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2284 if (options.GetStopOnContinue()) {
2285 // If we caused the target to proceed, and we're going to stop in that
2287 // status in our real result before returning. This is an error if the
2288 // continue was not the
2289 // last command in the set of commands to be run.
2290 if (idx != num_lines - 1)
2291 result.AppendErrorWithFormat(
2292 "Aborting reading of commands after command #%" PRIu64
2293 ": '%s' continued the target.\n",
2294 (uint64_t)idx + 1, cmd);
2296 result.AppendMessageWithFormat("Command #%" PRIu64
2297 " '%s' continued the target.\n",
2298 (uint64_t)idx + 1, cmd);
2300 result.SetStatus(tmp_result.GetStatus());
2301 m_debugger.SetAsyncExecution(old_async_execution);
2307 // Also check for "stop on crash here:
2308 bool should_stop = false;
2309 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2310 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2312 ProcessSP process_sp(target_sp->GetProcessSP());
2314 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2315 StopReason reason = thread_sp->GetStopReason();
2316 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2317 reason == eStopReasonInstrumentation) {
2325 if (idx != num_lines - 1)
2326 result.AppendErrorWithFormat(
2327 "Aborting reading of commands after command #%" PRIu64
2328 ": '%s' stopped with a signal or exception.\n",
2329 (uint64_t)idx + 1, cmd);
2331 result.AppendMessageWithFormat(
2332 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2333 (uint64_t)idx + 1, cmd);
2335 result.SetStatus(tmp_result.GetStatus());
2336 m_debugger.SetAsyncExecution(old_async_execution);
2343 result.SetStatus(eReturnStatusSuccessFinishResult);
2344 m_debugger.SetAsyncExecution(old_async_execution);
2349 // Make flags that we can pass into the IOHandler so our delegates can do the
2352 eHandleCommandFlagStopOnContinue = (1u << 0),
2353 eHandleCommandFlagStopOnError = (1u << 1),
2354 eHandleCommandFlagEchoCommand = (1u << 2),
2355 eHandleCommandFlagPrintResult = (1u << 3),
2356 eHandleCommandFlagStopOnCrash = (1u << 4)
2359 void CommandInterpreter::HandleCommandsFromFile(
2360 FileSpec &cmd_file, ExecutionContext *context,
2361 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2362 if (cmd_file.Exists()) {
2363 StreamFileSP input_file_sp(new StreamFile());
2365 std::string cmd_file_path = cmd_file.GetPath();
2366 Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2367 File::eOpenOptionRead);
2369 if (error.Success()) {
2370 Debugger &debugger = GetDebugger();
2374 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2375 if (m_command_source_flags.empty()) {
2376 // Stop on continue by default
2377 flags |= eHandleCommandFlagStopOnContinue;
2378 } else if (m_command_source_flags.back() &
2379 eHandleCommandFlagStopOnContinue) {
2380 flags |= eHandleCommandFlagStopOnContinue;
2382 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2383 flags |= eHandleCommandFlagStopOnContinue;
2386 if (options.m_stop_on_error == eLazyBoolCalculate) {
2387 if (m_command_source_flags.empty()) {
2388 if (GetStopCmdSourceOnError())
2389 flags |= eHandleCommandFlagStopOnError;
2390 } else if (m_command_source_flags.back() &
2391 eHandleCommandFlagStopOnError) {
2392 flags |= eHandleCommandFlagStopOnError;
2394 } else if (options.m_stop_on_error == eLazyBoolYes) {
2395 flags |= eHandleCommandFlagStopOnError;
2398 if (options.GetStopOnCrash()) {
2399 if (m_command_source_flags.empty()) {
2400 // Echo command by default
2401 flags |= eHandleCommandFlagStopOnCrash;
2402 } else if (m_command_source_flags.back() &
2403 eHandleCommandFlagStopOnCrash) {
2404 flags |= eHandleCommandFlagStopOnCrash;
2408 if (options.m_echo_commands == eLazyBoolCalculate) {
2409 if (m_command_source_flags.empty()) {
2410 // Echo command by default
2411 flags |= eHandleCommandFlagEchoCommand;
2412 } else if (m_command_source_flags.back() &
2413 eHandleCommandFlagEchoCommand) {
2414 flags |= eHandleCommandFlagEchoCommand;
2416 } else if (options.m_echo_commands == eLazyBoolYes) {
2417 flags |= eHandleCommandFlagEchoCommand;
2420 if (options.m_print_results == eLazyBoolCalculate) {
2421 if (m_command_source_flags.empty()) {
2422 // Print output by default
2423 flags |= eHandleCommandFlagPrintResult;
2424 } else if (m_command_source_flags.back() &
2425 eHandleCommandFlagPrintResult) {
2426 flags |= eHandleCommandFlagPrintResult;
2428 } else if (options.m_print_results == eLazyBoolYes) {
2429 flags |= eHandleCommandFlagPrintResult;
2432 if (flags & eHandleCommandFlagPrintResult) {
2433 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2434 cmd_file_path.c_str());
2437 // Used for inheriting the right settings when "command source" might have
2438 // nested "command source" commands
2439 lldb::StreamFileSP empty_stream_sp;
2440 m_command_source_flags.push_back(flags);
2441 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2442 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2443 empty_stream_sp, // Pass in an empty stream so we inherit the top
2444 // input reader output stream
2445 empty_stream_sp, // Pass in an empty stream so we inherit the top
2446 // input reader error stream
2448 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2450 debugger.GetPrompt(), llvm::StringRef(),
2451 false, // Not multi-line
2452 debugger.GetUseColor(), 0, *this));
2453 const bool old_async_execution = debugger.GetAsyncExecution();
2455 // Set synchronous execution if we are not stopping on continue
2456 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2457 debugger.SetAsyncExecution(false);
2459 m_command_source_depth++;
2461 debugger.RunIOHandler(io_handler_sp);
2462 if (!m_command_source_flags.empty())
2463 m_command_source_flags.pop_back();
2464 m_command_source_depth--;
2465 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2466 debugger.SetAsyncExecution(old_async_execution);
2468 result.AppendErrorWithFormat(
2469 "error: an error occurred read file '%s': %s\n",
2470 cmd_file_path.c_str(), error.AsCString());
2471 result.SetStatus(eReturnStatusFailed);
2475 result.AppendErrorWithFormat(
2476 "Error reading commands from file %s - file not found.\n",
2477 cmd_file.GetFilename().AsCString("<Unknown>"));
2478 result.SetStatus(eReturnStatusFailed);
2483 ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
2484 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
2485 if (!m_script_interpreter_sp) {
2488 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2489 m_script_interpreter_sp =
2490 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2492 return m_script_interpreter_sp.get();
2495 bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2497 void CommandInterpreter::SetSynchronous(bool value) {
2498 m_synchronous_execution = value;
2501 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2502 llvm::StringRef prefix,
2503 llvm::StringRef help_text) {
2504 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2506 size_t line_width_max = max_columns - prefix.size();
2507 if (line_width_max < 16)
2508 line_width_max = help_text.size() + prefix.size();
2510 strm.IndentMore(prefix.size());
2511 bool prefixed_yet = false;
2512 while (!help_text.empty()) {
2513 // Prefix the first line, indent subsequent lines to line up
2514 if (!prefixed_yet) {
2516 prefixed_yet = true;
2520 // Never print more than the maximum on one line.
2521 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2523 // Always break on an explicit newline.
2524 std::size_t first_newline = this_line.find_first_of("\n");
2526 // Don't break on space/tab unless the text is too long to fit on one line.
2527 std::size_t last_space = llvm::StringRef::npos;
2528 if (this_line.size() != help_text.size())
2529 last_space = this_line.find_last_of(" \t");
2531 // Break at whichever condition triggered first.
2532 this_line = this_line.substr(0, std::min(first_newline, last_space));
2533 strm.PutCString(this_line);
2536 // Remove whitespace / newlines after breaking.
2537 help_text = help_text.drop_front(this_line.size()).ltrim();
2539 strm.IndentLess(prefix.size());
2542 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2543 llvm::StringRef word_text,
2544 llvm::StringRef separator,
2545 llvm::StringRef help_text,
2546 size_t max_word_len) {
2547 StreamString prefix_stream;
2548 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2549 (int)separator.size(), separator.data());
2550 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2553 void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2554 llvm::StringRef separator,
2555 llvm::StringRef help_text,
2556 uint32_t max_word_len) {
2557 int indent_size = max_word_len + separator.size() + 2;
2559 strm.IndentMore(indent_size);
2561 StreamString text_strm;
2562 text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2563 text_strm << separator << " " << help_text;
2565 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2567 llvm::StringRef text = text_strm.GetString();
2569 uint32_t chars_left = max_columns;
2571 auto nextWordLength = [](llvm::StringRef S) {
2572 size_t pos = S.find_first_of(' ');
2573 return pos == llvm::StringRef::npos ? S.size() : pos;
2576 while (!text.empty()) {
2577 if (text.front() == '\n' ||
2578 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
2581 chars_left = max_columns - indent_size;
2582 if (text.front() == '\n')
2583 text = text.drop_front();
2585 text = text.ltrim(' ');
2587 strm.PutChar(text.front());
2589 text = text.drop_front();
2594 strm.IndentLess(indent_size);
2597 void CommandInterpreter::FindCommandsForApropos(
2598 llvm::StringRef search_word, StringList &commands_found,
2599 StringList &commands_help, CommandObject::CommandMap &command_map) {
2600 CommandObject::CommandMap::const_iterator pos;
2602 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
2603 llvm::StringRef command_name = pos->first;
2604 CommandObject *cmd_obj = pos->second.get();
2606 const bool search_short_help = true;
2607 const bool search_long_help = false;
2608 const bool search_syntax = false;
2609 const bool search_options = false;
2610 if (command_name.contains_lower(search_word) ||
2611 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2612 search_long_help, search_syntax,
2614 commands_found.AppendString(cmd_obj->GetCommandName());
2615 commands_help.AppendString(cmd_obj->GetHelp());
2618 if (cmd_obj->IsMultiwordObject()) {
2619 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2620 FindCommandsForApropos(search_word, commands_found, commands_help,
2621 cmd_multiword->GetSubcommandDictionary());
2626 void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
2627 StringList &commands_found,
2628 StringList &commands_help,
2629 bool search_builtin_commands,
2630 bool search_user_commands,
2631 bool search_alias_commands) {
2632 CommandObject::CommandMap::const_iterator pos;
2634 if (search_builtin_commands)
2635 FindCommandsForApropos(search_word, commands_found, commands_help,
2638 if (search_user_commands)
2639 FindCommandsForApropos(search_word, commands_found, commands_help,
2642 if (search_alias_commands)
2643 FindCommandsForApropos(search_word, commands_found, commands_help,
2647 void CommandInterpreter::UpdateExecutionContext(
2648 ExecutionContext *override_context) {
2649 if (override_context != nullptr) {
2650 m_exe_ctx_ref = *override_context;
2652 const bool adopt_selected = true;
2653 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2658 size_t CommandInterpreter::GetProcessOutput() {
2659 // The process has stuff waiting for stderr; get it and write it out to the
2660 // appropriate place.
2661 char stdio_buffer[1024];
2663 size_t total_bytes = 0;
2665 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2667 ProcessSP process_sp(target_sp->GetProcessSP());
2669 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2671 size_t bytes_written = len;
2672 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2675 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2677 size_t bytes_written = len;
2678 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2686 void CommandInterpreter::StartHandlingCommand() {
2687 auto idle_state = CommandHandlingState::eIdle;
2688 if (m_command_state.compare_exchange_strong(
2689 idle_state, CommandHandlingState::eInProgress))
2690 lldbassert(m_iohandler_nesting_level == 0);
2692 lldbassert(m_iohandler_nesting_level > 0);
2693 ++m_iohandler_nesting_level;
2696 void CommandInterpreter::FinishHandlingCommand() {
2697 lldbassert(m_iohandler_nesting_level > 0);
2698 if (--m_iohandler_nesting_level == 0) {
2699 auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2700 lldbassert(prev_state != CommandHandlingState::eIdle);
2704 bool CommandInterpreter::InterruptCommand() {
2705 auto in_progress = CommandHandlingState::eInProgress;
2706 return m_command_state.compare_exchange_strong(
2707 in_progress, CommandHandlingState::eInterrupted);
2710 bool CommandInterpreter::WasInterrupted() const {
2711 bool was_interrupted =
2712 (m_command_state == CommandHandlingState::eInterrupted);
2713 lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2714 return was_interrupted;
2717 void CommandInterpreter::PrintCommandOutput(Stream &stream,
2718 llvm::StringRef str) {
2719 // Split the output into lines and poll for interrupt requests
2720 const char *data = str.data();
2721 size_t size = str.size();
2722 while (size > 0 && !WasInterrupted()) {
2723 size_t chunk_size = 0;
2724 for (; chunk_size < size; ++chunk_size) {
2725 lldbassert(data[chunk_size] != '\0');
2726 if (data[chunk_size] == '\n') {
2731 chunk_size = stream.Write(data, chunk_size);
2732 lldbassert(size >= chunk_size);
2737 stream.Printf("\n... Interrupted.\n");
2741 void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2742 std::string &line) {
2743 // If we were interrupted, bail out...
2744 if (WasInterrupted())
2747 const bool is_interactive = io_handler.GetIsInteractive();
2748 if (is_interactive == false) {
2749 // When we are not interactive, don't execute blank lines. This will happen
2750 // sourcing a commands file. We don't want blank lines to repeat the
2752 // command and cause any errors to occur (like redefining an alias, get an
2754 // and stop parsing the commands file).
2758 // When using a non-interactive file handle (like when sourcing commands
2760 // we need to echo the command out so we don't just see the command output
2763 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2764 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2768 StartHandlingCommand();
2770 lldb_private::CommandReturnObject result;
2771 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2773 // Now emit the command output text from the command we just executed
2774 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2775 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2778 if (!result.GetImmediateOutputStream()) {
2779 llvm::StringRef output = result.GetOutputData();
2780 PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
2783 // Now emit the command error text from the command we just executed
2784 if (!result.GetImmediateErrorStream()) {
2785 llvm::StringRef error = result.GetErrorData();
2786 PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
2790 FinishHandlingCommand();
2792 switch (result.GetStatus()) {
2793 case eReturnStatusInvalid:
2794 case eReturnStatusSuccessFinishNoResult:
2795 case eReturnStatusSuccessFinishResult:
2796 case eReturnStatusStarted:
2799 case eReturnStatusSuccessContinuingNoResult:
2800 case eReturnStatusSuccessContinuingResult:
2801 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2802 io_handler.SetIsDone(true);
2805 case eReturnStatusFailed:
2807 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2808 io_handler.SetIsDone(true);
2811 case eReturnStatusQuit:
2812 m_quit_requested = true;
2813 io_handler.SetIsDone(true);
2817 // Finally, if we're going to stop on crash, check that here:
2818 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2819 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2820 bool should_stop = false;
2821 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2823 ProcessSP process_sp(target_sp->GetProcessSP());
2825 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2826 StopReason reason = thread_sp->GetStopReason();
2827 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2828 reason == eStopReasonInstrumentation) &&
2829 !result.GetAbnormalStopWasExpected()) {
2837 io_handler.SetIsDone(true);
2838 m_stopped_for_crash = true;
2843 bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2844 ExecutionContext exe_ctx(GetExecutionContext());
2845 Process *process = exe_ctx.GetProcessPtr();
2847 if (InterruptCommand())
2851 StateType state = process->GetState();
2852 if (StateIsRunningState(state)) {
2854 return true; // Don't do any updating when we are running
2858 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2859 if (script_interpreter) {
2860 if (script_interpreter->Interrupt())
2866 void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2867 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2869 Debugger &debugger = GetDebugger();
2870 IOHandlerSP io_handler_sp(
2871 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2872 "lldb", // Name of input reader for history
2873 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2874 llvm::StringRef(), // Continuation prompt
2875 true, // Get multiple lines
2876 debugger.GetUseColor(),
2877 0, // Don't show line numbers
2878 delegate)); // IOHandlerDelegate
2880 if (io_handler_sp) {
2881 io_handler_sp->SetUserData(baton);
2883 debugger.PushIOHandler(io_handler_sp);
2885 debugger.RunIOHandler(io_handler_sp);
2889 void CommandInterpreter::GetPythonCommandsFromIOHandler(
2890 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2892 Debugger &debugger = GetDebugger();
2893 IOHandlerSP io_handler_sp(
2894 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2895 "lldb-python", // Name of input reader for history
2896 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2897 llvm::StringRef(), // Continuation prompt
2898 true, // Get multiple lines
2899 debugger.GetUseColor(),
2900 0, // Don't show line numbers
2901 delegate)); // IOHandlerDelegate
2903 if (io_handler_sp) {
2904 io_handler_sp->SetUserData(baton);
2906 debugger.PushIOHandler(io_handler_sp);
2908 debugger.RunIOHandler(io_handler_sp);
2912 bool CommandInterpreter::IsActive() {
2913 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2917 CommandInterpreter::GetIOHandler(bool force_create,
2918 CommandInterpreterRunOptions *options) {
2919 // Always re-create the IOHandlerEditline in case the input
2920 // changed. The old instance might have had a non-interactive
2921 // input and now it does or vice versa.
2922 if (force_create || !m_command_io_handler_sp) {
2923 // Always re-create the IOHandlerEditline in case the input
2924 // changed. The old instance might have had a non-interactive
2925 // input and now it does or vice versa.
2929 if (options->m_stop_on_continue == eLazyBoolYes)
2930 flags |= eHandleCommandFlagStopOnContinue;
2931 if (options->m_stop_on_error == eLazyBoolYes)
2932 flags |= eHandleCommandFlagStopOnError;
2933 if (options->m_stop_on_crash == eLazyBoolYes)
2934 flags |= eHandleCommandFlagStopOnCrash;
2935 if (options->m_echo_commands != eLazyBoolNo)
2936 flags |= eHandleCommandFlagEchoCommand;
2937 if (options->m_print_results != eLazyBoolNo)
2938 flags |= eHandleCommandFlagPrintResult;
2940 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2943 m_command_io_handler_sp.reset(new IOHandlerEditline(
2944 m_debugger, IOHandler::Type::CommandInterpreter,
2945 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2946 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
2947 llvm::StringRef(), // Continuation prompt
2948 false, // Don't enable multiple line input, just single line commands
2949 m_debugger.GetUseColor(),
2950 0, // Don't show line numbers
2953 return m_command_io_handler_sp;
2956 void CommandInterpreter::RunCommandInterpreter(
2957 bool auto_handle_events, bool spawn_thread,
2958 CommandInterpreterRunOptions &options) {
2959 // Always re-create the command interpreter when we run it in case
2960 // any file handles have changed.
2961 bool force_create = true;
2962 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2963 m_stopped_for_crash = false;
2965 if (auto_handle_events)
2966 m_debugger.StartEventHandlerThread();
2969 m_debugger.StartIOHandlerThread();
2971 m_debugger.ExecuteIOHandlers();
2973 if (auto_handle_events)
2974 m_debugger.StopEventHandlerThread();
2979 CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2980 CommandReturnObject &result) {
2981 std::string scratch_command(command_line); // working copy so we don't modify
2982 // command_line unless we succeed
2983 CommandObject *cmd_obj = nullptr;
2984 StreamString revised_command_line;
2985 bool wants_raw_input = false;
2986 size_t actual_cmd_name_len = 0;
2987 std::string next_word;
2991 char quote_char = '\0';
2993 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2994 if (cmd_obj == nullptr) {
2995 std::string full_name;
2996 bool is_alias = GetAliasFullName(next_word, full_name);
2997 cmd_obj = GetCommandObject(next_word, &matches);
2998 bool is_real_command =
2999 (is_alias == false) ||
3000 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
3001 if (!is_real_command) {
3003 std::string alias_result;
3005 BuildAliasResult(full_name, scratch_command, alias_result, result);
3006 revised_command_line.Printf("%s", alias_result.c_str());
3008 wants_raw_input = cmd_obj->WantsRawCommandString();
3009 actual_cmd_name_len = cmd_obj->GetCommandName().size();
3013 cmd_obj = GetCommandObject(next_word, &matches);
3015 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3016 actual_cmd_name_len += cmd_name.size();
3017 revised_command_line.Printf("%s", cmd_name.str().c_str());
3018 wants_raw_input = cmd_obj->WantsRawCommandString();
3020 revised_command_line.Printf("%s", next_word.c_str());
3024 if (cmd_obj->IsMultiwordObject()) {
3025 CommandObject *sub_cmd_obj =
3026 cmd_obj->GetSubcommandObject(next_word.c_str());
3028 // The subcommand's name includes the parent command's name,
3029 // so restart rather than append to the revised_command_line.
3030 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3031 actual_cmd_name_len = sub_cmd_name.size() + 1;
3032 revised_command_line.Clear();
3033 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
3034 cmd_obj = sub_cmd_obj;
3035 wants_raw_input = cmd_obj->WantsRawCommandString();
3038 revised_command_line.Printf(" %c%s%s%c", quote_char,
3039 next_word.c_str(), suffix.c_str(),
3042 revised_command_line.Printf(" %s%s", next_word.c_str(),
3048 revised_command_line.Printf(" %c%s%s%c", quote_char,
3049 next_word.c_str(), suffix.c_str(),
3052 revised_command_line.Printf(" %s%s", next_word.c_str(),
3058 if (cmd_obj == nullptr) {
3059 const size_t num_matches = matches.GetSize();
3060 if (matches.GetSize() > 1) {
3061 StreamString error_msg;
3062 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3065 for (uint32_t i = 0; i < num_matches; ++i) {
3066 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3068 result.AppendRawError(error_msg.GetString());
3070 // We didn't have only one match, otherwise we wouldn't get here.
3071 lldbassert(num_matches == 0);
3072 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3075 result.SetStatus(eReturnStatusFailed);
3079 if (cmd_obj->IsMultiwordObject()) {
3080 if (!suffix.empty()) {
3081 result.AppendErrorWithFormat(
3082 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3083 "might be invalid).\n",
3084 cmd_obj->GetCommandName().str().c_str(),
3085 next_word.empty() ? "" : next_word.c_str(),
3086 next_word.empty() ? " -- " : " ", suffix.c_str());
3087 result.SetStatus(eReturnStatusFailed);
3091 // If we found a normal command, we are done
3093 if (!suffix.empty()) {
3094 switch (suffix[0]) {
3096 // GDB format suffixes
3098 Options *command_options = cmd_obj->GetOptions();
3099 if (command_options &&
3100 command_options->SupportsLongOption("gdb-format")) {
3101 std::string gdb_format_option("--gdb-format=");
3102 gdb_format_option += (suffix.c_str() + 1);
3104 std::string cmd = revised_command_line.GetString();
3105 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3106 if (arg_terminator_idx != std::string::npos) {
3107 // Insert the gdb format option before the "--" that terminates
3109 gdb_format_option.append(1, ' ');
3110 cmd.insert(arg_terminator_idx, gdb_format_option);
3111 revised_command_line.Clear();
3112 revised_command_line.PutCString(cmd);
3114 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3116 if (wants_raw_input &&
3117 FindArgumentTerminator(cmd) == std::string::npos)
3118 revised_command_line.PutCString(" --");
3120 result.AppendErrorWithFormat(
3121 "the '%s' command doesn't support the --gdb-format option\n",
3122 cmd_obj->GetCommandName().str().c_str());
3123 result.SetStatus(eReturnStatusFailed);
3130 result.AppendErrorWithFormat(
3131 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3132 result.SetStatus(eReturnStatusFailed);
3137 if (scratch_command.empty())
3141 if (!scratch_command.empty())
3142 revised_command_line.Printf(" %s", scratch_command.c_str());
3144 if (cmd_obj != NULL)
3145 command_line = revised_command_line.GetString();