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