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