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