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/Log.h"
46 #include "lldb/Core/PluginManager.h"
47 #include "lldb/Core/State.h"
48 #include "lldb/Core/Stream.h"
49 #include "lldb/Core/StreamFile.h"
50 #include "lldb/Core/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 Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION);
174 CommandReturnObject result;
176 LoadCommandDictionary();
178 // An alias arguments vector to reuse - reset it before use...
179 OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
181 // Set up some initial aliases.
182 CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
184 AddAlias("q", cmd_obj_sp);
185 AddAlias("exit", cmd_obj_sp);
188 cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
190 AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
192 cmd_obj_sp = GetCommandSPExact("process detach", false);
194 AddAlias("detach", cmd_obj_sp);
197 cmd_obj_sp = GetCommandSPExact("process continue", false);
199 AddAlias("c", cmd_obj_sp);
200 AddAlias("continue", cmd_obj_sp);
203 cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
205 AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
207 cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
209 AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
211 cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
213 AddAlias("stepi", cmd_obj_sp);
214 AddAlias("si", cmd_obj_sp);
217 cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
219 AddAlias("nexti", cmd_obj_sp);
220 AddAlias("ni", cmd_obj_sp);
223 cmd_obj_sp = GetCommandSPExact("thread step-in", false);
225 AddAlias("s", cmd_obj_sp);
226 AddAlias("step", cmd_obj_sp);
227 CommandAlias *sif_alias = AddAlias(
228 "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
230 sif_alias->SetHelp("Step through the current block, stopping if you step "
231 "directly into a function whose name matches the "
232 "TargetFunctionName.");
233 sif_alias->SetSyntax("sif <TargetFunctionName>");
237 cmd_obj_sp = GetCommandSPExact("thread step-over", false);
239 AddAlias("n", cmd_obj_sp);
240 AddAlias("next", cmd_obj_sp);
243 cmd_obj_sp = GetCommandSPExact("thread step-out", false);
245 AddAlias("finish", cmd_obj_sp);
248 cmd_obj_sp = GetCommandSPExact("frame select", false);
250 AddAlias("f", cmd_obj_sp);
253 cmd_obj_sp = GetCommandSPExact("thread select", false);
255 AddAlias("t", cmd_obj_sp);
258 cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
260 AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
261 AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
264 cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
266 AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
267 AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
270 cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
272 AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
274 cmd_obj_sp = GetCommandSPExact("memory read", false);
276 AddAlias("x", cmd_obj_sp);
278 cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
280 AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
282 cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
284 AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
286 cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
288 AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
290 cmd_obj_sp = GetCommandSPExact("disassemble", false);
292 AddAlias("dis", cmd_obj_sp);
294 cmd_obj_sp = GetCommandSPExact("disassemble", false);
296 AddAlias("di", cmd_obj_sp);
298 cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
300 AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
302 cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
304 AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
306 cmd_obj_sp = GetCommandSPExact("target create", false);
308 AddAlias("file", cmd_obj_sp);
310 cmd_obj_sp = GetCommandSPExact("target modules", false);
312 AddAlias("image", cmd_obj_sp);
314 alias_arguments_vector_sp.reset(new OptionArgVector);
316 cmd_obj_sp = GetCommandSPExact("expression", false);
318 AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
319 AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
320 AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
321 if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
322 po->SetHelp("Evaluate an expression on the current thread. Displays any "
323 "returned value with formatting "
324 "controlled by the type's author.");
327 AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
328 AddAlias("poarray", cmd_obj_sp,
329 "--object-description --element-count %1 --")
333 cmd_obj_sp = GetCommandSPExact("process kill", false);
335 AddAlias("kill", cmd_obj_sp);
338 cmd_obj_sp = GetCommandSPExact("process launch", false);
340 alias_arguments_vector_sp.reset(new OptionArgVector);
341 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
342 AddAlias("r", cmd_obj_sp, "--");
343 AddAlias("run", cmd_obj_sp, "--");
345 #if defined(__APPLE__)
346 std::string shell_option;
347 shell_option.append("--shell-expand-args");
348 shell_option.append(" true");
349 shell_option.append(" --");
350 AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
351 AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
353 StreamString defaultshell;
354 defaultshell.Printf("--shell=%s --",
355 HostInfo::GetDefaultShell().GetPath().c_str());
356 AddAlias("r", cmd_obj_sp, defaultshell.GetString());
357 AddAlias("run", cmd_obj_sp, defaultshell.GetString());
362 cmd_obj_sp = GetCommandSPExact("target symbols add", false);
364 AddAlias("add-dsym", cmd_obj_sp);
367 cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
369 AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
373 void CommandInterpreter::Clear() {
374 m_command_io_handler_sp.reset();
376 if (m_script_interpreter_sp)
377 m_script_interpreter_sp->Clear();
380 const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
381 // This function has not yet been implemented.
383 // Look for any embedded script command
385 // get interpreter object from the command dictionary,
386 // call execute_one_command on it,
387 // get the results as a string,
388 // substitute that string for current stuff.
393 void CommandInterpreter::LoadCommandDictionary() {
394 Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION);
396 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
398 m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
399 m_command_dict["breakpoint"] =
400 CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
401 m_command_dict["bugreport"] =
402 CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
403 m_command_dict["command"] =
404 CommandObjectSP(new CommandObjectMultiwordCommands(*this));
405 m_command_dict["disassemble"] =
406 CommandObjectSP(new CommandObjectDisassemble(*this));
407 m_command_dict["expression"] =
408 CommandObjectSP(new CommandObjectExpression(*this));
409 m_command_dict["frame"] =
410 CommandObjectSP(new CommandObjectMultiwordFrame(*this));
411 m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
412 m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
413 m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
414 m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
415 m_command_dict["platform"] =
416 CommandObjectSP(new CommandObjectPlatform(*this));
417 m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
418 m_command_dict["process"] =
419 CommandObjectSP(new CommandObjectMultiwordProcess(*this));
420 m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
421 m_command_dict["register"] =
422 CommandObjectSP(new CommandObjectRegister(*this));
423 m_command_dict["script"] =
424 CommandObjectSP(new CommandObjectScript(*this, script_language));
425 m_command_dict["settings"] =
426 CommandObjectSP(new CommandObjectMultiwordSettings(*this));
427 m_command_dict["source"] =
428 CommandObjectSP(new CommandObjectMultiwordSource(*this));
429 m_command_dict["target"] =
430 CommandObjectSP(new CommandObjectMultiwordTarget(*this));
431 m_command_dict["thread"] =
432 CommandObjectSP(new CommandObjectMultiwordThread(*this));
433 m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
434 m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
435 m_command_dict["watchpoint"] =
436 CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
437 m_command_dict["language"] =
438 CommandObjectSP(new CommandObjectLanguage(*this));
440 const char *break_regexes[][2] = {
441 {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
442 "breakpoint set --file '%1' --line %2"},
443 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
444 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
445 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
446 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
447 "breakpoint set --name '%1'"},
448 {"^(-.*)$", "breakpoint set %1"},
449 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
450 "breakpoint set --name '%2' --shlib '%1'"},
451 {"^\\&(.*[^[:space:]])[[:space:]]*$",
452 "breakpoint set --name '%1' --skip-prologue=0"},
453 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
454 "breakpoint set --name '%1'"}};
456 size_t num_regexes = llvm::array_lengthof(break_regexes);
458 std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(
459 new CommandObjectRegexCommand(
460 *this, "_regexp-break",
461 "Set a breakpoint using one of several shorthand formats.\n",
463 "_regexp-break <filename>:<linenum>\n"
464 " main.c:12 // Break at line 12 of "
466 "_regexp-break <linenum>\n"
467 " 12 // Break at line 12 of current "
469 "_regexp-break 0x<address>\n"
470 " 0x1234000 // Break at address "
472 "_regexp-break <name>\n"
473 " main // Break in 'main' after the "
475 "_regexp-break &<name>\n"
476 " &main // Break at first instruction "
478 "_regexp-break <module>`<name>\n"
479 " libc.so`malloc // Break in 'malloc' from "
481 "_regexp-break /<source-regex>/\n"
482 " /break here/ // Break on source lines in "
484 " // containing text 'break "
486 2, CommandCompletions::eSymbolCompletion |
487 CommandCompletions::eSourceFileCompletion,
490 if (break_regex_cmd_ap.get()) {
492 for (size_t i = 0; i < num_regexes; i++) {
493 success = break_regex_cmd_ap->AddRegexCommand(break_regexes[i][0],
494 break_regexes[i][1]);
499 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
502 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
503 m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
507 std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(
508 new CommandObjectRegexCommand(
509 *this, "_regexp-tbreak",
510 "Set a one-shot breakpoint using one of several shorthand formats.\n",
512 "_regexp-break <filename>:<linenum>\n"
513 " main.c:12 // Break at line 12 of "
515 "_regexp-break <linenum>\n"
516 " 12 // Break at line 12 of current "
518 "_regexp-break 0x<address>\n"
519 " 0x1234000 // Break at address "
521 "_regexp-break <name>\n"
522 " main // Break in 'main' after the "
524 "_regexp-break &<name>\n"
525 " &main // Break at first instruction "
527 "_regexp-break <module>`<name>\n"
528 " libc.so`malloc // Break in 'malloc' from "
530 "_regexp-break /<source-regex>/\n"
531 " /break here/ // Break on source lines in "
533 " // containing text 'break "
535 2, CommandCompletions::eSymbolCompletion |
536 CommandCompletions::eSourceFileCompletion,
539 if (tbreak_regex_cmd_ap.get()) {
541 for (size_t i = 0; i < num_regexes; i++) {
542 // If you add a resultant command string longer than 1024 characters be
543 // sure to increase the size of this buffer.
546 snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
547 assert(num_printed < 1024);
548 UNUSED_IF_ASSERT_DISABLED(num_printed);
550 tbreak_regex_cmd_ap->AddRegexCommand(break_regexes[i][0], buffer);
555 tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
558 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
559 m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
564 std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(
565 new CommandObjectRegexCommand(
566 *this, "_regexp-attach", "Attach to process by ID or name.",
567 "_regexp-attach <pid> | <process-name>", 2, 0, false));
568 if (attach_regex_cmd_ap.get()) {
569 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
570 "process attach --pid %1") &&
571 attach_regex_cmd_ap->AddRegexCommand(
572 "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
573 // specified get passed to
575 attach_regex_cmd_ap->AddRegexCommand("^(.+)$",
576 "process attach --name '%1'") &&
577 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) {
578 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
579 m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
584 std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(
585 new CommandObjectRegexCommand(*this, "_regexp-down",
586 "Select a newer stack frame. Defaults to "
587 "moving one frame, a numeric argument can "
588 "specify an arbitrary number.",
589 "_regexp-down [<count>]", 2, 0, false));
590 if (down_regex_cmd_ap.get()) {
591 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
592 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
593 "frame select -r -%1")) {
594 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
595 m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
599 std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(
600 new CommandObjectRegexCommand(
602 "Select an older stack frame. Defaults to moving one "
603 "frame, a numeric argument can specify an arbitrary number.",
604 "_regexp-up [<count>]", 2, 0, false));
605 if (up_regex_cmd_ap.get()) {
606 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
607 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
608 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
609 m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
613 std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(
614 new CommandObjectRegexCommand(
615 *this, "_regexp-display",
616 "Evaluate an expression at every stop (see 'help target stop-hook'.)",
617 "_regexp-display expression", 2, 0, false));
618 if (display_regex_cmd_ap.get()) {
619 if (display_regex_cmd_ap->AddRegexCommand(
620 "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
621 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
622 m_command_dict[display_regex_cmd_sp->GetCommandName()] =
623 display_regex_cmd_sp;
627 std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(
628 new CommandObjectRegexCommand(
629 *this, "_regexp-undisplay", "Stop displaying expression at every "
630 "stop (specified by stop-hook index.)",
631 "_regexp-undisplay stop-hook-number", 2, 0, false));
632 if (undisplay_regex_cmd_ap.get()) {
633 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
634 "target stop-hook delete %1")) {
635 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
636 m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
637 undisplay_regex_cmd_sp;
641 std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(
642 new CommandObjectRegexCommand(
643 *this, "gdb-remote", "Connect to a process via remote GDB server. "
644 "If no host is specifed, localhost is assumed.",
645 "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
646 if (connect_gdb_remote_cmd_ap.get()) {
647 if (connect_gdb_remote_cmd_ap->AddRegexCommand(
648 "^([^:]+:[[:digit:]]+)$",
649 "process connect --plugin gdb-remote connect://%1") &&
650 connect_gdb_remote_cmd_ap->AddRegexCommand(
652 "process connect --plugin gdb-remote connect://localhost:%1")) {
653 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
654 m_command_dict[command_sp->GetCommandName()] = command_sp;
658 std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(
659 new CommandObjectRegexCommand(
660 *this, "kdp-remote", "Connect to a process via remote KDP server. "
661 "If no UDP port is specified, port 41139 is "
663 "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
664 if (connect_kdp_remote_cmd_ap.get()) {
665 if (connect_kdp_remote_cmd_ap->AddRegexCommand(
666 "^([^:]+:[[:digit:]]+)$",
667 "process connect --plugin kdp-remote udp://%1") &&
668 connect_kdp_remote_cmd_ap->AddRegexCommand(
669 "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
670 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
671 m_command_dict[command_sp->GetCommandName()] = command_sp;
675 std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(
676 new CommandObjectRegexCommand(
678 "Show the current thread's call stack. Any numeric argument "
679 "displays at most that many "
680 "frames. The argument 'all' displays all threads.",
681 "bt [<digit> | all]", 2, 0, false));
682 if (bt_regex_cmd_ap.get()) {
683 // accept but don't document "bt -c <number>" -- before bt was a regex
684 // command if you wanted to backtrace
685 // three frames you would do "bt -c 3" but the intention is to have this
686 // emulate the gdb "bt" command and
687 // so now "bt 3" is the preferred form, in line with gdb.
688 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$",
689 "thread backtrace -c %1") &&
690 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$",
691 "thread backtrace -c %1") &&
692 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
693 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) {
694 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
695 m_command_dict[command_sp->GetCommandName()] = command_sp;
699 std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(
700 new CommandObjectRegexCommand(
701 *this, "_regexp-list",
702 "List relevant source code using one of several shorthand formats.",
704 "_regexp-list <file>:<line> // List around specific file/line\n"
705 "_regexp-list <line> // List current file around specified "
707 "_regexp-list <function-name> // List specified function\n"
708 "_regexp-list 0x<address> // List around specified address\n"
709 "_regexp-list -[<count>] // List previous <count> lines\n"
710 "_regexp-list // List subsequent lines",
711 2, CommandCompletions::eSourceFileCompletion, false));
712 if (list_regex_cmd_ap.get()) {
713 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$",
714 "source list --line %1") &&
715 list_regex_cmd_ap->AddRegexCommand(
716 "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
718 "source list --file '%1' --line %2") &&
719 list_regex_cmd_ap->AddRegexCommand(
720 "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
721 "source list --address %1") &&
722 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$",
723 "source list --reverse") &&
724 list_regex_cmd_ap->AddRegexCommand(
725 "^-([[:digit:]]+)[[:space:]]*$",
726 "source list --reverse --count %1") &&
727 list_regex_cmd_ap->AddRegexCommand("^(.+)$",
728 "source list --name \"%1\"") &&
729 list_regex_cmd_ap->AddRegexCommand("^$", "source list")) {
730 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
731 m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
735 std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(
736 new CommandObjectRegexCommand(
737 *this, "_regexp-env",
738 "Shorthand for viewing and setting environment variables.",
740 "_regexp-env // Show enrivonment\n"
741 "_regexp-env <name>=<value> // Set an environment variable",
743 if (env_regex_cmd_ap.get()) {
744 if (env_regex_cmd_ap->AddRegexCommand("^$",
745 "settings show target.env-vars") &&
746 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
747 "settings set target.env-vars %1")) {
748 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
749 m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
753 std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(
754 new CommandObjectRegexCommand(
755 *this, "_regexp-jump", "Set the program counter to a new address.",
757 "_regexp-jump <line>\n"
758 "_regexp-jump +<line-offset> | -<line-offset>\n"
759 "_regexp-jump <file>:<line>\n"
760 "_regexp-jump *<addr>\n",
762 if (jump_regex_cmd_ap.get()) {
763 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$",
764 "thread jump --addr %1") &&
765 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$",
766 "thread jump --line %1") &&
767 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$",
768 "thread jump --file %1 --line %2") &&
769 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$",
770 "thread jump --by %1")) {
771 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
772 m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
777 int CommandInterpreter::GetCommandNamesMatchingPartialString(
778 const char *cmd_str, bool include_aliases, StringList &matches) {
779 AddNamesMatchingPartialString(m_command_dict, cmd_str, matches);
781 if (include_aliases) {
782 AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches);
785 return matches.GetSize();
788 CommandObjectSP CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str,
789 bool include_aliases,
791 StringList *matches) const {
792 CommandObjectSP command_sp;
794 std::string cmd = cmd_str;
797 auto pos = m_command_dict.find(cmd);
798 if (pos != m_command_dict.end())
799 command_sp = pos->second;
802 if (include_aliases && HasAliases()) {
803 auto alias_pos = m_alias_dict.find(cmd);
804 if (alias_pos != m_alias_dict.end())
805 command_sp = alias_pos->second;
808 if (HasUserCommands()) {
809 auto pos = m_user_dict.find(cmd);
810 if (pos != m_user_dict.end())
811 command_sp = pos->second;
814 if (!exact && !command_sp) {
815 // We will only get into here if we didn't find any exact matches.
817 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
819 StringList local_matches;
820 if (matches == nullptr)
821 matches = &local_matches;
823 unsigned int num_cmd_matches = 0;
824 unsigned int num_alias_matches = 0;
825 unsigned int num_user_matches = 0;
827 // Look through the command dictionaries one by one, and if we get only one
829 // them in toto, then return that, otherwise return an empty CommandObjectSP
830 // and the list of matches.
834 AddNamesMatchingPartialString(m_command_dict, cmd_str, *matches);
837 if (num_cmd_matches == 1) {
838 cmd.assign(matches->GetStringAtIndex(0));
839 auto pos = m_command_dict.find(cmd);
840 if (pos != m_command_dict.end())
841 real_match_sp = pos->second;
844 if (include_aliases && HasAliases()) {
846 AddNamesMatchingPartialString(m_alias_dict, cmd_str, *matches);
849 if (num_alias_matches == 1) {
850 cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
851 auto alias_pos = m_alias_dict.find(cmd);
852 if (alias_pos != m_alias_dict.end())
853 alias_match_sp = alias_pos->second;
856 if (HasUserCommands()) {
858 AddNamesMatchingPartialString(m_user_dict, cmd_str, *matches);
861 if (num_user_matches == 1) {
863 matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
865 auto pos = m_user_dict.find(cmd);
866 if (pos != m_user_dict.end())
867 user_match_sp = pos->second;
870 // If we got exactly one match, return that, otherwise return the match
873 if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
875 return real_match_sp;
876 else if (num_alias_matches)
877 return alias_match_sp;
879 return user_match_sp;
881 } else if (matches && command_sp) {
882 matches->AppendString(cmd_str);
888 bool CommandInterpreter::AddCommand(llvm::StringRef name,
889 const lldb::CommandObjectSP &cmd_sp,
892 assert((this == &cmd_sp->GetCommandInterpreter()) &&
893 "tried to add a CommandObject from a different interpreter");
898 std::string name_sstr(name);
899 auto name_iter = m_command_dict.find(name_sstr);
900 if (name_iter != m_command_dict.end()) {
901 if (!can_replace || !name_iter->second->IsRemovable())
903 name_iter->second = cmd_sp;
905 m_command_dict[name_sstr] = cmd_sp;
910 bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
911 const lldb::CommandObjectSP &cmd_sp,
914 assert((this == &cmd_sp->GetCommandInterpreter()) &&
915 "tried to add a CommandObject from a different interpreter");
918 // do not allow replacement of internal commands
919 if (CommandExists(name)) {
920 if (can_replace == false)
922 if (m_command_dict[name]->IsRemovable() == false)
926 if (UserCommandExists(name)) {
927 if (can_replace == false)
929 if (m_user_dict[name]->IsRemovable() == false)
933 m_user_dict[name] = cmd_sp;
939 CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
940 bool include_aliases) const {
941 Args cmd_words(cmd_str); // Break up the command string into words, in case
942 // it's a multi-word command.
943 CommandObjectSP ret_val; // Possibly empty return value.
948 if (cmd_words.GetArgumentCount() == 1)
949 return GetCommandSP(cmd_str, include_aliases, true, nullptr);
951 // We have a multi-word command (seemingly), so we need to do more work.
952 // First, get the cmd_obj_sp for the first word in the command.
953 CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
954 include_aliases, true, nullptr);
955 if (cmd_obj_sp.get() != nullptr) {
956 // Loop through the rest of the words in the command (everything passed in
957 // was supposed to be part of a
958 // command name), and find the appropriate sub-command SP for each command
960 size_t end = cmd_words.GetArgumentCount();
961 for (size_t j = 1; j < end; ++j) {
962 if (cmd_obj_sp->IsMultiwordObject()) {
964 cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
965 if (cmd_obj_sp.get() == nullptr)
966 // The sub-command name was invalid. Fail and return the empty
970 // We have more words in the command name, but we don't have a
971 // multiword object. Fail and return empty 'ret_val'.
974 // We successfully looped through all the command words and got valid
975 // command objects for them. Assign the last object retrieved to
977 ret_val = cmd_obj_sp;
983 CommandObject *CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
984 StringList *matches) const {
985 CommandObject *command_obj =
986 GetCommandSP(cmd_str, false, true, matches).get();
988 // If we didn't find an exact match to the command string in the commands,
995 command_obj = GetCommandSP(cmd_str, true, true, matches).get();
1000 // If there wasn't an exact match then look for an inexact one in just the
1002 command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
1004 // Finally, if there wasn't an inexact match among the commands, look for an
1006 // match in both the commands and aliases.
1010 matches->AppendString(command_obj->GetCommandName());
1014 return GetCommandSP(cmd_str, true, false, matches).get();
1017 bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
1018 return m_command_dict.find(cmd) != m_command_dict.end();
1021 bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1022 std::string &full_name) const {
1023 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1025 full_name.assign(cmd);
1029 size_t num_alias_matches;
1031 AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1032 if (num_alias_matches == 1) {
1033 // Make sure this isn't shadowing a command in the regular command space:
1034 StringList regular_matches;
1035 const bool include_aliases = false;
1036 const bool exact = false;
1037 CommandObjectSP cmd_obj_sp(
1038 GetCommandSP(cmd, include_aliases, exact, ®ular_matches));
1039 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1042 full_name.assign(matches.GetStringAtIndex(0));
1050 bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
1051 return m_alias_dict.find(cmd) != m_alias_dict.end();
1054 bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
1055 return m_user_dict.find(cmd) != m_user_dict.end();
1059 CommandInterpreter::AddAlias(llvm::StringRef alias_name,
1060 lldb::CommandObjectSP &command_obj_sp,
1061 llvm::StringRef args_string) {
1062 if (command_obj_sp.get())
1063 assert((this == &command_obj_sp->GetCommandInterpreter()) &&
1064 "tried to add a CommandObject from a different interpreter");
1066 std::unique_ptr<CommandAlias> command_alias_up(
1067 new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1069 if (command_alias_up && command_alias_up->IsValid()) {
1070 m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1071 return command_alias_up.release();
1077 bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
1078 auto pos = m_alias_dict.find(alias_name);
1079 if (pos != m_alias_dict.end()) {
1080 m_alias_dict.erase(pos);
1086 bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
1087 auto pos = m_command_dict.find(cmd);
1088 if (pos != m_command_dict.end()) {
1089 if (pos->second->IsRemovable()) {
1090 // Only regular expression objects or python commands are removable
1091 m_command_dict.erase(pos);
1097 bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
1098 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1099 if (pos != m_user_dict.end()) {
1100 m_user_dict.erase(pos);
1106 void CommandInterpreter::GetHelp(CommandReturnObject &result,
1107 uint32_t cmd_types) {
1108 llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1109 if (!help_prologue.empty()) {
1110 OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1114 CommandObject::CommandMap::const_iterator pos;
1115 size_t max_len = FindLongestCommandWord(m_command_dict);
1117 if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1118 result.AppendMessage("Debugger commands:");
1119 result.AppendMessage("");
1121 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1122 if (!(cmd_types & eCommandTypesHidden) &&
1123 (pos->first.compare(0, 1, "_") == 0))
1126 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1127 pos->second->GetHelp(), max_len);
1129 result.AppendMessage("");
1132 if (!m_alias_dict.empty() &&
1133 ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1134 result.AppendMessageWithFormat(
1135 "Current command abbreviations "
1136 "(type '%shelp command alias' for more info):\n",
1137 GetCommandPrefix());
1138 result.AppendMessage("");
1139 max_len = FindLongestCommandWord(m_alias_dict);
1141 for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1143 OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
1144 alias_pos->second->GetHelp(), max_len);
1146 result.AppendMessage("");
1149 if (!m_user_dict.empty() &&
1150 ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1151 result.AppendMessage("Current user-defined commands:");
1152 result.AppendMessage("");
1153 max_len = FindLongestCommandWord(m_user_dict);
1154 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
1155 OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1156 pos->second->GetHelp(), max_len);
1158 result.AppendMessage("");
1161 result.AppendMessageWithFormat(
1162 "For more information on any command, type '%shelp <command-name>'.\n",
1163 GetCommandPrefix());
1166 CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1167 llvm::StringRef &command_string) {
1168 // This function finds the final, lowest-level, alias-resolved command object
1169 // whose 'Execute' function will
1170 // eventually be invoked by the given command line.
1172 CommandObject *cmd_obj = nullptr;
1173 size_t start = command_string.find_first_not_of(k_white_space);
1177 if (start != std::string::npos) {
1178 // Get the next word from command_string.
1179 end = command_string.find_first_of(k_white_space, start);
1180 if (end == std::string::npos)
1181 end = command_string.size();
1182 std::string cmd_word = command_string.substr(start, end - start);
1184 if (cmd_obj == nullptr)
1185 // Since cmd_obj is NULL we are on our first time through this loop.
1186 // Check to see if cmd_word is a valid command or alias.
1187 cmd_obj = GetCommandObject(cmd_word);
1188 else if (cmd_obj->IsMultiwordObject()) {
1189 // Our current object is a multi-word object; see if the cmd_word is a
1190 // valid sub-command for our object.
1191 CommandObject *sub_cmd_obj =
1192 cmd_obj->GetSubcommandObject(cmd_word.c_str());
1194 cmd_obj = sub_cmd_obj;
1195 else // cmd_word was not a valid sub-command word, so we are done
1198 // We have a cmd_obj and it is not a multi-word object, so we are done.
1201 // If we didn't find a valid command object, or our command object is not
1202 // a multi-word object, or we are at the end of the command_string, then
1203 // we are done. Otherwise, find the start of the next word.
1205 if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1206 end >= command_string.size())
1209 start = command_string.find_first_not_of(k_white_space, end);
1211 // Unable to find any more words.
1215 command_string = command_string.substr(end);
1219 static const char *k_valid_command_chars =
1220 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1221 static void StripLeadingSpaces(std::string &s) {
1223 size_t pos = s.find_first_not_of(k_white_space);
1224 if (pos == std::string::npos)
1232 static size_t FindArgumentTerminator(const std::string &s) {
1233 const size_t s_len = s.size();
1235 while (offset < s_len) {
1236 size_t pos = s.find("--", offset);
1237 if (pos == std::string::npos)
1240 if (isspace(s[pos - 1])) {
1241 // Check if the string ends "\s--" (where \s is a space character)
1242 // or if we have "\s--\s".
1243 if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1250 return std::string::npos;
1253 static bool ExtractCommand(std::string &command_string, std::string &command,
1254 std::string &suffix, char "e_char) {
1257 StripLeadingSpaces(command_string);
1259 bool result = false;
1262 if (!command_string.empty()) {
1263 const char first_char = command_string[0];
1264 if (first_char == '\'' || first_char == '"') {
1265 quote_char = first_char;
1266 const size_t end_quote_pos = command_string.find(quote_char, 1);
1267 if (end_quote_pos == std::string::npos) {
1268 command.swap(command_string);
1269 command_string.erase();
1271 command.assign(command_string, 1, end_quote_pos - 1);
1272 if (end_quote_pos + 1 < command_string.size())
1273 command_string.erase(0, command_string.find_first_not_of(
1274 k_white_space, end_quote_pos + 1));
1276 command_string.erase();
1279 const size_t first_space_pos =
1280 command_string.find_first_of(k_white_space);
1281 if (first_space_pos == std::string::npos) {
1282 command.swap(command_string);
1283 command_string.erase();
1285 command.assign(command_string, 0, first_space_pos);
1286 command_string.erase(0, command_string.find_first_not_of(
1287 k_white_space, first_space_pos));
1293 if (!command.empty()) {
1294 // actual commands can't start with '-' or '_'
1295 if (command[0] != '-' && command[0] != '_') {
1296 size_t pos = command.find_first_not_of(k_valid_command_chars);
1297 if (pos > 0 && pos != std::string::npos) {
1298 suffix.assign(command.begin() + pos, command.end());
1307 CommandObject *CommandInterpreter::BuildAliasResult(
1308 llvm::StringRef alias_name, std::string &raw_input_string,
1309 std::string &alias_result, CommandReturnObject &result) {
1310 CommandObject *alias_cmd_obj = nullptr;
1311 Args cmd_args(raw_input_string);
1312 alias_cmd_obj = GetCommandObject(alias_name);
1313 StreamString result_str;
1315 if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1316 alias_result.clear();
1317 return alias_cmd_obj;
1319 std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1320 ((CommandAlias *)alias_cmd_obj)->Desugar();
1321 OptionArgVectorSP option_arg_vector_sp = desugared.second;
1322 alias_cmd_obj = desugared.first.get();
1323 std::string alias_name_str = alias_name;
1324 if ((cmd_args.GetArgumentCount() == 0) ||
1325 (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0))
1326 cmd_args.Unshift(alias_name_str);
1328 result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
1330 if (!option_arg_vector_sp.get()) {
1331 alias_result = result_str.GetString();
1332 return alias_cmd_obj;
1334 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1339 for (const auto &entry : *option_arg_vector) {
1340 std::tie(option, value_type, value) = entry;
1341 if (option == "<argument>") {
1342 result_str.Printf(" %s", value.c_str());
1346 result_str.Printf(" %s", option.c_str());
1347 if (value_type == OptionParser::eNoArgument)
1350 if (value_type != OptionParser::eOptionalArgument)
1351 result_str.Printf(" ");
1352 int index = GetOptionArgumentPosition(value.c_str());
1354 result_str.Printf("%s", value.c_str());
1355 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1357 result.AppendErrorWithFormat("Not enough arguments provided; you "
1358 "need at least %d arguments to use "
1361 result.SetStatus(eReturnStatusFailed);
1364 size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1365 if (strpos != std::string::npos)
1366 raw_input_string = raw_input_string.erase(
1367 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1368 result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
1372 alias_result = result_str.GetString();
1373 return alias_cmd_obj;
1376 Error CommandInterpreter::PreprocessCommand(std::string &command) {
1377 // The command preprocessor needs to do things to the command
1378 // line before any parsing of arguments or anything else is done.
1379 // The only current stuff that gets preprocessed is anything enclosed
1380 // in backtick ('`') characters is evaluated as an expression and
1381 // the result of the expression must be a scalar that can be substituted
1382 // into the command. An example would be:
1383 // (lldb) memory read `$rsp + 20`
1384 Error error; // Error for any expressions that might not evaluate
1385 size_t start_backtick;
1387 while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1388 if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
1389 // The backtick was preceded by a '\' character, remove the slash
1390 // and don't treat the backtick as the start of an expression
1391 command.erase(start_backtick - 1, 1);
1392 // No need to add one to start_backtick since we just deleted a char
1393 pos = start_backtick;
1395 const size_t expr_content_start = start_backtick + 1;
1396 const size_t end_backtick = command.find('`', expr_content_start);
1397 if (end_backtick == std::string::npos)
1399 else if (end_backtick == expr_content_start) {
1400 // Empty expression (two backticks in a row)
1401 command.erase(start_backtick, 2);
1403 std::string expr_str(command, expr_content_start,
1404 end_backtick - expr_content_start);
1406 ExecutionContext exe_ctx(GetExecutionContext());
1407 Target *target = exe_ctx.GetTargetPtr();
1408 // Get a dummy target to allow for calculator mode while processing
1410 // This also helps break the infinite loop caused when target is null.
1412 target = m_debugger.GetDummyTarget();
1414 ValueObjectSP expr_result_valobj_sp;
1416 EvaluateExpressionOptions options;
1417 options.SetCoerceToId(false);
1418 options.SetUnwindOnError(true);
1419 options.SetIgnoreBreakpoints(true);
1420 options.SetKeepInMemory(false);
1421 options.SetTryAllThreads(true);
1422 options.SetTimeout(llvm::None);
1424 ExpressionResults expr_result = target->EvaluateExpression(
1425 expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp,
1428 if (expr_result == eExpressionCompleted) {
1430 if (expr_result_valobj_sp)
1431 expr_result_valobj_sp =
1432 expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1433 expr_result_valobj_sp->GetDynamicValueType(), true);
1434 if (expr_result_valobj_sp->ResolveValue(scalar)) {
1435 command.erase(start_backtick, end_backtick - start_backtick + 1);
1436 StreamString value_strm;
1437 const bool show_type = false;
1438 scalar.GetValue(&value_strm, show_type);
1439 size_t value_string_size = value_strm.GetSize();
1440 if (value_string_size) {
1441 command.insert(start_backtick, value_strm.GetString());
1442 pos = start_backtick + value_string_size;
1445 error.SetErrorStringWithFormat("expression value didn't result "
1446 "in a scalar value for the "
1451 error.SetErrorStringWithFormat("expression value didn't result "
1452 "in a scalar value for the "
1457 if (expr_result_valobj_sp)
1458 error = expr_result_valobj_sp->GetError();
1459 if (error.Success()) {
1461 switch (expr_result) {
1462 case eExpressionSetupError:
1463 error.SetErrorStringWithFormat(
1464 "expression setup error for the expression '%s'",
1467 case eExpressionParseError:
1468 error.SetErrorStringWithFormat(
1469 "expression parse error for the expression '%s'",
1472 case eExpressionResultUnavailable:
1473 error.SetErrorStringWithFormat(
1474 "expression error fetching result for the expression '%s'",
1477 case eExpressionCompleted:
1479 case eExpressionDiscarded:
1480 error.SetErrorStringWithFormat(
1481 "expression discarded for the expression '%s'",
1484 case eExpressionInterrupted:
1485 error.SetErrorStringWithFormat(
1486 "expression interrupted for the expression '%s'",
1489 case eExpressionHitBreakpoint:
1490 error.SetErrorStringWithFormat(
1491 "expression hit breakpoint for the expression '%s'",
1494 case eExpressionTimedOut:
1495 error.SetErrorStringWithFormat(
1496 "expression timed out for the expression '%s'",
1499 case eExpressionStoppedForDebug:
1500 error.SetErrorStringWithFormat("expression stop at entry point "
1501 "for debugging for the "
1517 bool CommandInterpreter::HandleCommand(const char *command_line,
1518 LazyBool lazy_add_to_history,
1519 CommandReturnObject &result,
1520 ExecutionContext *override_context,
1521 bool repeat_on_empty_command,
1522 bool no_context_switching)
1526 std::string command_string(command_line);
1527 std::string original_command_string(command_line);
1529 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
1530 llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
1534 log->Printf("Processing command: %s", command_line);
1536 Timer scoped_timer(LLVM_PRETTY_FUNCTION, "Handling command: %s.",
1539 if (!no_context_switching)
1540 UpdateExecutionContext(override_context);
1542 bool add_to_history;
1543 if (lazy_add_to_history == eLazyBoolCalculate)
1544 add_to_history = (m_command_source_depth == 0);
1546 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1548 bool empty_command = false;
1549 bool comment_command = false;
1550 if (command_string.empty())
1551 empty_command = true;
1553 const char *k_space_characters = "\t\n\v\f\r ";
1555 size_t non_space = command_string.find_first_not_of(k_space_characters);
1556 // Check for empty line or comment line (lines whose first
1557 // non-space character is the comment character for this interpreter)
1558 if (non_space == std::string::npos)
1559 empty_command = true;
1560 else if (command_string[non_space] == m_comment_char)
1561 comment_command = true;
1562 else if (command_string[non_space] == CommandHistory::g_repeat_char) {
1563 llvm::StringRef search_str(command_string);
1564 search_str = search_str.drop_front(non_space);
1565 if (auto hist_str = m_command_history.FindString(search_str)) {
1566 add_to_history = false;
1567 command_string = *hist_str;
1568 original_command_string = *hist_str;
1570 result.AppendErrorWithFormat("Could not find entry: %s in history",
1571 command_string.c_str());
1572 result.SetStatus(eReturnStatusFailed);
1578 if (empty_command) {
1579 if (repeat_on_empty_command) {
1580 if (m_command_history.IsEmpty()) {
1581 result.AppendError("empty command");
1582 result.SetStatus(eReturnStatusFailed);
1585 command_line = m_repeat_command.c_str();
1586 command_string = command_line;
1587 original_command_string = command_line;
1588 if (m_repeat_command.empty()) {
1589 result.AppendErrorWithFormat("No auto repeat.\n");
1590 result.SetStatus(eReturnStatusFailed);
1594 add_to_history = false;
1596 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1599 } else if (comment_command) {
1600 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1604 Error error(PreprocessCommand(command_string));
1607 result.AppendError(error.AsCString());
1608 result.SetStatus(eReturnStatusFailed);
1614 // Before we do ANY kind of argument processing, we need to figure out what
1615 // the real/final command object is for the specified command. This gets
1616 // complicated by the fact that the user could have specified an alias, and,
1617 // in translating the alias, there may also be command options and/or even
1618 // data (including raw text strings) that need to be found and inserted into
1619 // the command line as part of the translation. So this first step is plain
1620 // look-up and replacement, resulting in:
1621 // 1. the command object whose Execute method will actually be called
1622 // 2. a revised command string, with all substitutions and replacements
1624 // From 1 above, we can determine whether the Execute function wants raw
1627 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1629 // Although the user may have abbreviated the command, the command_string now
1630 // has the command expanded to the full name. For example, if the input
1631 // was "br s -n main", command_string is now "breakpoint set -n main".
1633 llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1634 log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
1635 log->Printf("HandleCommand, (revised) command_string: '%s'",
1636 command_string.c_str());
1637 const bool wants_raw_input =
1638 (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1639 log->Printf("HandleCommand, wants_raw_input:'%s'",
1640 wants_raw_input ? "True" : "False");
1644 // Take care of things like setting up the history command & calling the
1645 // appropriate Execute method on the
1646 // CommandObject, with the appropriate arguments.
1648 if (cmd_obj != nullptr) {
1649 if (add_to_history) {
1650 Args command_args(command_string);
1651 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1652 if (repeat_command != nullptr)
1653 m_repeat_command.assign(repeat_command);
1655 m_repeat_command.assign(original_command_string);
1657 m_command_history.AppendString(original_command_string);
1660 std::string remainder;
1661 const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
1662 if (actual_cmd_name_len < command_string.length())
1663 remainder = command_string.substr(actual_cmd_name_len);
1665 // Remove any initial spaces
1666 size_t pos = remainder.find_first_not_of(k_white_space);
1667 if (pos != 0 && pos != std::string::npos)
1668 remainder.erase(0, pos);
1672 "HandleCommand, command line after removing command name(s): '%s'",
1675 cmd_obj->Execute(remainder.c_str(), result);
1677 // We didn't find the first command object, so complete the first argument.
1678 Args command_args(command_string);
1681 int cursor_index = 0;
1682 int cursor_char_position = strlen(command_args.GetArgumentAtIndex(0));
1684 num_matches = HandleCompletionMatches(command_args, cursor_index,
1685 cursor_char_position, 0, -1,
1686 word_complete, matches);
1688 if (num_matches > 0) {
1689 std::string error_msg;
1690 error_msg.assign("ambiguous command '");
1691 error_msg.append(command_args.GetArgumentAtIndex(0));
1692 error_msg.append("'.");
1694 error_msg.append(" Possible completions:");
1695 for (int i = 0; i < num_matches; i++) {
1696 error_msg.append("\n\t");
1697 error_msg.append(matches.GetStringAtIndex(i));
1699 error_msg.append("\n");
1700 result.AppendRawError(error_msg.c_str());
1702 result.AppendErrorWithFormat("Unrecognized command '%s'.\n",
1703 command_args.GetArgumentAtIndex(0));
1705 result.SetStatus(eReturnStatusFailed);
1709 log->Printf("HandleCommand, command %s",
1710 (result.Succeeded() ? "succeeded" : "did not succeed"));
1712 return result.Succeeded();
1715 int CommandInterpreter::HandleCompletionMatches(
1716 Args &parsed_line, int &cursor_index, int &cursor_char_position,
1717 int match_start_point, int max_return_elements, bool &word_complete,
1718 StringList &matches) {
1719 int num_command_matches = 0;
1720 bool look_for_subcommand = false;
1722 // For any of the command completions a unique match will be a complete word.
1723 word_complete = true;
1725 if (cursor_index == -1) {
1726 // We got nothing on the command line, so return the list of commands
1727 bool include_aliases = true;
1728 num_command_matches =
1729 GetCommandNamesMatchingPartialString("", include_aliases, matches);
1730 } else if (cursor_index == 0) {
1731 // The cursor is in the first argument, so just do a lookup in the
1733 CommandObject *cmd_obj =
1734 GetCommandObject(parsed_line.GetArgumentAtIndex(0), &matches);
1735 num_command_matches = matches.GetSize();
1737 if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1738 matches.GetStringAtIndex(0) != nullptr &&
1739 strcmp(parsed_line.GetArgumentAtIndex(0),
1740 matches.GetStringAtIndex(0)) == 0) {
1741 if (parsed_line.GetArgumentCount() == 1) {
1742 word_complete = true;
1744 look_for_subcommand = true;
1745 num_command_matches = 0;
1746 matches.DeleteStringAtIndex(0);
1747 parsed_line.AppendArgument(llvm::StringRef());
1749 cursor_char_position = 0;
1754 if (cursor_index > 0 || look_for_subcommand) {
1755 // We are completing further on into a commands arguments, so find the
1756 // command and tell it
1757 // to complete the command.
1758 // First see if there is a matching initial command:
1759 CommandObject *command_object =
1760 GetCommandObject(parsed_line.GetArgumentAtIndex(0));
1761 if (command_object == nullptr) {
1764 parsed_line.Shift();
1766 num_command_matches = command_object->HandleCompletion(
1767 parsed_line, cursor_index, cursor_char_position, match_start_point,
1768 max_return_elements, word_complete, matches);
1772 return num_command_matches;
1775 int CommandInterpreter::HandleCompletion(
1776 const char *current_line, const char *cursor, const char *last_char,
1777 int match_start_point, int max_return_elements, StringList &matches) {
1778 // We parse the argument up to the cursor, so the last argument in parsed_line
1780 // the one containing the cursor, and the cursor is after the last character.
1782 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
1783 Args partial_parsed_line(
1784 llvm::StringRef(current_line, cursor - current_line));
1786 // Don't complete comments, and if the line we are completing is just the
1787 // history repeat character,
1788 // substitute the appropriate history line.
1789 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1791 if (first_arg[0] == m_comment_char)
1793 else if (first_arg[0] == CommandHistory::g_repeat_char) {
1794 if (auto hist_str = m_command_history.FindString(first_arg)) {
1796 matches.InsertStringAtIndex(0, *hist_str);
1803 int num_args = partial_parsed_line.GetArgumentCount();
1804 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1805 int cursor_char_position;
1807 if (cursor_index == -1)
1808 cursor_char_position = 0;
1810 cursor_char_position =
1811 strlen(partial_parsed_line.GetArgumentAtIndex(cursor_index));
1813 if (cursor > current_line && cursor[-1] == ' ') {
1814 // We are just after a space. If we are in an argument, then we will
1816 // parsing, but if we are between arguments, then we have to complete
1817 // whatever the next
1818 // element would be.
1819 // We can distinguish the two cases because if we are in an argument (e.g.
1820 // because the space is
1821 // protected by a quote) then the space will also be in the parsed
1824 const char *current_elem =
1825 partial_parsed_line.GetArgumentAtIndex(cursor_index);
1826 if (cursor_char_position == 0 ||
1827 current_elem[cursor_char_position - 1] != ' ') {
1828 parsed_line.InsertArgumentAtIndex(cursor_index + 1, llvm::StringRef(),
1831 cursor_char_position = 0;
1835 int num_command_matches;
1839 // Only max_return_elements == -1 is supported at present:
1840 assert(max_return_elements == -1);
1842 num_command_matches = HandleCompletionMatches(
1843 parsed_line, cursor_index, cursor_char_position, match_start_point,
1844 max_return_elements, word_complete, matches);
1846 if (num_command_matches <= 0)
1847 return num_command_matches;
1849 if (num_args == 0) {
1850 // If we got an empty string, insert nothing.
1851 matches.InsertStringAtIndex(0, "");
1853 // Now figure out if there is a common substring, and if so put that in
1854 // element 0, otherwise
1855 // put an empty string in element 0.
1856 std::string command_partial_str;
1857 if (cursor_index >= 0)
1858 command_partial_str =
1859 parsed_line[cursor_index].ref.take_front(cursor_char_position);
1861 std::string common_prefix;
1862 matches.LongestCommonPrefix(common_prefix);
1863 const size_t partial_name_len = command_partial_str.size();
1864 common_prefix.erase(0, partial_name_len);
1866 // If we matched a unique single command, add a space...
1867 // Only do this if the completer told us this was a complete word,
1869 if (num_command_matches == 1 && word_complete) {
1870 char quote_char = parsed_line[cursor_index].quote;
1872 Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1873 if (quote_char != '\0')
1874 common_prefix.push_back(quote_char);
1875 common_prefix.push_back(' ');
1877 matches.InsertStringAtIndex(0, common_prefix.c_str());
1879 return num_command_matches;
1882 CommandInterpreter::~CommandInterpreter() {}
1884 void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
1885 EventSP prompt_change_event_sp(
1886 new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1888 BroadcastEvent(prompt_change_event_sp);
1889 if (m_command_io_handler_sp)
1890 m_command_io_handler_sp->SetPrompt(new_prompt);
1893 bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
1894 // Check AutoConfirm first:
1895 if (m_debugger.GetAutoConfirm())
1896 return default_answer;
1898 IOHandlerConfirm *confirm =
1899 new IOHandlerConfirm(m_debugger, message, default_answer);
1900 IOHandlerSP io_handler_sp(confirm);
1901 m_debugger.RunIOHandler(io_handler_sp);
1902 return confirm->GetResponse();
1905 const CommandAlias *
1906 CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
1907 OptionArgVectorSP ret_val;
1909 auto pos = m_alias_dict.find(alias_name);
1910 if (pos != m_alias_dict.end())
1911 return (CommandAlias *)pos->second.get();
1916 bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
1918 bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
1920 bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
1922 bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
1924 void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1925 const char *alias_name,
1927 std::string &raw_input_string,
1928 CommandReturnObject &result) {
1929 OptionArgVectorSP option_arg_vector_sp =
1930 GetAlias(alias_name)->GetOptionArguments();
1932 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1934 // Make sure that the alias name is the 0th element in cmd_args
1935 std::string alias_name_str = alias_name;
1936 if (alias_name_str.compare(cmd_args.GetArgumentAtIndex(0)) != 0)
1937 cmd_args.Unshift(alias_name_str);
1939 Args new_args(alias_cmd_obj->GetCommandName());
1940 if (new_args.GetArgumentCount() == 2)
1943 if (option_arg_vector_sp.get()) {
1944 if (wants_raw_input) {
1945 // We have a command that both has command options and takes raw input.
1946 // Make *sure* it has a
1947 // " -- " in the right place in the raw_input_string.
1948 size_t pos = raw_input_string.find(" -- ");
1949 if (pos == std::string::npos) {
1950 // None found; assume it goes at the beginning of the raw input string
1951 raw_input_string.insert(0, " -- ");
1955 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1956 const size_t old_size = cmd_args.GetArgumentCount();
1957 std::vector<bool> used(old_size + 1, false);
1964 for (const auto &option_entry : *option_arg_vector) {
1965 std::tie(option, value_type, value) = option_entry;
1966 if (option == "<argument>") {
1967 if (!wants_raw_input || (value != "--")) {
1968 // Since we inserted this above, make sure we don't insert it twice
1969 new_args.AppendArgument(value);
1974 if (value_type != OptionParser::eOptionalArgument)
1975 new_args.AppendArgument(option);
1977 if (value == "<no-argument>")
1980 int index = GetOptionArgumentPosition(value.c_str());
1982 // value was NOT a positional argument; must be a real value
1983 if (value_type != OptionParser::eOptionalArgument)
1984 new_args.AppendArgument(value);
1987 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
1989 new_args.AppendArgument(llvm::StringRef(buffer));
1992 } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1993 result.AppendErrorWithFormat("Not enough arguments provided; you "
1994 "need at least %d arguments to use "
1997 result.SetStatus(eReturnStatusFailed);
2000 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2002 raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2003 if (strpos != std::string::npos) {
2004 raw_input_string = raw_input_string.erase(
2005 strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2008 if (value_type != OptionParser::eOptionalArgument)
2009 new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2012 ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2013 cmd_args.GetArgumentAtIndex(index));
2014 new_args.AppendArgument(buffer);
2020 for (auto entry : llvm::enumerate(cmd_args.entries())) {
2021 if (!used[entry.Index] && !wants_raw_input)
2022 new_args.AppendArgument(entry.Value.ref);
2026 cmd_args.SetArguments(new_args.GetArgumentCount(),
2027 new_args.GetConstArgumentVector());
2029 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2030 // This alias was not created with any options; nothing further needs to be
2031 // done, unless it is a command that
2032 // wants raw input, in which case we need to clear the rest of the data from
2033 // cmd_args, since its in the raw
2035 if (wants_raw_input) {
2037 cmd_args.SetArguments(new_args.GetArgumentCount(),
2038 new_args.GetConstArgumentVector());
2043 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2047 int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2048 int position = 0; // Any string that isn't an argument position, i.e. '%'
2049 // followed by an integer, gets a position
2052 const char *cptr = in_string;
2054 // Does it start with '%'
2055 if (cptr[0] == '%') {
2058 // Is the rest of it entirely digits?
2059 if (isdigit(cptr[0])) {
2060 const char *start = cptr;
2061 while (isdigit(cptr[0]))
2064 // We've gotten to the end of the digits; are we at the end of the string?
2065 if (cptr[0] == '\0')
2066 position = atoi(start);
2073 void CommandInterpreter::SourceInitFile(bool in_cwd,
2074 CommandReturnObject &result) {
2077 ExecutionContext exe_ctx(GetExecutionContext());
2078 Target *target = exe_ctx.GetTargetPtr();
2080 // In the current working directory we don't load any program specific
2081 // .lldbinit files, we only look for a ".lldbinit" file.
2082 if (m_skip_lldbinit_files)
2085 LoadCWDlldbinitFile should_load =
2086 target->TargetProperties::GetLoadCWDlldbinitFile();
2087 if (should_load == eLoadCWDlldbinitWarn) {
2088 FileSpec dot_lldb(".lldbinit", true);
2089 llvm::SmallString<64> home_dir_path;
2090 llvm::sys::path::home_directory(home_dir_path);
2091 FileSpec homedir_dot_lldb(home_dir_path.c_str(), false);
2092 homedir_dot_lldb.AppendPathComponent(".lldbinit");
2093 homedir_dot_lldb.ResolvePath();
2094 if (dot_lldb.Exists() &&
2095 dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2096 result.AppendErrorWithFormat(
2097 "There is a .lldbinit file in the current directory which is not "
2099 "To silence this warning without sourcing in the local "
2101 "add the following to the lldbinit file in your home directory:\n"
2102 " settings set target.load-cwd-lldbinit false\n"
2103 "To allow lldb to source .lldbinit files in the current working "
2105 "set the value of this variable to true. Only do so if you "
2107 "accept the security risk.");
2108 result.SetStatus(eReturnStatusFailed);
2111 } else if (should_load == eLoadCWDlldbinitTrue) {
2112 init_file.SetFile("./.lldbinit", true);
2116 // If we aren't looking in the current working directory we are looking
2117 // in the home directory. We will first see if there is an application
2118 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2119 // "-" and the name of the program. If this file doesn't exist, we fall
2120 // back to just the "~/.lldbinit" file. We also obey any requests to not
2121 // load the init files.
2122 llvm::SmallString<64> home_dir_path;
2123 llvm::sys::path::home_directory(home_dir_path);
2124 FileSpec profilePath(home_dir_path.c_str(), false);
2125 profilePath.AppendPathComponent(".lldbinit");
2126 std::string init_file_path = profilePath.GetPath();
2128 if (m_skip_app_init_files == false) {
2129 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2130 const char *program_name = program_file_spec.GetFilename().AsCString();
2133 char program_init_file_name[PATH_MAX];
2134 ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2135 "%s-%s", init_file_path.c_str(), program_name);
2136 init_file.SetFile(program_init_file_name, true);
2137 if (!init_file.Exists())
2142 if (!init_file && !m_skip_lldbinit_files)
2143 init_file.SetFile(init_file_path, false);
2146 // If the file exists, tell HandleCommand to 'source' it; this will do the
2147 // actual broadcasting
2148 // of the commands back to any appropriate listener (see
2149 // CommandObjectSource::Execute for more details).
2151 if (init_file.Exists()) {
2152 const bool saved_batch = SetBatchCommandMode(true);
2153 CommandInterpreterRunOptions options;
2154 options.SetSilent(true);
2155 options.SetStopOnError(false);
2156 options.SetStopOnContinue(true);
2158 HandleCommandsFromFile(init_file,
2159 nullptr, // Execution context
2161 SetBatchCommandMode(saved_batch);
2163 // nothing to be done if the file doesn't exist
2164 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2168 const char *CommandInterpreter::GetCommandPrefix() {
2169 const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2170 return prefix == NULL ? "" : prefix;
2173 PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2174 PlatformSP platform_sp;
2175 if (prefer_target_platform) {
2176 ExecutionContext exe_ctx(GetExecutionContext());
2177 Target *target = exe_ctx.GetTargetPtr();
2179 platform_sp = target->GetPlatform();
2183 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2187 void CommandInterpreter::HandleCommands(const StringList &commands,
2188 ExecutionContext *override_context,
2189 CommandInterpreterRunOptions &options,
2190 CommandReturnObject &result) {
2191 size_t num_lines = commands.GetSize();
2193 // If we are going to continue past a "continue" then we need to run the
2194 // commands synchronously.
2195 // Make sure you reset this value anywhere you return from the function.
2197 bool old_async_execution = m_debugger.GetAsyncExecution();
2199 // If we've been given an execution context, set it at the start, but don't
2200 // keep resetting it or we will
2201 // cause series of commands that change the context, then do an operation that
2202 // relies on that context to fail.
2204 if (override_context != nullptr)
2205 UpdateExecutionContext(override_context);
2207 if (!options.GetStopOnContinue()) {
2208 m_debugger.SetAsyncExecution(false);
2211 for (size_t idx = 0; idx < num_lines; idx++) {
2212 const char *cmd = commands.GetStringAtIndex(idx);
2216 if (options.GetEchoCommands()) {
2217 // TODO: Add Stream support.
2218 result.AppendMessageWithFormat("%s %s\n",
2219 m_debugger.GetPrompt().str().c_str(), cmd);
2222 CommandReturnObject tmp_result;
2223 // If override_context is not NULL, pass no_context_switching = true for
2224 // HandleCommand() since we updated our context already.
2226 // We might call into a regex or alias command, in which case the
2227 // add_to_history will get lost. This
2228 // m_command_source_depth dingus is the way we turn off adding to the
2229 // history in that case, so set it up here.
2230 if (!options.GetAddToHistory())
2231 m_command_source_depth++;
2233 HandleCommand(cmd, options.m_add_to_history, tmp_result,
2234 nullptr, /* override_context */
2235 true, /* repeat_on_empty_command */
2236 override_context != nullptr /* no_context_switching */);
2237 if (!options.GetAddToHistory())
2238 m_command_source_depth--;
2240 if (options.GetPrintResults()) {
2241 if (tmp_result.Succeeded())
2242 result.AppendMessage(tmp_result.GetOutputData());
2245 if (!success || !tmp_result.Succeeded()) {
2246 llvm::StringRef error_msg = tmp_result.GetErrorData();
2247 if (error_msg.empty())
2248 error_msg = "<unknown error>.\n";
2249 if (options.GetStopOnError()) {
2250 result.AppendErrorWithFormat(
2251 "Aborting reading of commands after command #%" PRIu64
2252 ": '%s' failed with %s",
2253 (uint64_t)idx, cmd, error_msg.str().c_str());
2254 result.SetStatus(eReturnStatusFailed);
2255 m_debugger.SetAsyncExecution(old_async_execution);
2257 } else if (options.GetPrintResults()) {
2258 result.AppendMessageWithFormat(
2259 "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2260 error_msg.str().c_str());
2264 if (result.GetImmediateOutputStream())
2265 result.GetImmediateOutputStream()->Flush();
2267 if (result.GetImmediateErrorStream())
2268 result.GetImmediateErrorStream()->Flush();
2270 // N.B. Can't depend on DidChangeProcessState, because the state coming into
2271 // the command execution
2272 // could be running (for instance in Breakpoint Commands.
2273 // So we check the return value to see if it is has running in it.
2274 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2275 (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2276 if (options.GetStopOnContinue()) {
2277 // If we caused the target to proceed, and we're going to stop in that
2279 // status in our real result before returning. This is an error if the
2280 // continue was not the
2281 // last command in the set of commands to be run.
2282 if (idx != num_lines - 1)
2283 result.AppendErrorWithFormat(
2284 "Aborting reading of commands after command #%" PRIu64
2285 ": '%s' continued the target.\n",
2286 (uint64_t)idx + 1, cmd);
2288 result.AppendMessageWithFormat("Command #%" PRIu64
2289 " '%s' continued the target.\n",
2290 (uint64_t)idx + 1, cmd);
2292 result.SetStatus(tmp_result.GetStatus());
2293 m_debugger.SetAsyncExecution(old_async_execution);
2299 // Also check for "stop on crash here:
2300 bool should_stop = false;
2301 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2302 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2304 ProcessSP process_sp(target_sp->GetProcessSP());
2306 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2307 StopReason reason = thread_sp->GetStopReason();
2308 if (reason == eStopReasonSignal || reason == eStopReasonException ||
2309 reason == eStopReasonInstrumentation) {
2317 if (idx != num_lines - 1)
2318 result.AppendErrorWithFormat(
2319 "Aborting reading of commands after command #%" PRIu64
2320 ": '%s' stopped with a signal or exception.\n",
2321 (uint64_t)idx + 1, cmd);
2323 result.AppendMessageWithFormat(
2324 "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2325 (uint64_t)idx + 1, cmd);
2327 result.SetStatus(tmp_result.GetStatus());
2328 m_debugger.SetAsyncExecution(old_async_execution);
2335 result.SetStatus(eReturnStatusSuccessFinishResult);
2336 m_debugger.SetAsyncExecution(old_async_execution);
2341 // Make flags that we can pass into the IOHandler so our delegates can do the
2344 eHandleCommandFlagStopOnContinue = (1u << 0),
2345 eHandleCommandFlagStopOnError = (1u << 1),
2346 eHandleCommandFlagEchoCommand = (1u << 2),
2347 eHandleCommandFlagPrintResult = (1u << 3),
2348 eHandleCommandFlagStopOnCrash = (1u << 4)
2351 void CommandInterpreter::HandleCommandsFromFile(
2352 FileSpec &cmd_file, ExecutionContext *context,
2353 CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2354 if (cmd_file.Exists()) {
2355 StreamFileSP input_file_sp(new StreamFile());
2357 std::string cmd_file_path = cmd_file.GetPath();
2358 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2359 File::eOpenOptionRead);
2361 if (error.Success()) {
2362 Debugger &debugger = GetDebugger();
2366 if (options.m_stop_on_continue == eLazyBoolCalculate) {
2367 if (m_command_source_flags.empty()) {
2368 // Stop on continue by default
2369 flags |= eHandleCommandFlagStopOnContinue;
2370 } else if (m_command_source_flags.back() &
2371 eHandleCommandFlagStopOnContinue) {
2372 flags |= eHandleCommandFlagStopOnContinue;
2374 } else if (options.m_stop_on_continue == eLazyBoolYes) {
2375 flags |= eHandleCommandFlagStopOnContinue;
2378 if (options.m_stop_on_error == eLazyBoolCalculate) {
2379 if (m_command_source_flags.empty()) {
2380 if (GetStopCmdSourceOnError())
2381 flags |= eHandleCommandFlagStopOnError;
2382 } else if (m_command_source_flags.back() &
2383 eHandleCommandFlagStopOnError) {
2384 flags |= eHandleCommandFlagStopOnError;
2386 } else if (options.m_stop_on_error == eLazyBoolYes) {
2387 flags |= eHandleCommandFlagStopOnError;
2390 if (options.GetStopOnCrash()) {
2391 if (m_command_source_flags.empty()) {
2392 // Echo command by default
2393 flags |= eHandleCommandFlagStopOnCrash;
2394 } else if (m_command_source_flags.back() &
2395 eHandleCommandFlagStopOnCrash) {
2396 flags |= eHandleCommandFlagStopOnCrash;
2400 if (options.m_echo_commands == eLazyBoolCalculate) {
2401 if (m_command_source_flags.empty()) {
2402 // Echo command by default
2403 flags |= eHandleCommandFlagEchoCommand;
2404 } else if (m_command_source_flags.back() &
2405 eHandleCommandFlagEchoCommand) {
2406 flags |= eHandleCommandFlagEchoCommand;
2408 } else if (options.m_echo_commands == eLazyBoolYes) {
2409 flags |= eHandleCommandFlagEchoCommand;
2412 if (options.m_print_results == eLazyBoolCalculate) {
2413 if (m_command_source_flags.empty()) {
2414 // Print output by default
2415 flags |= eHandleCommandFlagPrintResult;
2416 } else if (m_command_source_flags.back() &
2417 eHandleCommandFlagPrintResult) {
2418 flags |= eHandleCommandFlagPrintResult;
2420 } else if (options.m_print_results == eLazyBoolYes) {
2421 flags |= eHandleCommandFlagPrintResult;
2424 if (flags & eHandleCommandFlagPrintResult) {
2425 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2426 cmd_file_path.c_str());
2429 // Used for inheriting the right settings when "command source" might have
2430 // nested "command source" commands
2431 lldb::StreamFileSP empty_stream_sp;
2432 m_command_source_flags.push_back(flags);
2433 IOHandlerSP io_handler_sp(new IOHandlerEditline(
2434 debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2435 empty_stream_sp, // Pass in an empty stream so we inherit the top
2436 // input reader output stream
2437 empty_stream_sp, // Pass in an empty stream so we inherit the top
2438 // input reader error stream
2440 nullptr, // Pass in NULL for "editline_name" so no history is saved,
2442 debugger.GetPrompt(), llvm::StringRef(),
2443 false, // Not multi-line
2444 debugger.GetUseColor(), 0, *this));
2445 const bool old_async_execution = debugger.GetAsyncExecution();
2447 // Set synchronous execution if we are not stopping on continue
2448 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2449 debugger.SetAsyncExecution(false);
2451 m_command_source_depth++;
2453 debugger.RunIOHandler(io_handler_sp);
2454 if (!m_command_source_flags.empty())
2455 m_command_source_flags.pop_back();
2456 m_command_source_depth--;
2457 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2458 debugger.SetAsyncExecution(old_async_execution);
2460 result.AppendErrorWithFormat(
2461 "error: an error occurred read file '%s': %s\n",
2462 cmd_file_path.c_str(), error.AsCString());
2463 result.SetStatus(eReturnStatusFailed);
2467 result.AppendErrorWithFormat(
2468 "Error reading commands from file %s - file not found.\n",
2469 cmd_file.GetFilename().AsCString("<Unknown>"));
2470 result.SetStatus(eReturnStatusFailed);
2475 ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
2476 std::lock_guard<std::mutex> locker(m_script_interpreter_mutex);
2477 if (!m_script_interpreter_sp) {
2480 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2481 m_script_interpreter_sp =
2482 PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2484 return m_script_interpreter_sp.get();
2487 bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2489 void CommandInterpreter::SetSynchronous(bool value) {
2490 m_synchronous_execution = value;
2493 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2494 llvm::StringRef prefix,
2495 llvm::StringRef help_text) {
2496 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2498 size_t line_width_max = max_columns - prefix.size();
2499 if (line_width_max < 16)
2500 line_width_max = help_text.size() + prefix.size();
2502 strm.IndentMore(prefix.size());
2503 bool prefixed_yet = false;
2504 while (!help_text.empty()) {
2505 // Prefix the first line, indent subsequent lines to line up
2506 if (!prefixed_yet) {
2508 prefixed_yet = true;
2512 // Never print more than the maximum on one line.
2513 llvm::StringRef this_line = help_text.substr(0, line_width_max);
2515 // Always break on an explicit newline.
2516 std::size_t first_newline = this_line.find_first_of("\n");
2518 // Don't break on space/tab unless the text is too long to fit on one line.
2519 std::size_t last_space = llvm::StringRef::npos;
2520 if (this_line.size() != help_text.size())
2521 last_space = this_line.find_last_of(" \t");
2523 // Break at whichever condition triggered first.
2524 this_line = this_line.substr(0, std::min(first_newline, last_space));
2525 strm.PutCString(this_line);
2528 // Remove whitespace / newlines after breaking.
2529 help_text = help_text.drop_front(this_line.size()).ltrim();
2531 strm.IndentLess(prefix.size());
2534 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2535 llvm::StringRef word_text,
2536 llvm::StringRef separator,
2537 llvm::StringRef help_text,
2538 size_t max_word_len) {
2539 StreamString prefix_stream;
2540 prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2541 (int)separator.size(), separator.data());
2542 OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2545 LLVM_ATTRIBUTE_ALWAYS_INLINE
2546 static size_t nextWordLength(llvm::StringRef S) {
2547 size_t pos = S.find_first_of(' ');
2548 if (pos == llvm::StringRef::npos)
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 while (!text.empty()) {
2572 if (text.front() == '\n' ||
2573 (text.front() == ' ' && nextWordLength(text.ltrim(' ')) < chars_left)) {
2576 chars_left = max_columns - indent_size;
2577 if (text.front() == '\n')
2578 text = text.drop_front();
2580 text = text.ltrim(' ');
2582 strm.PutChar(text.front());
2584 text = text.drop_front();
2589 strm.IndentLess(indent_size);
2592 void CommandInterpreter::FindCommandsForApropos(
2593 llvm::StringRef search_word, StringList &commands_found,
2594 StringList &commands_help, CommandObject::CommandMap &command_map) {
2595 CommandObject::CommandMap::const_iterator pos;
2597 for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
2598 llvm::StringRef command_name = pos->first;
2599 CommandObject *cmd_obj = pos->second.get();
2601 const bool search_short_help = true;
2602 const bool search_long_help = false;
2603 const bool search_syntax = false;
2604 const bool search_options = false;
2605 if (command_name.contains_lower(search_word) ||
2606 cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2607 search_long_help, search_syntax,
2609 commands_found.AppendString(cmd_obj->GetCommandName());
2610 commands_help.AppendString(cmd_obj->GetHelp());
2613 if (cmd_obj->IsMultiwordObject()) {
2614 CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2615 FindCommandsForApropos(search_word, commands_found, commands_help,
2616 cmd_multiword->GetSubcommandDictionary());
2621 void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
2622 StringList &commands_found,
2623 StringList &commands_help,
2624 bool search_builtin_commands,
2625 bool search_user_commands,
2626 bool search_alias_commands) {
2627 CommandObject::CommandMap::const_iterator pos;
2629 if (search_builtin_commands)
2630 FindCommandsForApropos(search_word, commands_found, commands_help,
2633 if (search_user_commands)
2634 FindCommandsForApropos(search_word, commands_found, commands_help,
2637 if (search_alias_commands)
2638 FindCommandsForApropos(search_word, commands_found, commands_help,
2642 void CommandInterpreter::UpdateExecutionContext(
2643 ExecutionContext *override_context) {
2644 if (override_context != nullptr) {
2645 m_exe_ctx_ref = *override_context;
2647 const bool adopt_selected = true;
2648 m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2653 size_t CommandInterpreter::GetProcessOutput() {
2654 // The process has stuff waiting for stderr; get it and write it out to the
2655 // appropriate place.
2656 char stdio_buffer[1024];
2658 size_t total_bytes = 0;
2660 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2662 ProcessSP process_sp(target_sp->GetProcessSP());
2664 while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2666 size_t bytes_written = len;
2667 m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2670 while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2672 size_t bytes_written = len;
2673 m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2681 void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2682 std::string &line) {
2683 const bool is_interactive = io_handler.GetIsInteractive();
2684 if (is_interactive == false) {
2685 // When we are not interactive, don't execute blank lines. This will happen
2686 // sourcing a commands file. We don't want blank lines to repeat the
2688 // command and cause any errors to occur (like redefining an alias, get an
2690 // and stop parsing the commands file).
2694 // When using a non-interactive file handle (like when sourcing commands
2696 // we need to echo the command out so we don't just see the command output
2699 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2700 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2704 lldb_private::CommandReturnObject result;
2705 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2707 // Now emit the command output text from the command we just executed
2708 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2709 // Display any STDOUT/STDERR _prior_ to emitting the command result text
2712 if (!result.GetImmediateOutputStream()) {
2713 llvm::StringRef output = result.GetOutputData();
2714 if (!output.empty())
2715 io_handler.GetOutputStreamFile()->PutCString(output);
2718 // Now emit the command error text from the command we just executed
2719 if (!result.GetImmediateErrorStream()) {
2720 llvm::StringRef error = result.GetErrorData();
2722 io_handler.GetErrorStreamFile()->PutCString(error);
2726 switch (result.GetStatus()) {
2727 case eReturnStatusInvalid:
2728 case eReturnStatusSuccessFinishNoResult:
2729 case eReturnStatusSuccessFinishResult:
2730 case eReturnStatusStarted:
2733 case eReturnStatusSuccessContinuingNoResult:
2734 case eReturnStatusSuccessContinuingResult:
2735 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2736 io_handler.SetIsDone(true);
2739 case eReturnStatusFailed:
2741 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2742 io_handler.SetIsDone(true);
2745 case eReturnStatusQuit:
2746 m_quit_requested = true;
2747 io_handler.SetIsDone(true);
2751 // Finally, if we're going to stop on crash, check that here:
2752 if (!m_quit_requested && result.GetDidChangeProcessState() &&
2753 io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2754 bool should_stop = false;
2755 TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2757 ProcessSP process_sp(target_sp->GetProcessSP());
2759 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2760 StopReason reason = thread_sp->GetStopReason();
2761 if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2762 reason == eStopReasonInstrumentation) &&
2763 !result.GetAbnormalStopWasExpected()) {
2771 io_handler.SetIsDone(true);
2772 m_stopped_for_crash = true;
2777 bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2778 ExecutionContext exe_ctx(GetExecutionContext());
2779 Process *process = exe_ctx.GetProcessPtr();
2782 StateType state = process->GetState();
2783 if (StateIsRunningState(state)) {
2785 return true; // Don't do any updating when we are running
2789 ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2790 if (script_interpreter) {
2791 if (script_interpreter->Interrupt())
2797 void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2798 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2800 Debugger &debugger = GetDebugger();
2801 IOHandlerSP io_handler_sp(
2802 new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2803 "lldb", // Name of input reader for history
2804 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2805 llvm::StringRef(), // Continuation prompt
2806 true, // Get multiple lines
2807 debugger.GetUseColor(),
2808 0, // Don't show line numbers
2809 delegate)); // IOHandlerDelegate
2811 if (io_handler_sp) {
2812 io_handler_sp->SetUserData(baton);
2814 debugger.PushIOHandler(io_handler_sp);
2816 debugger.RunIOHandler(io_handler_sp);
2820 void CommandInterpreter::GetPythonCommandsFromIOHandler(
2821 const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2823 Debugger &debugger = GetDebugger();
2824 IOHandlerSP io_handler_sp(
2825 new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2826 "lldb-python", // Name of input reader for history
2827 llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2828 llvm::StringRef(), // Continuation prompt
2829 true, // Get multiple lines
2830 debugger.GetUseColor(),
2831 0, // Don't show line numbers
2832 delegate)); // IOHandlerDelegate
2834 if (io_handler_sp) {
2835 io_handler_sp->SetUserData(baton);
2837 debugger.PushIOHandler(io_handler_sp);
2839 debugger.RunIOHandler(io_handler_sp);
2843 bool CommandInterpreter::IsActive() {
2844 return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2848 CommandInterpreter::GetIOHandler(bool force_create,
2849 CommandInterpreterRunOptions *options) {
2850 // Always re-create the IOHandlerEditline in case the input
2851 // changed. The old instance might have had a non-interactive
2852 // input and now it does or vice versa.
2853 if (force_create || !m_command_io_handler_sp) {
2854 // Always re-create the IOHandlerEditline in case the input
2855 // changed. The old instance might have had a non-interactive
2856 // input and now it does or vice versa.
2860 if (options->m_stop_on_continue == eLazyBoolYes)
2861 flags |= eHandleCommandFlagStopOnContinue;
2862 if (options->m_stop_on_error == eLazyBoolYes)
2863 flags |= eHandleCommandFlagStopOnError;
2864 if (options->m_stop_on_crash == eLazyBoolYes)
2865 flags |= eHandleCommandFlagStopOnCrash;
2866 if (options->m_echo_commands != eLazyBoolNo)
2867 flags |= eHandleCommandFlagEchoCommand;
2868 if (options->m_print_results != eLazyBoolNo)
2869 flags |= eHandleCommandFlagPrintResult;
2871 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2874 m_command_io_handler_sp.reset(new IOHandlerEditline(
2875 m_debugger, IOHandler::Type::CommandInterpreter,
2876 m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2877 m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
2878 llvm::StringRef(), // Continuation prompt
2879 false, // Don't enable multiple line input, just single line commands
2880 m_debugger.GetUseColor(),
2881 0, // Don't show line numbers
2884 return m_command_io_handler_sp;
2887 void CommandInterpreter::RunCommandInterpreter(
2888 bool auto_handle_events, bool spawn_thread,
2889 CommandInterpreterRunOptions &options) {
2890 // Always re-create the command interpreter when we run it in case
2891 // any file handles have changed.
2892 bool force_create = true;
2893 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2894 m_stopped_for_crash = false;
2896 if (auto_handle_events)
2897 m_debugger.StartEventHandlerThread();
2900 m_debugger.StartIOHandlerThread();
2902 m_debugger.ExecuteIOHandlers();
2904 if (auto_handle_events)
2905 m_debugger.StopEventHandlerThread();
2910 CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2911 CommandReturnObject &result) {
2912 std::string scratch_command(command_line); // working copy so we don't modify
2913 // command_line unless we succeed
2914 CommandObject *cmd_obj = nullptr;
2915 StreamString revised_command_line;
2916 bool wants_raw_input = false;
2917 size_t actual_cmd_name_len = 0;
2918 std::string next_word;
2922 char quote_char = '\0';
2924 ExtractCommand(scratch_command, next_word, suffix, quote_char);
2925 if (cmd_obj == nullptr) {
2926 std::string full_name;
2927 bool is_alias = GetAliasFullName(next_word, full_name);
2928 cmd_obj = GetCommandObject(next_word, &matches);
2929 bool is_real_command =
2930 (is_alias == false) ||
2931 (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2932 if (!is_real_command) {
2934 std::string alias_result;
2936 BuildAliasResult(full_name, scratch_command, alias_result, result);
2937 revised_command_line.Printf("%s", alias_result.c_str());
2939 wants_raw_input = cmd_obj->WantsRawCommandString();
2940 actual_cmd_name_len = cmd_obj->GetCommandName().size();
2944 cmd_obj = GetCommandObject(next_word, &matches);
2946 llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2947 actual_cmd_name_len += cmd_name.size();
2948 revised_command_line.Printf("%s", cmd_name.str().c_str());
2949 wants_raw_input = cmd_obj->WantsRawCommandString();
2951 revised_command_line.Printf("%s", next_word.c_str());
2955 if (cmd_obj->IsMultiwordObject()) {
2956 CommandObject *sub_cmd_obj =
2957 cmd_obj->GetSubcommandObject(next_word.c_str());
2959 // The subcommand's name includes the parent command's name,
2960 // so restart rather than append to the revised_command_line.
2961 llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
2962 actual_cmd_name_len = sub_cmd_name.size() + 1;
2963 revised_command_line.Clear();
2964 revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
2965 cmd_obj = sub_cmd_obj;
2966 wants_raw_input = cmd_obj->WantsRawCommandString();
2969 revised_command_line.Printf(" %c%s%s%c", quote_char,
2970 next_word.c_str(), suffix.c_str(),
2973 revised_command_line.Printf(" %s%s", next_word.c_str(),
2979 revised_command_line.Printf(" %c%s%s%c", quote_char,
2980 next_word.c_str(), suffix.c_str(),
2983 revised_command_line.Printf(" %s%s", next_word.c_str(),
2989 if (cmd_obj == nullptr) {
2990 const size_t num_matches = matches.GetSize();
2991 if (matches.GetSize() > 1) {
2992 StreamString error_msg;
2993 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
2996 for (uint32_t i = 0; i < num_matches; ++i) {
2997 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
2999 result.AppendRawError(error_msg.GetString());
3001 // We didn't have only one match, otherwise we wouldn't get here.
3002 assert(num_matches == 0);
3003 result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3006 result.SetStatus(eReturnStatusFailed);
3010 if (cmd_obj->IsMultiwordObject()) {
3011 if (!suffix.empty()) {
3012 result.AppendErrorWithFormat(
3013 "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3014 "might be invalid).\n",
3015 cmd_obj->GetCommandName().str().c_str(),
3016 next_word.empty() ? "" : next_word.c_str(),
3017 next_word.empty() ? " -- " : " ", suffix.c_str());
3018 result.SetStatus(eReturnStatusFailed);
3022 // If we found a normal command, we are done
3024 if (!suffix.empty()) {
3025 switch (suffix[0]) {
3027 // GDB format suffixes
3029 Options *command_options = cmd_obj->GetOptions();
3030 if (command_options &&
3031 command_options->SupportsLongOption("gdb-format")) {
3032 std::string gdb_format_option("--gdb-format=");
3033 gdb_format_option += (suffix.c_str() + 1);
3035 std::string cmd = revised_command_line.GetString();
3036 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3037 if (arg_terminator_idx != std::string::npos) {
3038 // Insert the gdb format option before the "--" that terminates
3040 gdb_format_option.append(1, ' ');
3041 cmd.insert(arg_terminator_idx, gdb_format_option);
3042 revised_command_line.Clear();
3043 revised_command_line.PutCString(cmd);
3045 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3047 if (wants_raw_input &&
3048 FindArgumentTerminator(cmd) == std::string::npos)
3049 revised_command_line.PutCString(" --");
3051 result.AppendErrorWithFormat(
3052 "the '%s' command doesn't support the --gdb-format option\n",
3053 cmd_obj->GetCommandName().str().c_str());
3054 result.SetStatus(eReturnStatusFailed);
3061 result.AppendErrorWithFormat(
3062 "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3063 result.SetStatus(eReturnStatusFailed);
3068 if (scratch_command.empty())
3072 if (!scratch_command.empty())
3073 revised_command_line.Printf(" %s", scratch_command.c_str());
3075 if (cmd_obj != NULL)
3076 command_line = revised_command_line.GetString();