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