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