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