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