1 //===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <memory>
10 #include <stdlib.h>
11 #include <string>
12 #include <vector>
13 
14 #include "CommandObjectScript.h"
15 #include "lldb/Interpreter/CommandObjectRegexCommand.h"
16 
17 #include "Commands/CommandObjectApropos.h"
18 #include "Commands/CommandObjectBreakpoint.h"
19 #include "Commands/CommandObjectBugreport.h"
20 #include "Commands/CommandObjectCommands.h"
21 #include "Commands/CommandObjectDisassemble.h"
22 #include "Commands/CommandObjectExpression.h"
23 #include "Commands/CommandObjectFrame.h"
24 #include "Commands/CommandObjectGUI.h"
25 #include "Commands/CommandObjectHelp.h"
26 #include "Commands/CommandObjectLanguage.h"
27 #include "Commands/CommandObjectLog.h"
28 #include "Commands/CommandObjectMemory.h"
29 #include "Commands/CommandObjectPlatform.h"
30 #include "Commands/CommandObjectPlugin.h"
31 #include "Commands/CommandObjectProcess.h"
32 #include "Commands/CommandObjectQuit.h"
33 #include "Commands/CommandObjectRegister.h"
34 #include "Commands/CommandObjectReproducer.h"
35 #include "Commands/CommandObjectSettings.h"
36 #include "Commands/CommandObjectSource.h"
37 #include "Commands/CommandObjectStats.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"
43 
44 #include "lldb/Core/Debugger.h"
45 #include "lldb/Core/PluginManager.h"
46 #include "lldb/Core/StreamFile.h"
47 #include "lldb/Utility/Log.h"
48 #include "lldb/Utility/State.h"
49 #include "lldb/Utility/Stream.h"
50 #include "lldb/Utility/Timer.h"
51 
52 #ifndef LLDB_DISABLE_LIBEDIT
53 #include "lldb/Host/Editline.h"
54 #endif
55 #include "lldb/Host/Host.h"
56 #include "lldb/Host/HostInfo.h"
57 
58 #include "lldb/Interpreter/CommandCompletions.h"
59 #include "lldb/Interpreter/CommandInterpreter.h"
60 #include "lldb/Interpreter/CommandReturnObject.h"
61 #include "lldb/Interpreter/OptionValueProperties.h"
62 #include "lldb/Interpreter/Options.h"
63 #include "lldb/Interpreter/Property.h"
64 #include "lldb/Utility/Args.h"
65 
66 #include "lldb/Target/Process.h"
67 #include "lldb/Target/TargetList.h"
68 #include "lldb/Target/Thread.h"
69 
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/SmallString.h"
72 #include "llvm/Support/Path.h"
73 #include "llvm/Support/PrettyStackTrace.h"
74 
75 using namespace lldb;
76 using namespace lldb_private;
77 
78 static const char *k_white_space = " \t\v";
79 
80 static constexpr bool NoGlobalSetting = true;
81 static constexpr uintptr_t DefaultValueTrue = true;
82 static constexpr uintptr_t DefaultValueFalse = false;
83 static constexpr const char *NoCStrDefault = nullptr;
84 
85 static constexpr PropertyDefinition g_properties[] = {
86     {"expand-regex-aliases", OptionValue::eTypeBoolean, NoGlobalSetting,
87      DefaultValueFalse, NoCStrDefault, {},
88      "If true, regular expression alias commands will show the "
89      "expanded command that will be executed. This can be used to "
90      "debug new regular expression alias commands."},
91     {"prompt-on-quit", OptionValue::eTypeBoolean, NoGlobalSetting,
92      DefaultValueTrue, NoCStrDefault, {},
93      "If true, LLDB will prompt you before quitting if there are any live "
94      "processes being debugged. If false, LLDB will quit without asking in any "
95      "case."},
96     {"stop-command-source-on-error", OptionValue::eTypeBoolean, NoGlobalSetting,
97      DefaultValueTrue, NoCStrDefault, {},
98      "If true, LLDB will stop running a 'command source' "
99      "script upon encountering an error."},
100     {"space-repl-prompts", OptionValue::eTypeBoolean, NoGlobalSetting,
101      DefaultValueFalse, NoCStrDefault, {},
102      "If true, blank lines will be printed between between REPL submissions."},
103     {"echo-commands", OptionValue::eTypeBoolean, NoGlobalSetting,
104      DefaultValueTrue, NoCStrDefault, {},
105      "If true, commands will be echoed before they are evaluated."},
106     {"echo-comment-commands", OptionValue::eTypeBoolean, NoGlobalSetting,
107      DefaultValueTrue, NoCStrDefault, {},
108      "If true, commands will be echoed even if they are pure comment lines."}};
109 
110 enum {
111   ePropertyExpandRegexAliases = 0,
112   ePropertyPromptOnQuit = 1,
113   ePropertyStopCmdSourceOnError = 2,
114   eSpaceReplPrompts = 3,
115   eEchoCommands = 4,
116   eEchoCommentCommands = 5
117 };
118 
119 ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
120   static ConstString class_name("lldb.commandInterpreter");
121   return class_name;
122 }
123 
124 CommandInterpreter::CommandInterpreter(Debugger &debugger,
125                                        ScriptLanguage script_language,
126                                        bool synchronous_execution)
127     : Broadcaster(debugger.GetBroadcasterManager(),
128                   CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
129       Properties(OptionValuePropertiesSP(
130           new OptionValueProperties(ConstString("interpreter")))),
131       IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand),
132       m_debugger(debugger), m_synchronous_execution(synchronous_execution),
133       m_skip_lldbinit_files(false), m_skip_app_init_files(false),
134       m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'),
135       m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
136       m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
137       m_stopped_for_crash(false) {
138   debugger.SetScriptLanguage(script_language);
139   SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
140   SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
141   SetEventName(eBroadcastBitQuitCommandReceived, "quit");
142   CheckInWithManager();
143   m_collection_sp->Initialize(g_properties);
144 }
145 
146 bool CommandInterpreter::GetExpandRegexAliases() const {
147   const uint32_t idx = ePropertyExpandRegexAliases;
148   return m_collection_sp->GetPropertyAtIndexAsBoolean(
149       nullptr, idx, g_properties[idx].default_uint_value != 0);
150 }
151 
152 bool CommandInterpreter::GetPromptOnQuit() const {
153   const uint32_t idx = ePropertyPromptOnQuit;
154   return m_collection_sp->GetPropertyAtIndexAsBoolean(
155       nullptr, idx, g_properties[idx].default_uint_value != 0);
156 }
157 
158 void CommandInterpreter::SetPromptOnQuit(bool b) {
159   const uint32_t idx = ePropertyPromptOnQuit;
160   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
161 }
162 
163 bool CommandInterpreter::GetEchoCommands() const {
164   const uint32_t idx = eEchoCommands;
165   return m_collection_sp->GetPropertyAtIndexAsBoolean(
166       nullptr, idx, g_properties[idx].default_uint_value != 0);
167 }
168 
169 void CommandInterpreter::SetEchoCommands(bool b) {
170   const uint32_t idx = eEchoCommands;
171   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
172 }
173 
174 bool CommandInterpreter::GetEchoCommentCommands() const {
175   const uint32_t idx = eEchoCommentCommands;
176   return m_collection_sp->GetPropertyAtIndexAsBoolean(
177       nullptr, idx, g_properties[idx].default_uint_value != 0);
178 }
179 
180 void CommandInterpreter::SetEchoCommentCommands(bool b) {
181   const uint32_t idx = eEchoCommentCommands;
182   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
183 }
184 
185 void CommandInterpreter::AllowExitCodeOnQuit(bool allow) {
186   m_allow_exit_code = allow;
187   if (!allow)
188     m_quit_exit_code.reset();
189 }
190 
191 bool CommandInterpreter::SetQuitExitCode(int exit_code) {
192   if (!m_allow_exit_code)
193     return false;
194   m_quit_exit_code = exit_code;
195   return true;
196 }
197 
198 int CommandInterpreter::GetQuitExitCode(bool &exited) const {
199   exited = m_quit_exit_code.hasValue();
200   if (exited)
201     return *m_quit_exit_code;
202   return 0;
203 }
204 
205 void CommandInterpreter::ResolveCommand(const char *command_line,
206                                         CommandReturnObject &result) {
207   std::string command = command_line;
208   if (ResolveCommandImpl(command, result) != nullptr) {
209     result.AppendMessageWithFormat("%s", command.c_str());
210     result.SetStatus(eReturnStatusSuccessFinishResult);
211   }
212 }
213 
214 bool CommandInterpreter::GetStopCmdSourceOnError() const {
215   const uint32_t idx = ePropertyStopCmdSourceOnError;
216   return m_collection_sp->GetPropertyAtIndexAsBoolean(
217       nullptr, idx, g_properties[idx].default_uint_value != 0);
218 }
219 
220 bool CommandInterpreter::GetSpaceReplPrompts() const {
221   const uint32_t idx = eSpaceReplPrompts;
222   return m_collection_sp->GetPropertyAtIndexAsBoolean(
223       nullptr, idx, g_properties[idx].default_uint_value != 0);
224 }
225 
226 void CommandInterpreter::Initialize() {
227   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
228   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
229 
230   CommandReturnObject result;
231 
232   LoadCommandDictionary();
233 
234   // An alias arguments vector to reuse - reset it before use...
235   OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
236 
237   // Set up some initial aliases.
238   CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
239   if (cmd_obj_sp) {
240     AddAlias("q", cmd_obj_sp);
241     AddAlias("exit", cmd_obj_sp);
242   }
243 
244   cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
245   if (cmd_obj_sp)
246     AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
247 
248   cmd_obj_sp = GetCommandSPExact("process detach", false);
249   if (cmd_obj_sp) {
250     AddAlias("detach", cmd_obj_sp);
251   }
252 
253   cmd_obj_sp = GetCommandSPExact("process continue", false);
254   if (cmd_obj_sp) {
255     AddAlias("c", cmd_obj_sp);
256     AddAlias("continue", cmd_obj_sp);
257   }
258 
259   cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
260   if (cmd_obj_sp)
261     AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
262 
263   cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
264   if (cmd_obj_sp)
265     AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
266 
267   cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
268   if (cmd_obj_sp) {
269     AddAlias("stepi", cmd_obj_sp);
270     AddAlias("si", cmd_obj_sp);
271   }
272 
273   cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
274   if (cmd_obj_sp) {
275     AddAlias("nexti", cmd_obj_sp);
276     AddAlias("ni", cmd_obj_sp);
277   }
278 
279   cmd_obj_sp = GetCommandSPExact("thread step-in", false);
280   if (cmd_obj_sp) {
281     AddAlias("s", cmd_obj_sp);
282     AddAlias("step", cmd_obj_sp);
283     CommandAlias *sif_alias = AddAlias(
284         "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
285     if (sif_alias) {
286       sif_alias->SetHelp("Step through the current block, stopping if you step "
287                          "directly into a function whose name matches the "
288                          "TargetFunctionName.");
289       sif_alias->SetSyntax("sif <TargetFunctionName>");
290     }
291   }
292 
293   cmd_obj_sp = GetCommandSPExact("thread step-over", false);
294   if (cmd_obj_sp) {
295     AddAlias("n", cmd_obj_sp);
296     AddAlias("next", cmd_obj_sp);
297   }
298 
299   cmd_obj_sp = GetCommandSPExact("thread step-out", false);
300   if (cmd_obj_sp) {
301     AddAlias("finish", cmd_obj_sp);
302   }
303 
304   cmd_obj_sp = GetCommandSPExact("frame select", false);
305   if (cmd_obj_sp) {
306     AddAlias("f", cmd_obj_sp);
307   }
308 
309   cmd_obj_sp = GetCommandSPExact("thread select", false);
310   if (cmd_obj_sp) {
311     AddAlias("t", cmd_obj_sp);
312   }
313 
314   cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
315   if (cmd_obj_sp) {
316     AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
317     AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
318   }
319 
320   cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
321   if (cmd_obj_sp) {
322     AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
323     AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
324   }
325 
326   cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
327   if (cmd_obj_sp)
328     AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
329 
330   cmd_obj_sp = GetCommandSPExact("memory read", false);
331   if (cmd_obj_sp)
332     AddAlias("x", cmd_obj_sp);
333 
334   cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
335   if (cmd_obj_sp)
336     AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
337 
338   cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
339   if (cmd_obj_sp)
340     AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
341 
342   cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
343   if (cmd_obj_sp)
344     AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
345 
346   cmd_obj_sp = GetCommandSPExact("disassemble", false);
347   if (cmd_obj_sp)
348     AddAlias("dis", cmd_obj_sp);
349 
350   cmd_obj_sp = GetCommandSPExact("disassemble", false);
351   if (cmd_obj_sp)
352     AddAlias("di", cmd_obj_sp);
353 
354   cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
355   if (cmd_obj_sp)
356     AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
357 
358   cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
359   if (cmd_obj_sp)
360     AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
361 
362   cmd_obj_sp = GetCommandSPExact("target create", false);
363   if (cmd_obj_sp)
364     AddAlias("file", cmd_obj_sp);
365 
366   cmd_obj_sp = GetCommandSPExact("target modules", false);
367   if (cmd_obj_sp)
368     AddAlias("image", cmd_obj_sp);
369 
370   alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
371 
372   cmd_obj_sp = GetCommandSPExact("expression", false);
373   if (cmd_obj_sp) {
374     AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
375     AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
376     AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
377     if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
378       po->SetHelp("Evaluate an expression on the current thread.  Displays any "
379                   "returned value with formatting "
380                   "controlled by the type's author.");
381       po->SetHelpLong("");
382     }
383     AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
384     AddAlias("poarray", cmd_obj_sp,
385              "--object-description --element-count %1 --")
386         ->SetHelpLong("");
387   }
388 
389   cmd_obj_sp = GetCommandSPExact("process kill", false);
390   if (cmd_obj_sp) {
391     AddAlias("kill", cmd_obj_sp);
392   }
393 
394   cmd_obj_sp = GetCommandSPExact("process launch", false);
395   if (cmd_obj_sp) {
396     alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
397 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
398     AddAlias("r", cmd_obj_sp, "--");
399     AddAlias("run", cmd_obj_sp, "--");
400 #else
401 #if defined(__APPLE__)
402     std::string shell_option;
403     shell_option.append("--shell-expand-args");
404     shell_option.append(" true");
405     shell_option.append(" --");
406     AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
407     AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
408 #else
409     StreamString defaultshell;
410     defaultshell.Printf("--shell=%s --",
411                         HostInfo::GetDefaultShell().GetPath().c_str());
412     AddAlias("r", cmd_obj_sp, defaultshell.GetString());
413     AddAlias("run", cmd_obj_sp, defaultshell.GetString());
414 #endif
415 #endif
416   }
417 
418   cmd_obj_sp = GetCommandSPExact("target symbols add", false);
419   if (cmd_obj_sp) {
420     AddAlias("add-dsym", cmd_obj_sp);
421   }
422 
423   cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
424   if (cmd_obj_sp) {
425     AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
426   }
427 
428   cmd_obj_sp = GetCommandSPExact("frame variable", false);
429   if (cmd_obj_sp) {
430     AddAlias("v", cmd_obj_sp);
431     AddAlias("var", cmd_obj_sp);
432     AddAlias("vo", cmd_obj_sp, "--object-description");
433   }
434 }
435 
436 void CommandInterpreter::Clear() {
437   m_command_io_handler_sp.reset();
438 
439   if (m_script_interpreter_sp)
440     m_script_interpreter_sp->Clear();
441 }
442 
443 const char *CommandInterpreter::ProcessEmbeddedScriptCommands(const char *arg) {
444   // This function has not yet been implemented.
445 
446   // Look for any embedded script command
447   // If found,
448   //    get interpreter object from the command dictionary,
449   //    call execute_one_command on it,
450   //    get the results as a string,
451   //    substitute that string for current stuff.
452 
453   return arg;
454 }
455 
456 void CommandInterpreter::LoadCommandDictionary() {
457   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
458   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
459 
460   lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
461 
462   m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
463   m_command_dict["breakpoint"] =
464       CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
465   m_command_dict["bugreport"] =
466       CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
467   m_command_dict["command"] =
468       CommandObjectSP(new CommandObjectMultiwordCommands(*this));
469   m_command_dict["disassemble"] =
470       CommandObjectSP(new CommandObjectDisassemble(*this));
471   m_command_dict["expression"] =
472       CommandObjectSP(new CommandObjectExpression(*this));
473   m_command_dict["frame"] =
474       CommandObjectSP(new CommandObjectMultiwordFrame(*this));
475   m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
476   m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
477   m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
478   m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
479   m_command_dict["platform"] =
480       CommandObjectSP(new CommandObjectPlatform(*this));
481   m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
482   m_command_dict["process"] =
483       CommandObjectSP(new CommandObjectMultiwordProcess(*this));
484   m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
485   m_command_dict["register"] =
486       CommandObjectSP(new CommandObjectRegister(*this));
487   m_command_dict["reproducer"] =
488       CommandObjectSP(new CommandObjectReproducer(*this));
489   m_command_dict["script"] =
490       CommandObjectSP(new CommandObjectScript(*this, script_language));
491   m_command_dict["settings"] =
492       CommandObjectSP(new CommandObjectMultiwordSettings(*this));
493   m_command_dict["source"] =
494       CommandObjectSP(new CommandObjectMultiwordSource(*this));
495   m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
496   m_command_dict["target"] =
497       CommandObjectSP(new CommandObjectMultiwordTarget(*this));
498   m_command_dict["thread"] =
499       CommandObjectSP(new CommandObjectMultiwordThread(*this));
500   m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
501   m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
502   m_command_dict["watchpoint"] =
503       CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
504   m_command_dict["language"] =
505       CommandObjectSP(new CommandObjectLanguage(*this));
506 
507   const char *break_regexes[][2] = {
508       {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
509        "breakpoint set --file '%1' --line %2"},
510       {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
511       {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
512       {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
513       {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
514        "breakpoint set --name '%1'"},
515       {"^(-.*)$", "breakpoint set %1"},
516       {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
517        "breakpoint set --name '%2' --shlib '%1'"},
518       {"^\\&(.*[^[:space:]])[[:space:]]*$",
519        "breakpoint set --name '%1' --skip-prologue=0"},
520       {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
521        "breakpoint set --name '%1'"}};
522 
523   size_t num_regexes = llvm::array_lengthof(break_regexes);
524 
525   std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_up(
526       new CommandObjectRegexCommand(
527           *this, "_regexp-break",
528           "Set a breakpoint using one of several shorthand formats.",
529           "\n"
530           "_regexp-break <filename>:<linenum>\n"
531           "              main.c:12             // Break at line 12 of "
532           "main.c\n\n"
533           "_regexp-break <linenum>\n"
534           "              12                    // Break at line 12 of current "
535           "file\n\n"
536           "_regexp-break 0x<address>\n"
537           "              0x1234000             // Break at address "
538           "0x1234000\n\n"
539           "_regexp-break <name>\n"
540           "              main                  // Break in 'main' after the "
541           "prologue\n\n"
542           "_regexp-break &<name>\n"
543           "              &main                 // Break at first instruction "
544           "in 'main'\n\n"
545           "_regexp-break <module>`<name>\n"
546           "              libc.so`malloc        // Break in 'malloc' from "
547           "'libc.so'\n\n"
548           "_regexp-break /<source-regex>/\n"
549           "              /break here/          // Break on source lines in "
550           "current file\n"
551           "                                    // containing text 'break "
552           "here'.\n",
553           2,
554           CommandCompletions::eSymbolCompletion |
555               CommandCompletions::eSourceFileCompletion,
556           false));
557 
558   if (break_regex_cmd_up) {
559     bool success = true;
560     for (size_t i = 0; i < num_regexes; i++) {
561       success = break_regex_cmd_up->AddRegexCommand(break_regexes[i][0],
562                                                     break_regexes[i][1]);
563       if (!success)
564         break;
565     }
566     success =
567         break_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full");
568 
569     if (success) {
570       CommandObjectSP break_regex_cmd_sp(break_regex_cmd_up.release());
571       m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
572     }
573   }
574 
575   std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_up(
576       new CommandObjectRegexCommand(
577           *this, "_regexp-tbreak",
578           "Set a one-shot breakpoint using one of several shorthand formats.",
579           "\n"
580           "_regexp-break <filename>:<linenum>\n"
581           "              main.c:12             // Break at line 12 of "
582           "main.c\n\n"
583           "_regexp-break <linenum>\n"
584           "              12                    // Break at line 12 of current "
585           "file\n\n"
586           "_regexp-break 0x<address>\n"
587           "              0x1234000             // Break at address "
588           "0x1234000\n\n"
589           "_regexp-break <name>\n"
590           "              main                  // Break in 'main' after the "
591           "prologue\n\n"
592           "_regexp-break &<name>\n"
593           "              &main                 // Break at first instruction "
594           "in 'main'\n\n"
595           "_regexp-break <module>`<name>\n"
596           "              libc.so`malloc        // Break in 'malloc' from "
597           "'libc.so'\n\n"
598           "_regexp-break /<source-regex>/\n"
599           "              /break here/          // Break on source lines in "
600           "current file\n"
601           "                                    // containing text 'break "
602           "here'.\n",
603           2,
604           CommandCompletions::eSymbolCompletion |
605               CommandCompletions::eSourceFileCompletion,
606           false));
607 
608   if (tbreak_regex_cmd_up) {
609     bool success = true;
610     for (size_t i = 0; i < num_regexes; i++) {
611       // If you add a resultant command string longer than 1024 characters be
612       // sure to increase the size of this buffer.
613       char buffer[1024];
614       int num_printed =
615           snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
616       lldbassert(num_printed < 1024);
617       UNUSED_IF_ASSERT_DISABLED(num_printed);
618       success =
619           tbreak_regex_cmd_up->AddRegexCommand(break_regexes[i][0], buffer);
620       if (!success)
621         break;
622     }
623     success =
624         tbreak_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full");
625 
626     if (success) {
627       CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_up.release());
628       m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
629           tbreak_regex_cmd_sp;
630     }
631   }
632 
633   std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_up(
634       new CommandObjectRegexCommand(
635           *this, "_regexp-attach", "Attach to process by ID or name.",
636           "_regexp-attach <pid> | <process-name>", 2, 0, false));
637   if (attach_regex_cmd_up) {
638     if (attach_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
639                                              "process attach --pid %1") &&
640         attach_regex_cmd_up->AddRegexCommand(
641             "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
642                                                       // specified get passed to
643                                                       // 'process attach'
644         attach_regex_cmd_up->AddRegexCommand("^(.+)$",
645                                              "process attach --name '%1'") &&
646         attach_regex_cmd_up->AddRegexCommand("^$", "process attach")) {
647       CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_up.release());
648       m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
649           attach_regex_cmd_sp;
650     }
651   }
652 
653   std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_up(
654       new CommandObjectRegexCommand(*this, "_regexp-down",
655                                     "Select a newer stack frame.  Defaults to "
656                                     "moving one frame, a numeric argument can "
657                                     "specify an arbitrary number.",
658                                     "_regexp-down [<count>]", 2, 0, false));
659   if (down_regex_cmd_up) {
660     if (down_regex_cmd_up->AddRegexCommand("^$", "frame select -r -1") &&
661         down_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
662                                            "frame select -r -%1")) {
663       CommandObjectSP down_regex_cmd_sp(down_regex_cmd_up.release());
664       m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
665     }
666   }
667 
668   std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_up(
669       new CommandObjectRegexCommand(
670           *this, "_regexp-up",
671           "Select an older stack frame.  Defaults to moving one "
672           "frame, a numeric argument can specify an arbitrary number.",
673           "_regexp-up [<count>]", 2, 0, false));
674   if (up_regex_cmd_up) {
675     if (up_regex_cmd_up->AddRegexCommand("^$", "frame select -r 1") &&
676         up_regex_cmd_up->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
677       CommandObjectSP up_regex_cmd_sp(up_regex_cmd_up.release());
678       m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
679     }
680   }
681 
682   std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_up(
683       new CommandObjectRegexCommand(
684           *this, "_regexp-display",
685           "Evaluate an expression at every stop (see 'help target stop-hook'.)",
686           "_regexp-display expression", 2, 0, false));
687   if (display_regex_cmd_up) {
688     if (display_regex_cmd_up->AddRegexCommand(
689             "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
690       CommandObjectSP display_regex_cmd_sp(display_regex_cmd_up.release());
691       m_command_dict[display_regex_cmd_sp->GetCommandName()] =
692           display_regex_cmd_sp;
693     }
694   }
695 
696   std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_up(
697       new CommandObjectRegexCommand(*this, "_regexp-undisplay",
698                                     "Stop displaying expression at every "
699                                     "stop (specified by stop-hook index.)",
700                                     "_regexp-undisplay stop-hook-number", 2, 0,
701                                     false));
702   if (undisplay_regex_cmd_up) {
703     if (undisplay_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
704                                                 "target stop-hook delete %1")) {
705       CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_up.release());
706       m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
707           undisplay_regex_cmd_sp;
708     }
709   }
710 
711   std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_up(
712       new CommandObjectRegexCommand(
713           *this, "gdb-remote",
714           "Connect to a process via remote GDB server.  "
715           "If no host is specifed, localhost is assumed.",
716           "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
717   if (connect_gdb_remote_cmd_up) {
718     if (connect_gdb_remote_cmd_up->AddRegexCommand(
719             "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
720             "process connect --plugin gdb-remote connect://%1:%2") &&
721         connect_gdb_remote_cmd_up->AddRegexCommand(
722             "^([[:digit:]]+)$",
723             "process connect --plugin gdb-remote connect://localhost:%1")) {
724       CommandObjectSP command_sp(connect_gdb_remote_cmd_up.release());
725       m_command_dict[command_sp->GetCommandName()] = command_sp;
726     }
727   }
728 
729   std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_up(
730       new CommandObjectRegexCommand(
731           *this, "kdp-remote",
732           "Connect to a process via remote KDP server.  "
733           "If no UDP port is specified, port 41139 is "
734           "assumed.",
735           "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
736   if (connect_kdp_remote_cmd_up) {
737     if (connect_kdp_remote_cmd_up->AddRegexCommand(
738             "^([^:]+:[[:digit:]]+)$",
739             "process connect --plugin kdp-remote udp://%1") &&
740         connect_kdp_remote_cmd_up->AddRegexCommand(
741             "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
742       CommandObjectSP command_sp(connect_kdp_remote_cmd_up.release());
743       m_command_dict[command_sp->GetCommandName()] = command_sp;
744     }
745   }
746 
747   std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_up(
748       new CommandObjectRegexCommand(
749           *this, "_regexp-bt",
750           "Show the current thread's call stack.  Any numeric argument "
751           "displays at most that many "
752           "frames.  The argument 'all' displays all threads.",
753           "bt [<digit> | all]", 2, 0, false));
754   if (bt_regex_cmd_up) {
755     // accept but don't document "bt -c <number>" -- before bt was a regex
756     // command if you wanted to backtrace three frames you would do "bt -c 3"
757     // but the intention is to have this emulate the gdb "bt" command and so
758     // now "bt 3" is the preferred form, in line with gdb.
759     if (bt_regex_cmd_up->AddRegexCommand("^([[:digit:]]+)$",
760                                          "thread backtrace -c %1") &&
761         bt_regex_cmd_up->AddRegexCommand("^-c ([[:digit:]]+)$",
762                                          "thread backtrace -c %1") &&
763         bt_regex_cmd_up->AddRegexCommand("^all$", "thread backtrace all") &&
764         bt_regex_cmd_up->AddRegexCommand("^$", "thread backtrace")) {
765       CommandObjectSP command_sp(bt_regex_cmd_up.release());
766       m_command_dict[command_sp->GetCommandName()] = command_sp;
767     }
768   }
769 
770   std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_up(
771       new CommandObjectRegexCommand(
772           *this, "_regexp-list",
773           "List relevant source code using one of several shorthand formats.",
774           "\n"
775           "_regexp-list <file>:<line>   // List around specific file/line\n"
776           "_regexp-list <line>          // List current file around specified "
777           "line\n"
778           "_regexp-list <function-name> // List specified function\n"
779           "_regexp-list 0x<address>     // List around specified address\n"
780           "_regexp-list -[<count>]      // List previous <count> lines\n"
781           "_regexp-list                 // List subsequent lines",
782           2, CommandCompletions::eSourceFileCompletion, false));
783   if (list_regex_cmd_up) {
784     if (list_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
785                                            "source list --line %1") &&
786         list_regex_cmd_up->AddRegexCommand(
787             "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
788             "]*$",
789             "source list --file '%1' --line %2") &&
790         list_regex_cmd_up->AddRegexCommand(
791             "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
792             "source list --address %1") &&
793         list_regex_cmd_up->AddRegexCommand("^-[[:space:]]*$",
794                                            "source list --reverse") &&
795         list_regex_cmd_up->AddRegexCommand(
796             "^-([[:digit:]]+)[[:space:]]*$",
797             "source list --reverse --count %1") &&
798         list_regex_cmd_up->AddRegexCommand("^(.+)$",
799                                            "source list --name \"%1\"") &&
800         list_regex_cmd_up->AddRegexCommand("^$", "source list")) {
801       CommandObjectSP list_regex_cmd_sp(list_regex_cmd_up.release());
802       m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
803     }
804   }
805 
806   std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_up(
807       new CommandObjectRegexCommand(
808           *this, "_regexp-env",
809           "Shorthand for viewing and setting environment variables.",
810           "\n"
811           "_regexp-env                  // Show enrivonment\n"
812           "_regexp-env <name>=<value>   // Set an environment variable",
813           2, 0, false));
814   if (env_regex_cmd_up) {
815     if (env_regex_cmd_up->AddRegexCommand("^$",
816                                           "settings show target.env-vars") &&
817         env_regex_cmd_up->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
818                                           "settings set target.env-vars %1")) {
819       CommandObjectSP env_regex_cmd_sp(env_regex_cmd_up.release());
820       m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
821     }
822   }
823 
824   std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_up(
825       new CommandObjectRegexCommand(
826           *this, "_regexp-jump", "Set the program counter to a new address.",
827           "\n"
828           "_regexp-jump <line>\n"
829           "_regexp-jump +<line-offset> | -<line-offset>\n"
830           "_regexp-jump <file>:<line>\n"
831           "_regexp-jump *<addr>\n",
832           2, 0, false));
833   if (jump_regex_cmd_up) {
834     if (jump_regex_cmd_up->AddRegexCommand("^\\*(.*)$",
835                                            "thread jump --addr %1") &&
836         jump_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
837                                            "thread jump --line %1") &&
838         jump_regex_cmd_up->AddRegexCommand("^([^:]+):([0-9]+)$",
839                                            "thread jump --file %1 --line %2") &&
840         jump_regex_cmd_up->AddRegexCommand("^([+\\-][0-9]+)$",
841                                            "thread jump --by %1")) {
842       CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_up.release());
843       m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
844     }
845   }
846 }
847 
848 int CommandInterpreter::GetCommandNamesMatchingPartialString(
849     const char *cmd_str, bool include_aliases, StringList &matches,
850     StringList &descriptions) {
851   AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
852                                 &descriptions);
853 
854   if (include_aliases) {
855     AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
856                                   &descriptions);
857   }
858 
859   return matches.GetSize();
860 }
861 
862 CommandObjectSP
863 CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
864                                  bool exact, StringList *matches,
865                                  StringList *descriptions) const {
866   CommandObjectSP command_sp;
867 
868   std::string cmd = cmd_str;
869 
870   if (HasCommands()) {
871     auto pos = m_command_dict.find(cmd);
872     if (pos != m_command_dict.end())
873       command_sp = pos->second;
874   }
875 
876   if (include_aliases && HasAliases()) {
877     auto alias_pos = m_alias_dict.find(cmd);
878     if (alias_pos != m_alias_dict.end())
879       command_sp = alias_pos->second;
880   }
881 
882   if (HasUserCommands()) {
883     auto pos = m_user_dict.find(cmd);
884     if (pos != m_user_dict.end())
885       command_sp = pos->second;
886   }
887 
888   if (!exact && !command_sp) {
889     // We will only get into here if we didn't find any exact matches.
890 
891     CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
892 
893     StringList local_matches;
894     if (matches == nullptr)
895       matches = &local_matches;
896 
897     unsigned int num_cmd_matches = 0;
898     unsigned int num_alias_matches = 0;
899     unsigned int num_user_matches = 0;
900 
901     // Look through the command dictionaries one by one, and if we get only one
902     // match from any of them in toto, then return that, otherwise return an
903     // empty CommandObjectSP and the list of matches.
904 
905     if (HasCommands()) {
906       num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
907                                                       *matches, descriptions);
908     }
909 
910     if (num_cmd_matches == 1) {
911       cmd.assign(matches->GetStringAtIndex(0));
912       auto pos = m_command_dict.find(cmd);
913       if (pos != m_command_dict.end())
914         real_match_sp = pos->second;
915     }
916 
917     if (include_aliases && HasAliases()) {
918       num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
919                                                         *matches, descriptions);
920     }
921 
922     if (num_alias_matches == 1) {
923       cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
924       auto alias_pos = m_alias_dict.find(cmd);
925       if (alias_pos != m_alias_dict.end())
926         alias_match_sp = alias_pos->second;
927     }
928 
929     if (HasUserCommands()) {
930       num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
931                                                        *matches, descriptions);
932     }
933 
934     if (num_user_matches == 1) {
935       cmd.assign(
936           matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
937 
938       auto pos = m_user_dict.find(cmd);
939       if (pos != m_user_dict.end())
940         user_match_sp = pos->second;
941     }
942 
943     // If we got exactly one match, return that, otherwise return the match
944     // list.
945 
946     if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
947       if (num_cmd_matches)
948         return real_match_sp;
949       else if (num_alias_matches)
950         return alias_match_sp;
951       else
952         return user_match_sp;
953     }
954   } else if (matches && command_sp) {
955     matches->AppendString(cmd_str);
956     if (descriptions)
957       descriptions->AppendString(command_sp->GetHelp());
958   }
959 
960   return command_sp;
961 }
962 
963 bool CommandInterpreter::AddCommand(llvm::StringRef name,
964                                     const lldb::CommandObjectSP &cmd_sp,
965                                     bool can_replace) {
966   if (cmd_sp.get())
967     lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
968                "tried to add a CommandObject from a different interpreter");
969 
970   if (name.empty())
971     return false;
972 
973   std::string name_sstr(name);
974   auto name_iter = m_command_dict.find(name_sstr);
975   if (name_iter != m_command_dict.end()) {
976     if (!can_replace || !name_iter->second->IsRemovable())
977       return false;
978     name_iter->second = cmd_sp;
979   } else {
980     m_command_dict[name_sstr] = cmd_sp;
981   }
982   return true;
983 }
984 
985 bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
986                                         const lldb::CommandObjectSP &cmd_sp,
987                                         bool can_replace) {
988   if (cmd_sp.get())
989     lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
990                "tried to add a CommandObject from a different interpreter");
991 
992   if (!name.empty()) {
993     // do not allow replacement of internal commands
994     if (CommandExists(name)) {
995       if (!can_replace)
996         return false;
997       if (!m_command_dict[name]->IsRemovable())
998         return false;
999     }
1000 
1001     if (UserCommandExists(name)) {
1002       if (!can_replace)
1003         return false;
1004       if (!m_user_dict[name]->IsRemovable())
1005         return false;
1006     }
1007 
1008     m_user_dict[name] = cmd_sp;
1009     return true;
1010   }
1011   return false;
1012 }
1013 
1014 CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
1015                                                       bool include_aliases) const {
1016   Args cmd_words(cmd_str);  // Break up the command string into words, in case
1017                             // it's a multi-word command.
1018   CommandObjectSP ret_val;  // Possibly empty return value.
1019 
1020   if (cmd_str.empty())
1021     return ret_val;
1022 
1023   if (cmd_words.GetArgumentCount() == 1)
1024     return GetCommandSP(cmd_str, include_aliases, true, nullptr);
1025   else {
1026     // We have a multi-word command (seemingly), so we need to do more work.
1027     // First, get the cmd_obj_sp for the first word in the command.
1028     CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
1029                                               include_aliases, true, nullptr);
1030     if (cmd_obj_sp.get() != nullptr) {
1031       // Loop through the rest of the words in the command (everything passed
1032       // in was supposed to be part of a command name), and find the
1033       // appropriate sub-command SP for each command word....
1034       size_t end = cmd_words.GetArgumentCount();
1035       for (size_t j = 1; j < end; ++j) {
1036         if (cmd_obj_sp->IsMultiwordObject()) {
1037           cmd_obj_sp =
1038               cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
1039           if (cmd_obj_sp.get() == nullptr)
1040             // The sub-command name was invalid.  Fail and return the empty
1041             // 'ret_val'.
1042             return ret_val;
1043         } else
1044           // We have more words in the command name, but we don't have a
1045           // multiword object. Fail and return empty 'ret_val'.
1046           return ret_val;
1047       }
1048       // We successfully looped through all the command words and got valid
1049       // command objects for them.  Assign the last object retrieved to
1050       // 'ret_val'.
1051       ret_val = cmd_obj_sp;
1052     }
1053   }
1054   return ret_val;
1055 }
1056 
1057 CommandObject *
1058 CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1059                                      StringList *matches,
1060                                      StringList *descriptions) const {
1061   CommandObject *command_obj =
1062       GetCommandSP(cmd_str, false, true, matches, descriptions).get();
1063 
1064   // If we didn't find an exact match to the command string in the commands,
1065   // look in the aliases.
1066 
1067   if (command_obj)
1068     return command_obj;
1069 
1070   command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
1071 
1072   if (command_obj)
1073     return command_obj;
1074 
1075   // If there wasn't an exact match then look for an inexact one in just the
1076   // commands
1077   command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
1078 
1079   // Finally, if there wasn't an inexact match among the commands, look for an
1080   // inexact match in both the commands and aliases.
1081 
1082   if (command_obj) {
1083     if (matches)
1084       matches->AppendString(command_obj->GetCommandName());
1085     if (descriptions)
1086       descriptions->AppendString(command_obj->GetHelp());
1087     return command_obj;
1088   }
1089 
1090   return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
1091 }
1092 
1093 bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
1094   return m_command_dict.find(cmd) != m_command_dict.end();
1095 }
1096 
1097 bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1098                                           std::string &full_name) const {
1099   bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1100   if (exact_match) {
1101     full_name.assign(cmd);
1102     return exact_match;
1103   } else {
1104     StringList matches;
1105     size_t num_alias_matches;
1106     num_alias_matches =
1107         AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1108     if (num_alias_matches == 1) {
1109       // Make sure this isn't shadowing a command in the regular command space:
1110       StringList regular_matches;
1111       const bool include_aliases = false;
1112       const bool exact = false;
1113       CommandObjectSP cmd_obj_sp(
1114           GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1115       if (cmd_obj_sp || regular_matches.GetSize() > 0)
1116         return false;
1117       else {
1118         full_name.assign(matches.GetStringAtIndex(0));
1119         return true;
1120       }
1121     } else
1122       return false;
1123   }
1124 }
1125 
1126 bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
1127   return m_alias_dict.find(cmd) != m_alias_dict.end();
1128 }
1129 
1130 bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
1131   return m_user_dict.find(cmd) != m_user_dict.end();
1132 }
1133 
1134 CommandAlias *
1135 CommandInterpreter::AddAlias(llvm::StringRef alias_name,
1136                              lldb::CommandObjectSP &command_obj_sp,
1137                              llvm::StringRef args_string) {
1138   if (command_obj_sp.get())
1139     lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1140                "tried to add a CommandObject from a different interpreter");
1141 
1142   std::unique_ptr<CommandAlias> command_alias_up(
1143       new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1144 
1145   if (command_alias_up && command_alias_up->IsValid()) {
1146     m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1147     return command_alias_up.release();
1148   }
1149 
1150   return nullptr;
1151 }
1152 
1153 bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
1154   auto pos = m_alias_dict.find(alias_name);
1155   if (pos != m_alias_dict.end()) {
1156     m_alias_dict.erase(pos);
1157     return true;
1158   }
1159   return false;
1160 }
1161 
1162 bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
1163   auto pos = m_command_dict.find(cmd);
1164   if (pos != m_command_dict.end()) {
1165     if (pos->second->IsRemovable()) {
1166       // Only regular expression objects or python commands are removable
1167       m_command_dict.erase(pos);
1168       return true;
1169     }
1170   }
1171   return false;
1172 }
1173 bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
1174   CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1175   if (pos != m_user_dict.end()) {
1176     m_user_dict.erase(pos);
1177     return true;
1178   }
1179   return false;
1180 }
1181 
1182 void CommandInterpreter::GetHelp(CommandReturnObject &result,
1183                                  uint32_t cmd_types) {
1184   llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1185   if (!help_prologue.empty()) {
1186     OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1187                             help_prologue);
1188   }
1189 
1190   CommandObject::CommandMap::const_iterator pos;
1191   size_t max_len = FindLongestCommandWord(m_command_dict);
1192 
1193   if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1194     result.AppendMessage("Debugger commands:");
1195     result.AppendMessage("");
1196 
1197     for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1198       if (!(cmd_types & eCommandTypesHidden) &&
1199           (pos->first.compare(0, 1, "_") == 0))
1200         continue;
1201 
1202       OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1203                               pos->second->GetHelp(), max_len);
1204     }
1205     result.AppendMessage("");
1206   }
1207 
1208   if (!m_alias_dict.empty() &&
1209       ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1210     result.AppendMessageWithFormat(
1211         "Current command abbreviations "
1212         "(type '%shelp command alias' for more info):\n",
1213         GetCommandPrefix());
1214     result.AppendMessage("");
1215     max_len = FindLongestCommandWord(m_alias_dict);
1216 
1217     for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1218          ++alias_pos) {
1219       OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
1220                               alias_pos->second->GetHelp(), max_len);
1221     }
1222     result.AppendMessage("");
1223   }
1224 
1225   if (!m_user_dict.empty() &&
1226       ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1227     result.AppendMessage("Current user-defined commands:");
1228     result.AppendMessage("");
1229     max_len = FindLongestCommandWord(m_user_dict);
1230     for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
1231       OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1232                               pos->second->GetHelp(), max_len);
1233     }
1234     result.AppendMessage("");
1235   }
1236 
1237   result.AppendMessageWithFormat(
1238       "For more information on any command, type '%shelp <command-name>'.\n",
1239       GetCommandPrefix());
1240 }
1241 
1242 CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1243     llvm::StringRef &command_string) {
1244   // This function finds the final, lowest-level, alias-resolved command object
1245   // whose 'Execute' function will eventually be invoked by the given command
1246   // line.
1247 
1248   CommandObject *cmd_obj = nullptr;
1249   size_t start = command_string.find_first_not_of(k_white_space);
1250   size_t end = 0;
1251   bool done = false;
1252   while (!done) {
1253     if (start != std::string::npos) {
1254       // Get the next word from command_string.
1255       end = command_string.find_first_of(k_white_space, start);
1256       if (end == std::string::npos)
1257         end = command_string.size();
1258       std::string cmd_word = command_string.substr(start, end - start);
1259 
1260       if (cmd_obj == nullptr)
1261         // Since cmd_obj is NULL we are on our first time through this loop.
1262         // Check to see if cmd_word is a valid command or alias.
1263         cmd_obj = GetCommandObject(cmd_word);
1264       else if (cmd_obj->IsMultiwordObject()) {
1265         // Our current object is a multi-word object; see if the cmd_word is a
1266         // valid sub-command for our object.
1267         CommandObject *sub_cmd_obj =
1268             cmd_obj->GetSubcommandObject(cmd_word.c_str());
1269         if (sub_cmd_obj)
1270           cmd_obj = sub_cmd_obj;
1271         else // cmd_word was not a valid sub-command word, so we are done
1272           done = true;
1273       } else
1274         // We have a cmd_obj and it is not a multi-word object, so we are done.
1275         done = true;
1276 
1277       // If we didn't find a valid command object, or our command object is not
1278       // a multi-word object, or we are at the end of the command_string, then
1279       // we are done.  Otherwise, find the start of the next word.
1280 
1281       if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1282           end >= command_string.size())
1283         done = true;
1284       else
1285         start = command_string.find_first_not_of(k_white_space, end);
1286     } else
1287       // Unable to find any more words.
1288       done = true;
1289   }
1290 
1291   command_string = command_string.substr(end);
1292   return cmd_obj;
1293 }
1294 
1295 static const char *k_valid_command_chars =
1296     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1297 static void StripLeadingSpaces(std::string &s) {
1298   if (!s.empty()) {
1299     size_t pos = s.find_first_not_of(k_white_space);
1300     if (pos == std::string::npos)
1301       s.clear();
1302     else if (pos == 0)
1303       return;
1304     s.erase(0, pos);
1305   }
1306 }
1307 
1308 static size_t FindArgumentTerminator(const std::string &s) {
1309   const size_t s_len = s.size();
1310   size_t offset = 0;
1311   while (offset < s_len) {
1312     size_t pos = s.find("--", offset);
1313     if (pos == std::string::npos)
1314       break;
1315     if (pos > 0) {
1316       if (isspace(s[pos - 1])) {
1317         // Check if the string ends "\s--" (where \s is a space character) or
1318         // if we have "\s--\s".
1319         if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1320           return pos;
1321         }
1322       }
1323     }
1324     offset = pos + 2;
1325   }
1326   return std::string::npos;
1327 }
1328 
1329 static bool ExtractCommand(std::string &command_string, std::string &command,
1330                            std::string &suffix, char &quote_char) {
1331   command.clear();
1332   suffix.clear();
1333   StripLeadingSpaces(command_string);
1334 
1335   bool result = false;
1336   quote_char = '\0';
1337 
1338   if (!command_string.empty()) {
1339     const char first_char = command_string[0];
1340     if (first_char == '\'' || first_char == '"') {
1341       quote_char = first_char;
1342       const size_t end_quote_pos = command_string.find(quote_char, 1);
1343       if (end_quote_pos == std::string::npos) {
1344         command.swap(command_string);
1345         command_string.erase();
1346       } else {
1347         command.assign(command_string, 1, end_quote_pos - 1);
1348         if (end_quote_pos + 1 < command_string.size())
1349           command_string.erase(0, command_string.find_first_not_of(
1350                                       k_white_space, end_quote_pos + 1));
1351         else
1352           command_string.erase();
1353       }
1354     } else {
1355       const size_t first_space_pos =
1356           command_string.find_first_of(k_white_space);
1357       if (first_space_pos == std::string::npos) {
1358         command.swap(command_string);
1359         command_string.erase();
1360       } else {
1361         command.assign(command_string, 0, first_space_pos);
1362         command_string.erase(0, command_string.find_first_not_of(
1363                                     k_white_space, first_space_pos));
1364       }
1365     }
1366     result = true;
1367   }
1368 
1369   if (!command.empty()) {
1370     // actual commands can't start with '-' or '_'
1371     if (command[0] != '-' && command[0] != '_') {
1372       size_t pos = command.find_first_not_of(k_valid_command_chars);
1373       if (pos > 0 && pos != std::string::npos) {
1374         suffix.assign(command.begin() + pos, command.end());
1375         command.erase(pos);
1376       }
1377     }
1378   }
1379 
1380   return result;
1381 }
1382 
1383 CommandObject *CommandInterpreter::BuildAliasResult(
1384     llvm::StringRef alias_name, std::string &raw_input_string,
1385     std::string &alias_result, CommandReturnObject &result) {
1386   CommandObject *alias_cmd_obj = nullptr;
1387   Args cmd_args(raw_input_string);
1388   alias_cmd_obj = GetCommandObject(alias_name);
1389   StreamString result_str;
1390 
1391   if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1392     alias_result.clear();
1393     return alias_cmd_obj;
1394   }
1395   std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1396       ((CommandAlias *)alias_cmd_obj)->Desugar();
1397   OptionArgVectorSP option_arg_vector_sp = desugared.second;
1398   alias_cmd_obj = desugared.first.get();
1399   std::string alias_name_str = alias_name;
1400   if ((cmd_args.GetArgumentCount() == 0) ||
1401       (alias_name_str != cmd_args.GetArgumentAtIndex(0)))
1402     cmd_args.Unshift(alias_name_str);
1403 
1404   result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
1405 
1406   if (!option_arg_vector_sp.get()) {
1407     alias_result = result_str.GetString();
1408     return alias_cmd_obj;
1409   }
1410   OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1411 
1412   int value_type;
1413   std::string option;
1414   std::string value;
1415   for (const auto &entry : *option_arg_vector) {
1416     std::tie(option, value_type, value) = entry;
1417     if (option == "<argument>") {
1418       result_str.Printf(" %s", value.c_str());
1419       continue;
1420     }
1421 
1422     result_str.Printf(" %s", option.c_str());
1423     if (value_type == OptionParser::eNoArgument)
1424       continue;
1425 
1426     if (value_type != OptionParser::eOptionalArgument)
1427       result_str.Printf(" ");
1428     int index = GetOptionArgumentPosition(value.c_str());
1429     if (index == 0)
1430       result_str.Printf("%s", value.c_str());
1431     else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1432 
1433       result.AppendErrorWithFormat("Not enough arguments provided; you "
1434                                    "need at least %d arguments to use "
1435                                    "this alias.\n",
1436                                    index);
1437       result.SetStatus(eReturnStatusFailed);
1438       return nullptr;
1439     } else {
1440       size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1441       if (strpos != std::string::npos)
1442         raw_input_string = raw_input_string.erase(
1443             strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1444       result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
1445     }
1446   }
1447 
1448   alias_result = result_str.GetString();
1449   return alias_cmd_obj;
1450 }
1451 
1452 Status CommandInterpreter::PreprocessCommand(std::string &command) {
1453   // The command preprocessor needs to do things to the command line before any
1454   // parsing of arguments or anything else is done. The only current stuff that
1455   // gets preprocessed is anything enclosed in backtick ('`') characters is
1456   // evaluated as an expression and the result of the expression must be a
1457   // scalar that can be substituted into the command. An example would be:
1458   // (lldb) memory read `$rsp + 20`
1459   Status error; // Status for any expressions that might not evaluate
1460   size_t start_backtick;
1461   size_t pos = 0;
1462   while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1463     // Stop if an error was encountered during the previous iteration.
1464     if (error.Fail())
1465       break;
1466 
1467     if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
1468       // The backtick was preceded by a '\' character, remove the slash and
1469       // don't treat the backtick as the start of an expression.
1470       command.erase(start_backtick - 1, 1);
1471       // No need to add one to start_backtick since we just deleted a char.
1472       pos = start_backtick;
1473       continue;
1474     }
1475 
1476     const size_t expr_content_start = start_backtick + 1;
1477     const size_t end_backtick = command.find('`', expr_content_start);
1478 
1479     if (end_backtick == std::string::npos) {
1480       // Stop if there's no end backtick.
1481       break;
1482     }
1483 
1484     if (end_backtick == expr_content_start) {
1485       // Skip over empty expression. (two backticks in a row)
1486       command.erase(start_backtick, 2);
1487       continue;
1488     }
1489 
1490     std::string expr_str(command, expr_content_start,
1491                          end_backtick - expr_content_start);
1492 
1493     ExecutionContext exe_ctx(GetExecutionContext());
1494     Target *target = exe_ctx.GetTargetPtr();
1495 
1496     // Get a dummy target to allow for calculator mode while processing
1497     // backticks. This also helps break the infinite loop caused when target is
1498     // null.
1499     if (!target)
1500       target = m_debugger.GetDummyTarget();
1501 
1502     if (!target)
1503       continue;
1504 
1505     ValueObjectSP expr_result_valobj_sp;
1506 
1507     EvaluateExpressionOptions options;
1508     options.SetCoerceToId(false);
1509     options.SetUnwindOnError(true);
1510     options.SetIgnoreBreakpoints(true);
1511     options.SetKeepInMemory(false);
1512     options.SetTryAllThreads(true);
1513     options.SetTimeout(llvm::None);
1514 
1515     ExpressionResults expr_result =
1516         target->EvaluateExpression(expr_str.c_str(), exe_ctx.GetFramePtr(),
1517                                    expr_result_valobj_sp, options);
1518 
1519     if (expr_result == eExpressionCompleted) {
1520       Scalar scalar;
1521       if (expr_result_valobj_sp)
1522         expr_result_valobj_sp =
1523             expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1524                 expr_result_valobj_sp->GetDynamicValueType(), true);
1525       if (expr_result_valobj_sp->ResolveValue(scalar)) {
1526         command.erase(start_backtick, end_backtick - start_backtick + 1);
1527         StreamString value_strm;
1528         const bool show_type = false;
1529         scalar.GetValue(&value_strm, show_type);
1530         size_t value_string_size = value_strm.GetSize();
1531         if (value_string_size) {
1532           command.insert(start_backtick, value_strm.GetString());
1533           pos = start_backtick + value_string_size;
1534           continue;
1535         } else {
1536           error.SetErrorStringWithFormat("expression value didn't result "
1537                                          "in a scalar value for the "
1538                                          "expression '%s'",
1539                                          expr_str.c_str());
1540           break;
1541         }
1542       } else {
1543         error.SetErrorStringWithFormat("expression value didn't result "
1544                                        "in a scalar value for the "
1545                                        "expression '%s'",
1546                                        expr_str.c_str());
1547         break;
1548       }
1549 
1550       continue;
1551     }
1552 
1553     if (expr_result_valobj_sp)
1554       error = expr_result_valobj_sp->GetError();
1555 
1556     if (error.Success()) {
1557       switch (expr_result) {
1558       case eExpressionSetupError:
1559         error.SetErrorStringWithFormat(
1560             "expression setup error for the expression '%s'", expr_str.c_str());
1561         break;
1562       case eExpressionParseError:
1563         error.SetErrorStringWithFormat(
1564             "expression parse error for the expression '%s'", expr_str.c_str());
1565         break;
1566       case eExpressionResultUnavailable:
1567         error.SetErrorStringWithFormat(
1568             "expression error fetching result for the expression '%s'",
1569             expr_str.c_str());
1570         break;
1571       case eExpressionCompleted:
1572         break;
1573       case eExpressionDiscarded:
1574         error.SetErrorStringWithFormat(
1575             "expression discarded for the expression '%s'", expr_str.c_str());
1576         break;
1577       case eExpressionInterrupted:
1578         error.SetErrorStringWithFormat(
1579             "expression interrupted for the expression '%s'", expr_str.c_str());
1580         break;
1581       case eExpressionHitBreakpoint:
1582         error.SetErrorStringWithFormat(
1583             "expression hit breakpoint for the expression '%s'",
1584             expr_str.c_str());
1585         break;
1586       case eExpressionTimedOut:
1587         error.SetErrorStringWithFormat(
1588             "expression timed out for the expression '%s'", expr_str.c_str());
1589         break;
1590       case eExpressionStoppedForDebug:
1591         error.SetErrorStringWithFormat("expression stop at entry point "
1592                                        "for debugging for the "
1593                                        "expression '%s'",
1594                                        expr_str.c_str());
1595         break;
1596       }
1597     }
1598   }
1599   return error;
1600 }
1601 
1602 bool CommandInterpreter::HandleCommand(const char *command_line,
1603                                        LazyBool lazy_add_to_history,
1604                                        CommandReturnObject &result,
1605                                        ExecutionContext *override_context,
1606                                        bool repeat_on_empty_command,
1607                                        bool no_context_switching)
1608 
1609 {
1610 
1611   std::string command_string(command_line);
1612   std::string original_command_string(command_line);
1613 
1614   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
1615   llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
1616                                    command_line);
1617 
1618   if (log)
1619     log->Printf("Processing command: %s", command_line);
1620 
1621   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1622   Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
1623 
1624   if (!no_context_switching)
1625     UpdateExecutionContext(override_context);
1626 
1627   if (WasInterrupted()) {
1628     result.AppendError("interrupted");
1629     result.SetStatus(eReturnStatusFailed);
1630     return false;
1631   }
1632 
1633   bool add_to_history;
1634   if (lazy_add_to_history == eLazyBoolCalculate)
1635     add_to_history = (m_command_source_depth == 0);
1636   else
1637     add_to_history = (lazy_add_to_history == eLazyBoolYes);
1638 
1639   bool empty_command = false;
1640   bool comment_command = false;
1641   if (command_string.empty())
1642     empty_command = true;
1643   else {
1644     const char *k_space_characters = "\t\n\v\f\r ";
1645 
1646     size_t non_space = command_string.find_first_not_of(k_space_characters);
1647     // Check for empty line or comment line (lines whose first non-space
1648     // character is the comment character for this interpreter)
1649     if (non_space == std::string::npos)
1650       empty_command = true;
1651     else if (command_string[non_space] == m_comment_char)
1652       comment_command = true;
1653     else if (command_string[non_space] == CommandHistory::g_repeat_char) {
1654       llvm::StringRef search_str(command_string);
1655       search_str = search_str.drop_front(non_space);
1656       if (auto hist_str = m_command_history.FindString(search_str)) {
1657         add_to_history = false;
1658         command_string = *hist_str;
1659         original_command_string = *hist_str;
1660       } else {
1661         result.AppendErrorWithFormat("Could not find entry: %s in history",
1662                                      command_string.c_str());
1663         result.SetStatus(eReturnStatusFailed);
1664         return false;
1665       }
1666     }
1667   }
1668 
1669   if (empty_command) {
1670     if (repeat_on_empty_command) {
1671       if (m_command_history.IsEmpty()) {
1672         result.AppendError("empty command");
1673         result.SetStatus(eReturnStatusFailed);
1674         return false;
1675       } else {
1676         command_line = m_repeat_command.c_str();
1677         command_string = command_line;
1678         original_command_string = command_line;
1679         if (m_repeat_command.empty()) {
1680           result.AppendErrorWithFormat("No auto repeat.\n");
1681           result.SetStatus(eReturnStatusFailed);
1682           return false;
1683         }
1684       }
1685       add_to_history = false;
1686     } else {
1687       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1688       return true;
1689     }
1690   } else if (comment_command) {
1691     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1692     return true;
1693   }
1694 
1695   Status error(PreprocessCommand(command_string));
1696 
1697   if (error.Fail()) {
1698     result.AppendError(error.AsCString());
1699     result.SetStatus(eReturnStatusFailed);
1700     return false;
1701   }
1702 
1703   // Phase 1.
1704 
1705   // Before we do ANY kind of argument processing, we need to figure out what
1706   // the real/final command object is for the specified command.  This gets
1707   // complicated by the fact that the user could have specified an alias, and,
1708   // in translating the alias, there may also be command options and/or even
1709   // data (including raw text strings) that need to be found and inserted into
1710   // the command line as part of the translation.  So this first step is plain
1711   // look-up and replacement, resulting in:
1712   //    1. the command object whose Execute method will actually be called
1713   //    2. a revised command string, with all substitutions and replacements
1714   //       taken care of
1715   // From 1 above, we can determine whether the Execute function wants raw
1716   // input or not.
1717 
1718   CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1719 
1720   // Although the user may have abbreviated the command, the command_string now
1721   // has the command expanded to the full name.  For example, if the input was
1722   // "br s -n main", command_string is now "breakpoint set -n main".
1723   if (log) {
1724     llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1725     log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
1726     log->Printf("HandleCommand, (revised) command_string: '%s'",
1727                 command_string.c_str());
1728     const bool wants_raw_input =
1729         (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1730     log->Printf("HandleCommand, wants_raw_input:'%s'",
1731                 wants_raw_input ? "True" : "False");
1732   }
1733 
1734   // Phase 2.
1735   // Take care of things like setting up the history command & calling the
1736   // appropriate Execute method on the CommandObject, with the appropriate
1737   // arguments.
1738 
1739   if (cmd_obj != nullptr) {
1740     if (add_to_history) {
1741       Args command_args(command_string);
1742       const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1743       if (repeat_command != nullptr)
1744         m_repeat_command.assign(repeat_command);
1745       else
1746         m_repeat_command.assign(original_command_string);
1747 
1748       m_command_history.AppendString(original_command_string);
1749     }
1750 
1751     std::string remainder;
1752     const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
1753     if (actual_cmd_name_len < command_string.length())
1754       remainder = command_string.substr(actual_cmd_name_len);
1755 
1756     // Remove any initial spaces
1757     size_t pos = remainder.find_first_not_of(k_white_space);
1758     if (pos != 0 && pos != std::string::npos)
1759       remainder.erase(0, pos);
1760 
1761     if (log)
1762       log->Printf(
1763           "HandleCommand, command line after removing command name(s): '%s'",
1764           remainder.c_str());
1765 
1766     cmd_obj->Execute(remainder.c_str(), result);
1767   }
1768 
1769   if (log)
1770     log->Printf("HandleCommand, command %s",
1771                 (result.Succeeded() ? "succeeded" : "did not succeed"));
1772 
1773   return result.Succeeded();
1774 }
1775 
1776 int CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
1777   int num_command_matches = 0;
1778   bool look_for_subcommand = false;
1779 
1780   // For any of the command completions a unique match will be a complete word.
1781   request.SetWordComplete(true);
1782 
1783   if (request.GetCursorIndex() == -1) {
1784     // We got nothing on the command line, so return the list of commands
1785     bool include_aliases = true;
1786     StringList new_matches, descriptions;
1787     num_command_matches = GetCommandNamesMatchingPartialString(
1788         "", include_aliases, new_matches, descriptions);
1789     request.AddCompletions(new_matches, descriptions);
1790   } else if (request.GetCursorIndex() == 0) {
1791     // The cursor is in the first argument, so just do a lookup in the
1792     // dictionary.
1793     StringList new_matches, new_descriptions;
1794     CommandObject *cmd_obj =
1795         GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1796                          &new_matches, &new_descriptions);
1797 
1798     if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1799         new_matches.GetStringAtIndex(0) != nullptr &&
1800         strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
1801                new_matches.GetStringAtIndex(0)) == 0) {
1802       if (request.GetParsedLine().GetArgumentCount() == 1) {
1803         request.SetWordComplete(true);
1804       } else {
1805         look_for_subcommand = true;
1806         num_command_matches = 0;
1807         new_matches.DeleteStringAtIndex(0);
1808         new_descriptions.DeleteStringAtIndex(0);
1809         request.GetParsedLine().AppendArgument(llvm::StringRef());
1810         request.SetCursorIndex(request.GetCursorIndex() + 1);
1811         request.SetCursorCharPosition(0);
1812       }
1813     }
1814     request.AddCompletions(new_matches, new_descriptions);
1815     num_command_matches = request.GetNumberOfMatches();
1816   }
1817 
1818   if (request.GetCursorIndex() > 0 || look_for_subcommand) {
1819     // We are completing further on into a commands arguments, so find the
1820     // command and tell it to complete the command. First see if there is a
1821     // matching initial command:
1822     CommandObject *command_object =
1823         GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
1824     if (command_object == nullptr) {
1825       return 0;
1826     } else {
1827       request.GetParsedLine().Shift();
1828       request.SetCursorIndex(request.GetCursorIndex() - 1);
1829       num_command_matches = command_object->HandleCompletion(request);
1830     }
1831   }
1832 
1833   return num_command_matches;
1834 }
1835 
1836 int CommandInterpreter::HandleCompletion(
1837     const char *current_line, const char *cursor, const char *last_char,
1838     int match_start_point, int max_return_elements, StringList &matches,
1839     StringList &descriptions) {
1840 
1841   llvm::StringRef command_line(current_line, last_char - current_line);
1842   CompletionResult result;
1843   CompletionRequest request(command_line, cursor - current_line,
1844                             match_start_point, max_return_elements, result);
1845   // Don't complete comments, and if the line we are completing is just the
1846   // history repeat character, substitute the appropriate history line.
1847   const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
1848   if (first_arg) {
1849     if (first_arg[0] == m_comment_char)
1850       return 0;
1851     else if (first_arg[0] == CommandHistory::g_repeat_char) {
1852       if (auto hist_str = m_command_history.FindString(first_arg)) {
1853         matches.InsertStringAtIndex(0, *hist_str);
1854         descriptions.InsertStringAtIndex(0, "Previous command history event");
1855         return -2;
1856       } else
1857         return 0;
1858     }
1859   }
1860 
1861   // Only max_return_elements == -1 is supported at present:
1862   lldbassert(max_return_elements == -1);
1863 
1864   int num_command_matches = HandleCompletionMatches(request);
1865   result.GetMatches(matches);
1866   result.GetDescriptions(descriptions);
1867 
1868   if (num_command_matches <= 0)
1869     return num_command_matches;
1870 
1871   if (request.GetParsedLine().GetArgumentCount() == 0) {
1872     // If we got an empty string, insert nothing.
1873     matches.InsertStringAtIndex(0, "");
1874     descriptions.InsertStringAtIndex(0, "");
1875   } else {
1876     // Now figure out if there is a common substring, and if so put that in
1877     // element 0, otherwise put an empty string in element 0.
1878     std::string command_partial_str = request.GetCursorArgumentPrefix().str();
1879 
1880     std::string common_prefix;
1881     matches.LongestCommonPrefix(common_prefix);
1882     const size_t partial_name_len = command_partial_str.size();
1883     common_prefix.erase(0, partial_name_len);
1884 
1885     // If we matched a unique single command, add a space... Only do this if
1886     // the completer told us this was a complete word, however...
1887     if (num_command_matches == 1 && request.GetWordComplete()) {
1888       char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
1889       common_prefix =
1890           Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1891       if (quote_char != '\0')
1892         common_prefix.push_back(quote_char);
1893       common_prefix.push_back(' ');
1894     }
1895     matches.InsertStringAtIndex(0, common_prefix.c_str());
1896     descriptions.InsertStringAtIndex(0, "");
1897   }
1898   return num_command_matches;
1899 }
1900 
1901 CommandInterpreter::~CommandInterpreter() {}
1902 
1903 void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
1904   EventSP prompt_change_event_sp(
1905       new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1906   ;
1907   BroadcastEvent(prompt_change_event_sp);
1908   if (m_command_io_handler_sp)
1909     m_command_io_handler_sp->SetPrompt(new_prompt);
1910 }
1911 
1912 bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
1913   // Check AutoConfirm first:
1914   if (m_debugger.GetAutoConfirm())
1915     return default_answer;
1916 
1917   IOHandlerConfirm *confirm =
1918       new IOHandlerConfirm(m_debugger, message, default_answer);
1919   IOHandlerSP io_handler_sp(confirm);
1920   m_debugger.RunIOHandler(io_handler_sp);
1921   return confirm->GetResponse();
1922 }
1923 
1924 const CommandAlias *
1925 CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
1926   OptionArgVectorSP ret_val;
1927 
1928   auto pos = m_alias_dict.find(alias_name);
1929   if (pos != m_alias_dict.end())
1930     return (CommandAlias *)pos->second.get();
1931 
1932   return nullptr;
1933 }
1934 
1935 bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
1936 
1937 bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
1938 
1939 bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
1940 
1941 bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
1942 
1943 void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
1944                                                const char *alias_name,
1945                                                Args &cmd_args,
1946                                                std::string &raw_input_string,
1947                                                CommandReturnObject &result) {
1948   OptionArgVectorSP option_arg_vector_sp =
1949       GetAlias(alias_name)->GetOptionArguments();
1950 
1951   bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1952 
1953   // Make sure that the alias name is the 0th element in cmd_args
1954   std::string alias_name_str = alias_name;
1955   if (alias_name_str != cmd_args.GetArgumentAtIndex(0))
1956     cmd_args.Unshift(alias_name_str);
1957 
1958   Args new_args(alias_cmd_obj->GetCommandName());
1959   if (new_args.GetArgumentCount() == 2)
1960     new_args.Shift();
1961 
1962   if (option_arg_vector_sp.get()) {
1963     if (wants_raw_input) {
1964       // We have a command that both has command options and takes raw input.
1965       // Make *sure* it has a " -- " in the right place in the
1966       // raw_input_string.
1967       size_t pos = raw_input_string.find(" -- ");
1968       if (pos == std::string::npos) {
1969         // None found; assume it goes at the beginning of the raw input string
1970         raw_input_string.insert(0, " -- ");
1971       }
1972     }
1973 
1974     OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1975     const size_t old_size = cmd_args.GetArgumentCount();
1976     std::vector<bool> used(old_size + 1, false);
1977 
1978     used[0] = true;
1979 
1980     int value_type;
1981     std::string option;
1982     std::string value;
1983     for (const auto &option_entry : *option_arg_vector) {
1984       std::tie(option, value_type, value) = option_entry;
1985       if (option == "<argument>") {
1986         if (!wants_raw_input || (value != "--")) {
1987           // Since we inserted this above, make sure we don't insert it twice
1988           new_args.AppendArgument(value);
1989         }
1990         continue;
1991       }
1992 
1993       if (value_type != OptionParser::eOptionalArgument)
1994         new_args.AppendArgument(option);
1995 
1996       if (value == "<no-argument>")
1997         continue;
1998 
1999       int index = GetOptionArgumentPosition(value.c_str());
2000       if (index == 0) {
2001         // value was NOT a positional argument; must be a real value
2002         if (value_type != OptionParser::eOptionalArgument)
2003           new_args.AppendArgument(value);
2004         else {
2005           char buffer[255];
2006           ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2007                      value.c_str());
2008           new_args.AppendArgument(llvm::StringRef(buffer));
2009         }
2010 
2011       } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
2012         result.AppendErrorWithFormat("Not enough arguments provided; you "
2013                                      "need at least %d arguments to use "
2014                                      "this alias.\n",
2015                                      index);
2016         result.SetStatus(eReturnStatusFailed);
2017         return;
2018       } else {
2019         // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2020         size_t strpos =
2021             raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2022         if (strpos != std::string::npos) {
2023           raw_input_string = raw_input_string.erase(
2024               strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2025         }
2026 
2027         if (value_type != OptionParser::eOptionalArgument)
2028           new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2029         else {
2030           char buffer[255];
2031           ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2032                      cmd_args.GetArgumentAtIndex(index));
2033           new_args.AppendArgument(buffer);
2034         }
2035         used[index] = true;
2036       }
2037     }
2038 
2039     for (auto entry : llvm::enumerate(cmd_args.entries())) {
2040       if (!used[entry.index()] && !wants_raw_input)
2041         new_args.AppendArgument(entry.value().ref);
2042     }
2043 
2044     cmd_args.Clear();
2045     cmd_args.SetArguments(new_args.GetArgumentCount(),
2046                           new_args.GetConstArgumentVector());
2047   } else {
2048     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2049     // This alias was not created with any options; nothing further needs to be
2050     // done, unless it is a command that wants raw input, in which case we need
2051     // to clear the rest of the data from cmd_args, since its in the raw input
2052     // string.
2053     if (wants_raw_input) {
2054       cmd_args.Clear();
2055       cmd_args.SetArguments(new_args.GetArgumentCount(),
2056                             new_args.GetConstArgumentVector());
2057     }
2058     return;
2059   }
2060 
2061   result.SetStatus(eReturnStatusSuccessFinishNoResult);
2062   return;
2063 }
2064 
2065 int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2066   int position = 0; // Any string that isn't an argument position, i.e. '%'
2067                     // followed by an integer, gets a position
2068                     // of zero.
2069 
2070   const char *cptr = in_string;
2071 
2072   // Does it start with '%'
2073   if (cptr[0] == '%') {
2074     ++cptr;
2075 
2076     // Is the rest of it entirely digits?
2077     if (isdigit(cptr[0])) {
2078       const char *start = cptr;
2079       while (isdigit(cptr[0]))
2080         ++cptr;
2081 
2082       // We've gotten to the end of the digits; are we at the end of the
2083       // string?
2084       if (cptr[0] == '\0')
2085         position = atoi(start);
2086     }
2087   }
2088 
2089   return position;
2090 }
2091 
2092 void CommandInterpreter::SourceInitFile(bool in_cwd,
2093                                         CommandReturnObject &result) {
2094   FileSpec init_file;
2095   if (in_cwd) {
2096     ExecutionContext exe_ctx(GetExecutionContext());
2097     Target *target = exe_ctx.GetTargetPtr();
2098     if (target) {
2099       // In the current working directory we don't load any program specific
2100       // .lldbinit files, we only look for a ".lldbinit" file.
2101       if (m_skip_lldbinit_files)
2102         return;
2103 
2104       LoadCWDlldbinitFile should_load =
2105           target->TargetProperties::GetLoadCWDlldbinitFile();
2106       if (should_load == eLoadCWDlldbinitWarn) {
2107         FileSpec dot_lldb(".lldbinit");
2108         FileSystem::Instance().Resolve(dot_lldb);
2109         llvm::SmallString<64> home_dir_path;
2110         llvm::sys::path::home_directory(home_dir_path);
2111         FileSpec homedir_dot_lldb(home_dir_path.c_str());
2112         homedir_dot_lldb.AppendPathComponent(".lldbinit");
2113         FileSystem::Instance().Resolve(homedir_dot_lldb);
2114         if (FileSystem::Instance().Exists(dot_lldb) &&
2115             dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2116           result.AppendErrorWithFormat(
2117               "There is a .lldbinit file in the current directory which is not "
2118               "being read.\n"
2119               "To silence this warning without sourcing in the local "
2120               ".lldbinit,\n"
2121               "add the following to the lldbinit file in your home directory:\n"
2122               "    settings set target.load-cwd-lldbinit false\n"
2123               "To allow lldb to source .lldbinit files in the current working "
2124               "directory,\n"
2125               "set the value of this variable to true.  Only do so if you "
2126               "understand and\n"
2127               "accept the security risk.");
2128           result.SetStatus(eReturnStatusFailed);
2129           return;
2130         }
2131       } else if (should_load == eLoadCWDlldbinitTrue) {
2132         init_file.SetFile("./.lldbinit", FileSpec::Style::native);
2133         FileSystem::Instance().Resolve(init_file);
2134       }
2135     }
2136   } else {
2137     // If we aren't looking in the current working directory we are looking in
2138     // the home directory. We will first see if there is an application
2139     // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2140     // and the name of the program. If this file doesn't exist, we fall back to
2141     // just the "~/.lldbinit" file. We also obey any requests to not load the
2142     // init files.
2143     llvm::SmallString<64> home_dir_path;
2144     llvm::sys::path::home_directory(home_dir_path);
2145     FileSpec profilePath(home_dir_path.c_str());
2146     profilePath.AppendPathComponent(".lldbinit");
2147     std::string init_file_path = profilePath.GetPath();
2148 
2149     if (!m_skip_app_init_files) {
2150       FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2151       const char *program_name = program_file_spec.GetFilename().AsCString();
2152 
2153       if (program_name) {
2154         char program_init_file_name[PATH_MAX];
2155         ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2156                    "%s-%s", init_file_path.c_str(), program_name);
2157         init_file.SetFile(program_init_file_name, FileSpec::Style::native);
2158         FileSystem::Instance().Resolve(init_file);
2159         if (!FileSystem::Instance().Exists(init_file))
2160           init_file.Clear();
2161       }
2162     }
2163 
2164     if (!init_file && !m_skip_lldbinit_files)
2165       init_file.SetFile(init_file_path, FileSpec::Style::native);
2166   }
2167 
2168   // If the file exists, tell HandleCommand to 'source' it; this will do the
2169   // actual broadcasting of the commands back to any appropriate listener (see
2170   // CommandObjectSource::Execute for more details).
2171 
2172   if (FileSystem::Instance().Exists(init_file)) {
2173     const bool saved_batch = SetBatchCommandMode(true);
2174     CommandInterpreterRunOptions options;
2175     options.SetSilent(true);
2176     options.SetStopOnError(false);
2177     options.SetStopOnContinue(true);
2178 
2179     HandleCommandsFromFile(init_file,
2180                            nullptr, // Execution context
2181                            options, result);
2182     SetBatchCommandMode(saved_batch);
2183   } else {
2184     // nothing to be done if the file doesn't exist
2185     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2186   }
2187 }
2188 
2189 const char *CommandInterpreter::GetCommandPrefix() {
2190   const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2191   return prefix == NULL ? "" : prefix;
2192 }
2193 
2194 PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2195   PlatformSP platform_sp;
2196   if (prefer_target_platform) {
2197     ExecutionContext exe_ctx(GetExecutionContext());
2198     Target *target = exe_ctx.GetTargetPtr();
2199     if (target)
2200       platform_sp = target->GetPlatform();
2201   }
2202 
2203   if (!platform_sp)
2204     platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2205   return platform_sp;
2206 }
2207 
2208 void CommandInterpreter::HandleCommands(const StringList &commands,
2209                                         ExecutionContext *override_context,
2210                                         CommandInterpreterRunOptions &options,
2211                                         CommandReturnObject &result) {
2212   size_t num_lines = commands.GetSize();
2213 
2214   // If we are going to continue past a "continue" then we need to run the
2215   // commands synchronously. Make sure you reset this value anywhere you return
2216   // from the function.
2217 
2218   bool old_async_execution = m_debugger.GetAsyncExecution();
2219 
2220   // If we've been given an execution context, set it at the start, but don't
2221   // keep resetting it or we will cause series of commands that change the
2222   // context, then do an operation that relies on that context to fail.
2223 
2224   if (override_context != nullptr)
2225     UpdateExecutionContext(override_context);
2226 
2227   if (!options.GetStopOnContinue()) {
2228     m_debugger.SetAsyncExecution(false);
2229   }
2230 
2231   for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
2232     const char *cmd = commands.GetStringAtIndex(idx);
2233     if (cmd[0] == '\0')
2234       continue;
2235 
2236     if (options.GetEchoCommands()) {
2237       // TODO: Add Stream support.
2238       result.AppendMessageWithFormat("%s %s\n",
2239                                      m_debugger.GetPrompt().str().c_str(), cmd);
2240     }
2241 
2242     CommandReturnObject tmp_result;
2243     // If override_context is not NULL, pass no_context_switching = true for
2244     // HandleCommand() since we updated our context already.
2245 
2246     // We might call into a regex or alias command, in which case the
2247     // add_to_history will get lost.  This m_command_source_depth dingus is the
2248     // way we turn off adding to the history in that case, so set it up here.
2249     if (!options.GetAddToHistory())
2250       m_command_source_depth++;
2251     bool success =
2252         HandleCommand(cmd, options.m_add_to_history, tmp_result,
2253                       nullptr, /* override_context */
2254                       true,    /* repeat_on_empty_command */
2255                       override_context != nullptr /* no_context_switching */);
2256     if (!options.GetAddToHistory())
2257       m_command_source_depth--;
2258 
2259     if (options.GetPrintResults()) {
2260       if (tmp_result.Succeeded())
2261         result.AppendMessage(tmp_result.GetOutputData());
2262     }
2263 
2264     if (!success || !tmp_result.Succeeded()) {
2265       llvm::StringRef error_msg = tmp_result.GetErrorData();
2266       if (error_msg.empty())
2267         error_msg = "<unknown error>.\n";
2268       if (options.GetStopOnError()) {
2269         result.AppendErrorWithFormat(
2270             "Aborting reading of commands after command #%" PRIu64
2271             ": '%s' failed with %s",
2272             (uint64_t)idx, cmd, error_msg.str().c_str());
2273         result.SetStatus(eReturnStatusFailed);
2274         m_debugger.SetAsyncExecution(old_async_execution);
2275         return;
2276       } else if (options.GetPrintResults()) {
2277         result.AppendMessageWithFormat(
2278             "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2279             error_msg.str().c_str());
2280       }
2281     }
2282 
2283     if (result.GetImmediateOutputStream())
2284       result.GetImmediateOutputStream()->Flush();
2285 
2286     if (result.GetImmediateErrorStream())
2287       result.GetImmediateErrorStream()->Flush();
2288 
2289     // N.B. Can't depend on DidChangeProcessState, because the state coming
2290     // into the command execution could be running (for instance in Breakpoint
2291     // Commands. So we check the return value to see if it is has running in
2292     // it.
2293     if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2294         (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2295       if (options.GetStopOnContinue()) {
2296         // If we caused the target to proceed, and we're going to stop in that
2297         // case, set the status in our real result before returning.  This is
2298         // an error if the continue was not the last command in the set of
2299         // commands to be run.
2300         if (idx != num_lines - 1)
2301           result.AppendErrorWithFormat(
2302               "Aborting reading of commands after command #%" PRIu64
2303               ": '%s' continued the target.\n",
2304               (uint64_t)idx + 1, cmd);
2305         else
2306           result.AppendMessageWithFormat("Command #%" PRIu64
2307                                          " '%s' continued the target.\n",
2308                                          (uint64_t)idx + 1, cmd);
2309 
2310         result.SetStatus(tmp_result.GetStatus());
2311         m_debugger.SetAsyncExecution(old_async_execution);
2312 
2313         return;
2314       }
2315     }
2316 
2317     // Also check for "stop on crash here:
2318     bool should_stop = false;
2319     if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2320       TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2321       if (target_sp) {
2322         ProcessSP process_sp(target_sp->GetProcessSP());
2323         if (process_sp) {
2324           for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2325             StopReason reason = thread_sp->GetStopReason();
2326             if (reason == eStopReasonSignal || reason == eStopReasonException ||
2327                 reason == eStopReasonInstrumentation) {
2328               should_stop = true;
2329               break;
2330             }
2331           }
2332         }
2333       }
2334       if (should_stop) {
2335         if (idx != num_lines - 1)
2336           result.AppendErrorWithFormat(
2337               "Aborting reading of commands after command #%" PRIu64
2338               ": '%s' stopped with a signal or exception.\n",
2339               (uint64_t)idx + 1, cmd);
2340         else
2341           result.AppendMessageWithFormat(
2342               "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2343               (uint64_t)idx + 1, cmd);
2344 
2345         result.SetStatus(tmp_result.GetStatus());
2346         m_debugger.SetAsyncExecution(old_async_execution);
2347 
2348         return;
2349       }
2350     }
2351   }
2352 
2353   result.SetStatus(eReturnStatusSuccessFinishResult);
2354   m_debugger.SetAsyncExecution(old_async_execution);
2355 
2356   return;
2357 }
2358 
2359 // Make flags that we can pass into the IOHandler so our delegates can do the
2360 // right thing
2361 enum {
2362   eHandleCommandFlagStopOnContinue = (1u << 0),
2363   eHandleCommandFlagStopOnError = (1u << 1),
2364   eHandleCommandFlagEchoCommand = (1u << 2),
2365   eHandleCommandFlagEchoCommentCommand = (1u << 3),
2366   eHandleCommandFlagPrintResult = (1u << 4),
2367   eHandleCommandFlagStopOnCrash = (1u << 5)
2368 };
2369 
2370 void CommandInterpreter::HandleCommandsFromFile(
2371     FileSpec &cmd_file, ExecutionContext *context,
2372     CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2373   if (!FileSystem::Instance().Exists(cmd_file)) {
2374     result.AppendErrorWithFormat(
2375         "Error reading commands from file %s - file not found.\n",
2376         cmd_file.GetFilename().AsCString("<Unknown>"));
2377     result.SetStatus(eReturnStatusFailed);
2378     return;
2379   }
2380 
2381   StreamFileSP input_file_sp(new StreamFile());
2382   std::string cmd_file_path = cmd_file.GetPath();
2383   Status error = FileSystem::Instance().Open(input_file_sp->GetFile(), cmd_file,
2384                                              File::eOpenOptionRead);
2385 
2386   if (error.Fail()) {
2387     result.AppendErrorWithFormat(
2388         "error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(),
2389         error.AsCString());
2390     result.SetStatus(eReturnStatusFailed);
2391     return;
2392   }
2393 
2394   Debugger &debugger = GetDebugger();
2395 
2396   uint32_t flags = 0;
2397 
2398   if (options.m_stop_on_continue == eLazyBoolCalculate) {
2399     if (m_command_source_flags.empty()) {
2400       // Stop on continue by default
2401       flags |= eHandleCommandFlagStopOnContinue;
2402     } else if (m_command_source_flags.back() &
2403                eHandleCommandFlagStopOnContinue) {
2404       flags |= eHandleCommandFlagStopOnContinue;
2405     }
2406   } else if (options.m_stop_on_continue == eLazyBoolYes) {
2407     flags |= eHandleCommandFlagStopOnContinue;
2408   }
2409 
2410   if (options.m_stop_on_error == eLazyBoolCalculate) {
2411     if (m_command_source_flags.empty()) {
2412       if (GetStopCmdSourceOnError())
2413         flags |= eHandleCommandFlagStopOnError;
2414     } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2415       flags |= eHandleCommandFlagStopOnError;
2416     }
2417   } else if (options.m_stop_on_error == eLazyBoolYes) {
2418     flags |= eHandleCommandFlagStopOnError;
2419   }
2420 
2421   // stop-on-crash can only be set, if it is present in all levels of
2422   // pushed flag sets.
2423   if (options.GetStopOnCrash()) {
2424     if (m_command_source_flags.empty()) {
2425       flags |= eHandleCommandFlagStopOnCrash;
2426     } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2427       flags |= eHandleCommandFlagStopOnCrash;
2428     }
2429   }
2430 
2431   if (options.m_echo_commands == eLazyBoolCalculate) {
2432     if (m_command_source_flags.empty()) {
2433       // Echo command by default
2434       flags |= eHandleCommandFlagEchoCommand;
2435     } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2436       flags |= eHandleCommandFlagEchoCommand;
2437     }
2438   } else if (options.m_echo_commands == eLazyBoolYes) {
2439     flags |= eHandleCommandFlagEchoCommand;
2440   }
2441 
2442   // We will only ever ask for this flag, if we echo commands in general.
2443   if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2444     if (m_command_source_flags.empty()) {
2445       // Echo comments by default
2446       flags |= eHandleCommandFlagEchoCommentCommand;
2447     } else if (m_command_source_flags.back() &
2448                eHandleCommandFlagEchoCommentCommand) {
2449       flags |= eHandleCommandFlagEchoCommentCommand;
2450     }
2451   } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2452     flags |= eHandleCommandFlagEchoCommentCommand;
2453   }
2454 
2455   if (options.m_print_results == eLazyBoolCalculate) {
2456     if (m_command_source_flags.empty()) {
2457       // Print output by default
2458       flags |= eHandleCommandFlagPrintResult;
2459     } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2460       flags |= eHandleCommandFlagPrintResult;
2461     }
2462   } else if (options.m_print_results == eLazyBoolYes) {
2463     flags |= eHandleCommandFlagPrintResult;
2464   }
2465 
2466   if (flags & eHandleCommandFlagPrintResult) {
2467     debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2468                                      cmd_file_path.c_str());
2469   }
2470 
2471   // Used for inheriting the right settings when "command source" might
2472   // have nested "command source" commands
2473   lldb::StreamFileSP empty_stream_sp;
2474   m_command_source_flags.push_back(flags);
2475   IOHandlerSP io_handler_sp(new IOHandlerEditline(
2476       debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2477       empty_stream_sp, // Pass in an empty stream so we inherit the top
2478                        // input reader output stream
2479       empty_stream_sp, // Pass in an empty stream so we inherit the top
2480                        // input reader error stream
2481       flags,
2482       nullptr, // Pass in NULL for "editline_name" so no history is saved,
2483                // or written
2484       debugger.GetPrompt(), llvm::StringRef(),
2485       false, // Not multi-line
2486       debugger.GetUseColor(), 0, *this, nullptr));
2487   const bool old_async_execution = debugger.GetAsyncExecution();
2488 
2489   // Set synchronous execution if we are not stopping on continue
2490   if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2491     debugger.SetAsyncExecution(false);
2492 
2493   m_command_source_depth++;
2494 
2495   debugger.RunIOHandler(io_handler_sp);
2496   if (!m_command_source_flags.empty())
2497     m_command_source_flags.pop_back();
2498   m_command_source_depth--;
2499   result.SetStatus(eReturnStatusSuccessFinishNoResult);
2500   debugger.SetAsyncExecution(old_async_execution);
2501 }
2502 
2503 ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
2504   std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
2505   if (!m_script_interpreter_sp) {
2506     if (!can_create)
2507       return nullptr;
2508     lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2509     m_script_interpreter_sp =
2510         PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2511   }
2512   return m_script_interpreter_sp.get();
2513 }
2514 
2515 bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2516 
2517 void CommandInterpreter::SetSynchronous(bool value) {
2518   m_synchronous_execution = value;
2519 }
2520 
2521 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2522                                                  llvm::StringRef prefix,
2523                                                  llvm::StringRef help_text) {
2524   const uint32_t max_columns = m_debugger.GetTerminalWidth();
2525 
2526   size_t line_width_max = max_columns - prefix.size();
2527   if (line_width_max < 16)
2528     line_width_max = help_text.size() + prefix.size();
2529 
2530   strm.IndentMore(prefix.size());
2531   bool prefixed_yet = false;
2532   while (!help_text.empty()) {
2533     // Prefix the first line, indent subsequent lines to line up
2534     if (!prefixed_yet) {
2535       strm << prefix;
2536       prefixed_yet = true;
2537     } else
2538       strm.Indent();
2539 
2540     // Never print more than the maximum on one line.
2541     llvm::StringRef this_line = help_text.substr(0, line_width_max);
2542 
2543     // Always break on an explicit newline.
2544     std::size_t first_newline = this_line.find_first_of("\n");
2545 
2546     // Don't break on space/tab unless the text is too long to fit on one line.
2547     std::size_t last_space = llvm::StringRef::npos;
2548     if (this_line.size() != help_text.size())
2549       last_space = this_line.find_last_of(" \t");
2550 
2551     // Break at whichever condition triggered first.
2552     this_line = this_line.substr(0, std::min(first_newline, last_space));
2553     strm.PutCString(this_line);
2554     strm.EOL();
2555 
2556     // Remove whitespace / newlines after breaking.
2557     help_text = help_text.drop_front(this_line.size()).ltrim();
2558   }
2559   strm.IndentLess(prefix.size());
2560 }
2561 
2562 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2563                                                  llvm::StringRef word_text,
2564                                                  llvm::StringRef separator,
2565                                                  llvm::StringRef help_text,
2566                                                  size_t max_word_len) {
2567   StreamString prefix_stream;
2568   prefix_stream.Printf("  %-*s %*s ", (int)max_word_len, word_text.data(),
2569                        (int)separator.size(), separator.data());
2570   OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2571 }
2572 
2573 void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2574                                         llvm::StringRef separator,
2575                                         llvm::StringRef help_text,
2576                                         uint32_t max_word_len) {
2577   int indent_size = max_word_len + separator.size() + 2;
2578 
2579   strm.IndentMore(indent_size);
2580 
2581   StreamString text_strm;
2582   text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2583   text_strm << separator << " " << help_text;
2584 
2585   const uint32_t max_columns = m_debugger.GetTerminalWidth();
2586 
2587   llvm::StringRef text = text_strm.GetString();
2588 
2589   uint32_t chars_left = max_columns;
2590 
2591   auto nextWordLength = [](llvm::StringRef S) {
2592     size_t pos = S.find_first_of(' ');
2593     return pos == llvm::StringRef::npos ? S.size() : pos;
2594   };
2595 
2596   while (!text.empty()) {
2597     if (text.front() == '\n' ||
2598         (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
2599       strm.EOL();
2600       strm.Indent();
2601       chars_left = max_columns - indent_size;
2602       if (text.front() == '\n')
2603         text = text.drop_front();
2604       else
2605         text = text.ltrim(' ');
2606     } else {
2607       strm.PutChar(text.front());
2608       --chars_left;
2609       text = text.drop_front();
2610     }
2611   }
2612 
2613   strm.EOL();
2614   strm.IndentLess(indent_size);
2615 }
2616 
2617 void CommandInterpreter::FindCommandsForApropos(
2618     llvm::StringRef search_word, StringList &commands_found,
2619     StringList &commands_help, CommandObject::CommandMap &command_map) {
2620   CommandObject::CommandMap::const_iterator pos;
2621 
2622   for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
2623     llvm::StringRef command_name = pos->first;
2624     CommandObject *cmd_obj = pos->second.get();
2625 
2626     const bool search_short_help = true;
2627     const bool search_long_help = false;
2628     const bool search_syntax = false;
2629     const bool search_options = false;
2630     if (command_name.contains_lower(search_word) ||
2631         cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2632                                       search_long_help, search_syntax,
2633                                       search_options)) {
2634       commands_found.AppendString(cmd_obj->GetCommandName());
2635       commands_help.AppendString(cmd_obj->GetHelp());
2636     }
2637 
2638     if (cmd_obj->IsMultiwordObject()) {
2639       CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2640       FindCommandsForApropos(search_word, commands_found, commands_help,
2641                              cmd_multiword->GetSubcommandDictionary());
2642     }
2643   }
2644 }
2645 
2646 void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
2647                                                 StringList &commands_found,
2648                                                 StringList &commands_help,
2649                                                 bool search_builtin_commands,
2650                                                 bool search_user_commands,
2651                                                 bool search_alias_commands) {
2652   CommandObject::CommandMap::const_iterator pos;
2653 
2654   if (search_builtin_commands)
2655     FindCommandsForApropos(search_word, commands_found, commands_help,
2656                            m_command_dict);
2657 
2658   if (search_user_commands)
2659     FindCommandsForApropos(search_word, commands_found, commands_help,
2660                            m_user_dict);
2661 
2662   if (search_alias_commands)
2663     FindCommandsForApropos(search_word, commands_found, commands_help,
2664                            m_alias_dict);
2665 }
2666 
2667 void CommandInterpreter::UpdateExecutionContext(
2668     ExecutionContext *override_context) {
2669   if (override_context != nullptr) {
2670     m_exe_ctx_ref = *override_context;
2671   } else {
2672     const bool adopt_selected = true;
2673     m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2674                                adopt_selected);
2675   }
2676 }
2677 
2678 size_t CommandInterpreter::GetProcessOutput() {
2679   //  The process has stuff waiting for stderr; get it and write it out to the
2680   //  appropriate place.
2681   char stdio_buffer[1024];
2682   size_t len;
2683   size_t total_bytes = 0;
2684   Status error;
2685   TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2686   if (target_sp) {
2687     ProcessSP process_sp(target_sp->GetProcessSP());
2688     if (process_sp) {
2689       while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2690                                           error)) > 0) {
2691         size_t bytes_written = len;
2692         m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2693         total_bytes += len;
2694       }
2695       while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2696                                           error)) > 0) {
2697         size_t bytes_written = len;
2698         m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2699         total_bytes += len;
2700       }
2701     }
2702   }
2703   return total_bytes;
2704 }
2705 
2706 void CommandInterpreter::StartHandlingCommand() {
2707   auto idle_state = CommandHandlingState::eIdle;
2708   if (m_command_state.compare_exchange_strong(
2709           idle_state, CommandHandlingState::eInProgress))
2710     lldbassert(m_iohandler_nesting_level == 0);
2711   else
2712     lldbassert(m_iohandler_nesting_level > 0);
2713   ++m_iohandler_nesting_level;
2714 }
2715 
2716 void CommandInterpreter::FinishHandlingCommand() {
2717   lldbassert(m_iohandler_nesting_level > 0);
2718   if (--m_iohandler_nesting_level == 0) {
2719     auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2720     lldbassert(prev_state != CommandHandlingState::eIdle);
2721   }
2722 }
2723 
2724 bool CommandInterpreter::InterruptCommand() {
2725   auto in_progress = CommandHandlingState::eInProgress;
2726   return m_command_state.compare_exchange_strong(
2727       in_progress, CommandHandlingState::eInterrupted);
2728 }
2729 
2730 bool CommandInterpreter::WasInterrupted() const {
2731   bool was_interrupted =
2732       (m_command_state == CommandHandlingState::eInterrupted);
2733   lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2734   return was_interrupted;
2735 }
2736 
2737 void CommandInterpreter::PrintCommandOutput(Stream &stream,
2738                                             llvm::StringRef str) {
2739   // Split the output into lines and poll for interrupt requests
2740   const char *data = str.data();
2741   size_t size = str.size();
2742   while (size > 0 && !WasInterrupted()) {
2743     size_t chunk_size = 0;
2744     for (; chunk_size < size; ++chunk_size) {
2745       lldbassert(data[chunk_size] != '\0');
2746       if (data[chunk_size] == '\n') {
2747         ++chunk_size;
2748         break;
2749       }
2750     }
2751     chunk_size = stream.Write(data, chunk_size);
2752     lldbassert(size >= chunk_size);
2753     data += chunk_size;
2754     size -= chunk_size;
2755   }
2756   if (size > 0) {
2757     stream.Printf("\n... Interrupted.\n");
2758   }
2759 }
2760 
2761 bool CommandInterpreter::EchoCommandNonInteractive(
2762     llvm::StringRef line, const Flags &io_handler_flags) const {
2763   if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2764     return false;
2765 
2766   llvm::StringRef command = line.trim();
2767   if (command.empty())
2768     return true;
2769 
2770   if (command.front() == m_comment_char)
2771     return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2772 
2773   return true;
2774 }
2775 
2776 void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2777                                                 std::string &line) {
2778     // If we were interrupted, bail out...
2779     if (WasInterrupted())
2780       return;
2781 
2782   const bool is_interactive = io_handler.GetIsInteractive();
2783   if (!is_interactive) {
2784     // When we are not interactive, don't execute blank lines. This will happen
2785     // sourcing a commands file. We don't want blank lines to repeat the
2786     // previous command and cause any errors to occur (like redefining an
2787     // alias, get an error and stop parsing the commands file).
2788     if (line.empty())
2789       return;
2790 
2791     // When using a non-interactive file handle (like when sourcing commands
2792     // from a file) we need to echo the command out so we don't just see the
2793     // command output and no command...
2794     if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
2795       io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2796                                                line.c_str());
2797   }
2798 
2799   StartHandlingCommand();
2800 
2801   lldb_private::CommandReturnObject result;
2802   HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2803 
2804   // Now emit the command output text from the command we just executed
2805   if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2806     // Display any STDOUT/STDERR _prior_ to emitting the command result text
2807     GetProcessOutput();
2808 
2809     if (!result.GetImmediateOutputStream()) {
2810       llvm::StringRef output = result.GetOutputData();
2811       PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
2812     }
2813 
2814     // Now emit the command error text from the command we just executed
2815     if (!result.GetImmediateErrorStream()) {
2816       llvm::StringRef error = result.GetErrorData();
2817       PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
2818     }
2819   }
2820 
2821   FinishHandlingCommand();
2822 
2823   switch (result.GetStatus()) {
2824   case eReturnStatusInvalid:
2825   case eReturnStatusSuccessFinishNoResult:
2826   case eReturnStatusSuccessFinishResult:
2827   case eReturnStatusStarted:
2828     break;
2829 
2830   case eReturnStatusSuccessContinuingNoResult:
2831   case eReturnStatusSuccessContinuingResult:
2832     if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2833       io_handler.SetIsDone(true);
2834     break;
2835 
2836   case eReturnStatusFailed:
2837     m_num_errors++;
2838     if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2839       io_handler.SetIsDone(true);
2840     break;
2841 
2842   case eReturnStatusQuit:
2843     m_quit_requested = true;
2844     io_handler.SetIsDone(true);
2845     break;
2846   }
2847 
2848   // Finally, if we're going to stop on crash, check that here:
2849   if (!m_quit_requested && result.GetDidChangeProcessState() &&
2850       io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2851     bool should_stop = false;
2852     TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2853     if (target_sp) {
2854       ProcessSP process_sp(target_sp->GetProcessSP());
2855       if (process_sp) {
2856         for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2857           StopReason reason = thread_sp->GetStopReason();
2858           if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2859                reason == eStopReasonInstrumentation) &&
2860               !result.GetAbnormalStopWasExpected()) {
2861             should_stop = true;
2862             break;
2863           }
2864         }
2865       }
2866     }
2867     if (should_stop) {
2868       io_handler.SetIsDone(true);
2869       m_stopped_for_crash = true;
2870     }
2871   }
2872 }
2873 
2874 bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2875   ExecutionContext exe_ctx(GetExecutionContext());
2876   Process *process = exe_ctx.GetProcessPtr();
2877 
2878   if (InterruptCommand())
2879     return true;
2880 
2881   if (process) {
2882     StateType state = process->GetState();
2883     if (StateIsRunningState(state)) {
2884       process->Halt();
2885       return true; // Don't do any updating when we are running
2886     }
2887   }
2888 
2889   ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2890   if (script_interpreter) {
2891     if (script_interpreter->Interrupt())
2892       return true;
2893   }
2894   return false;
2895 }
2896 
2897 void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2898     const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2899     void *baton) {
2900   Debugger &debugger = GetDebugger();
2901   IOHandlerSP io_handler_sp(
2902       new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2903                             "lldb", // Name of input reader for history
2904                             llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2905                             llvm::StringRef(), // Continuation prompt
2906                             true,              // Get multiple lines
2907                             debugger.GetUseColor(),
2908                             0,         // Don't show line numbers
2909                             delegate,  // IOHandlerDelegate
2910                             nullptr)); // FileShadowCollector
2911 
2912   if (io_handler_sp) {
2913     io_handler_sp->SetUserData(baton);
2914     if (asynchronously)
2915       debugger.PushIOHandler(io_handler_sp);
2916     else
2917       debugger.RunIOHandler(io_handler_sp);
2918   }
2919 }
2920 
2921 void CommandInterpreter::GetPythonCommandsFromIOHandler(
2922     const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2923     void *baton) {
2924   Debugger &debugger = GetDebugger();
2925   IOHandlerSP io_handler_sp(
2926       new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2927                             "lldb-python", // Name of input reader for history
2928                             llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2929                             llvm::StringRef(), // Continuation prompt
2930                             true,              // Get multiple lines
2931                             debugger.GetUseColor(),
2932                             0,         // Don't show line numbers
2933                             delegate,  // IOHandlerDelegate
2934                             nullptr)); // FileShadowCollector
2935 
2936   if (io_handler_sp) {
2937     io_handler_sp->SetUserData(baton);
2938     if (asynchronously)
2939       debugger.PushIOHandler(io_handler_sp);
2940     else
2941       debugger.RunIOHandler(io_handler_sp);
2942   }
2943 }
2944 
2945 bool CommandInterpreter::IsActive() {
2946   return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2947 }
2948 
2949 lldb::IOHandlerSP
2950 CommandInterpreter::GetIOHandler(bool force_create,
2951                                  CommandInterpreterRunOptions *options) {
2952   // Always re-create the IOHandlerEditline in case the input changed. The old
2953   // instance might have had a non-interactive input and now it does or vice
2954   // versa.
2955   if (force_create || !m_command_io_handler_sp) {
2956     // Always re-create the IOHandlerEditline in case the input changed. The
2957     // old instance might have had a non-interactive input and now it does or
2958     // vice versa.
2959     uint32_t flags = 0;
2960 
2961     if (options) {
2962       if (options->m_stop_on_continue == eLazyBoolYes)
2963         flags |= eHandleCommandFlagStopOnContinue;
2964       if (options->m_stop_on_error == eLazyBoolYes)
2965         flags |= eHandleCommandFlagStopOnError;
2966       if (options->m_stop_on_crash == eLazyBoolYes)
2967         flags |= eHandleCommandFlagStopOnCrash;
2968       if (options->m_echo_commands != eLazyBoolNo)
2969         flags |= eHandleCommandFlagEchoCommand;
2970       if (options->m_echo_comment_commands != eLazyBoolNo)
2971         flags |= eHandleCommandFlagEchoCommentCommand;
2972       if (options->m_print_results != eLazyBoolNo)
2973         flags |= eHandleCommandFlagPrintResult;
2974     } else {
2975       flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2976     }
2977 
2978     m_command_io_handler_sp = std::make_shared<IOHandlerEditline>(
2979         m_debugger, IOHandler::Type::CommandInterpreter,
2980         m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2981         m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
2982         llvm::StringRef(), // Continuation prompt
2983         false, // Don't enable multiple line input, just single line commands
2984         m_debugger.GetUseColor(),
2985         0,     // Don't show line numbers
2986         *this, // IOHandlerDelegate
2987         GetDebugger().GetInputRecorder());
2988   }
2989   return m_command_io_handler_sp;
2990 }
2991 
2992 void CommandInterpreter::RunCommandInterpreter(
2993     bool auto_handle_events, bool spawn_thread,
2994     CommandInterpreterRunOptions &options) {
2995   // Always re-create the command interpreter when we run it in case any file
2996   // handles have changed.
2997   bool force_create = true;
2998   m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2999   m_stopped_for_crash = false;
3000 
3001   if (auto_handle_events)
3002     m_debugger.StartEventHandlerThread();
3003 
3004   if (spawn_thread) {
3005     m_debugger.StartIOHandlerThread();
3006   } else {
3007     m_debugger.ExecuteIOHandlers();
3008 
3009     if (auto_handle_events)
3010       m_debugger.StopEventHandlerThread();
3011   }
3012 }
3013 
3014 CommandObject *
3015 CommandInterpreter::ResolveCommandImpl(std::string &command_line,
3016                                        CommandReturnObject &result) {
3017   std::string scratch_command(command_line); // working copy so we don't modify
3018                                              // command_line unless we succeed
3019   CommandObject *cmd_obj = nullptr;
3020   StreamString revised_command_line;
3021   bool wants_raw_input = false;
3022   size_t actual_cmd_name_len = 0;
3023   std::string next_word;
3024   StringList matches;
3025   bool done = false;
3026   while (!done) {
3027     char quote_char = '\0';
3028     std::string suffix;
3029     ExtractCommand(scratch_command, next_word, suffix, quote_char);
3030     if (cmd_obj == nullptr) {
3031       std::string full_name;
3032       bool is_alias = GetAliasFullName(next_word, full_name);
3033       cmd_obj = GetCommandObject(next_word, &matches);
3034       bool is_real_command =
3035           (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
3036       if (!is_real_command) {
3037         matches.Clear();
3038         std::string alias_result;
3039         cmd_obj =
3040             BuildAliasResult(full_name, scratch_command, alias_result, result);
3041         revised_command_line.Printf("%s", alias_result.c_str());
3042         if (cmd_obj) {
3043           wants_raw_input = cmd_obj->WantsRawCommandString();
3044           actual_cmd_name_len = cmd_obj->GetCommandName().size();
3045         }
3046       } else {
3047         if (cmd_obj) {
3048           llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3049           actual_cmd_name_len += cmd_name.size();
3050           revised_command_line.Printf("%s", cmd_name.str().c_str());
3051           wants_raw_input = cmd_obj->WantsRawCommandString();
3052         } else {
3053           revised_command_line.Printf("%s", next_word.c_str());
3054         }
3055       }
3056     } else {
3057       if (cmd_obj->IsMultiwordObject()) {
3058         CommandObject *sub_cmd_obj =
3059             cmd_obj->GetSubcommandObject(next_word.c_str());
3060         if (sub_cmd_obj) {
3061           // The subcommand's name includes the parent command's name, so
3062           // restart rather than append to the revised_command_line.
3063           llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3064           actual_cmd_name_len = sub_cmd_name.size() + 1;
3065           revised_command_line.Clear();
3066           revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
3067           cmd_obj = sub_cmd_obj;
3068           wants_raw_input = cmd_obj->WantsRawCommandString();
3069         } else {
3070           if (quote_char)
3071             revised_command_line.Printf(" %c%s%s%c", quote_char,
3072                                         next_word.c_str(), suffix.c_str(),
3073                                         quote_char);
3074           else
3075             revised_command_line.Printf(" %s%s", next_word.c_str(),
3076                                         suffix.c_str());
3077           done = true;
3078         }
3079       } else {
3080         if (quote_char)
3081           revised_command_line.Printf(" %c%s%s%c", quote_char,
3082                                       next_word.c_str(), suffix.c_str(),
3083                                       quote_char);
3084         else
3085           revised_command_line.Printf(" %s%s", next_word.c_str(),
3086                                       suffix.c_str());
3087         done = true;
3088       }
3089     }
3090 
3091     if (cmd_obj == nullptr) {
3092       const size_t num_matches = matches.GetSize();
3093       if (matches.GetSize() > 1) {
3094         StreamString error_msg;
3095         error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3096                          next_word.c_str());
3097 
3098         for (uint32_t i = 0; i < num_matches; ++i) {
3099           error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3100         }
3101         result.AppendRawError(error_msg.GetString());
3102       } else {
3103         // We didn't have only one match, otherwise we wouldn't get here.
3104         lldbassert(num_matches == 0);
3105         result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3106                                      next_word.c_str());
3107       }
3108       result.SetStatus(eReturnStatusFailed);
3109       return nullptr;
3110     }
3111 
3112     if (cmd_obj->IsMultiwordObject()) {
3113       if (!suffix.empty()) {
3114         result.AppendErrorWithFormat(
3115             "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3116             "might be invalid).\n",
3117             cmd_obj->GetCommandName().str().c_str(),
3118             next_word.empty() ? "" : next_word.c_str(),
3119             next_word.empty() ? " -- " : " ", suffix.c_str());
3120         result.SetStatus(eReturnStatusFailed);
3121         return nullptr;
3122       }
3123     } else {
3124       // If we found a normal command, we are done
3125       done = true;
3126       if (!suffix.empty()) {
3127         switch (suffix[0]) {
3128         case '/':
3129           // GDB format suffixes
3130           {
3131             Options *command_options = cmd_obj->GetOptions();
3132             if (command_options &&
3133                 command_options->SupportsLongOption("gdb-format")) {
3134               std::string gdb_format_option("--gdb-format=");
3135               gdb_format_option += (suffix.c_str() + 1);
3136 
3137               std::string cmd = revised_command_line.GetString();
3138               size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3139               if (arg_terminator_idx != std::string::npos) {
3140                 // Insert the gdb format option before the "--" that terminates
3141                 // options
3142                 gdb_format_option.append(1, ' ');
3143                 cmd.insert(arg_terminator_idx, gdb_format_option);
3144                 revised_command_line.Clear();
3145                 revised_command_line.PutCString(cmd);
3146               } else
3147                 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3148 
3149               if (wants_raw_input &&
3150                   FindArgumentTerminator(cmd) == std::string::npos)
3151                 revised_command_line.PutCString(" --");
3152             } else {
3153               result.AppendErrorWithFormat(
3154                   "the '%s' command doesn't support the --gdb-format option\n",
3155                   cmd_obj->GetCommandName().str().c_str());
3156               result.SetStatus(eReturnStatusFailed);
3157               return nullptr;
3158             }
3159           }
3160           break;
3161 
3162         default:
3163           result.AppendErrorWithFormat(
3164               "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3165           result.SetStatus(eReturnStatusFailed);
3166           return nullptr;
3167         }
3168       }
3169     }
3170     if (scratch_command.empty())
3171       done = true;
3172   }
3173 
3174   if (!scratch_command.empty())
3175     revised_command_line.Printf(" %s", scratch_command.c_str());
3176 
3177   if (cmd_obj != NULL)
3178     command_line = revised_command_line.GetString();
3179 
3180   return cmd_obj;
3181 }
3182