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