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