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