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