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.  "
748           "If no host is specifed, localhost is assumed.",
749           "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
750   if (connect_gdb_remote_cmd_up) {
751     if (connect_gdb_remote_cmd_up->AddRegexCommand(
752             "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
753             "process connect --plugin gdb-remote connect://%1:%2") &&
754         connect_gdb_remote_cmd_up->AddRegexCommand(
755             "^([[:digit:]]+)$",
756             "process connect --plugin gdb-remote connect://localhost:%1")) {
757       CommandObjectSP command_sp(connect_gdb_remote_cmd_up.release());
758       m_command_dict[std::string(command_sp->GetCommandName())] = command_sp;
759     }
760   }
761 
762   std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_up(
763       new CommandObjectRegexCommand(
764           *this, "kdp-remote",
765           "Connect to a process via remote KDP server.  "
766           "If no UDP port is specified, port 41139 is "
767           "assumed.",
768           "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
769   if (connect_kdp_remote_cmd_up) {
770     if (connect_kdp_remote_cmd_up->AddRegexCommand(
771             "^([^:]+:[[:digit:]]+)$",
772             "process connect --plugin kdp-remote udp://%1") &&
773         connect_kdp_remote_cmd_up->AddRegexCommand(
774             "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
775       CommandObjectSP command_sp(connect_kdp_remote_cmd_up.release());
776       m_command_dict[std::string(command_sp->GetCommandName())] = command_sp;
777     }
778   }
779 
780   std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_up(
781       new CommandObjectRegexCommand(
782           *this, "_regexp-bt",
783           "Show the current thread's call stack.  Any numeric argument "
784           "displays at most that many "
785           "frames.  The argument 'all' displays all threads.  Use 'settings"
786           " set frame-format' to customize the printing of individual frames "
787           "and 'settings set thread-format' to customize the thread header.",
788           "bt [<digit> | all]", 2, 0, false));
789   if (bt_regex_cmd_up) {
790     // accept but don't document "bt -c <number>" -- before bt was a regex
791     // command if you wanted to backtrace three frames you would do "bt -c 3"
792     // but the intention is to have this emulate the gdb "bt" command and so
793     // now "bt 3" is the preferred form, in line with gdb.
794     if (bt_regex_cmd_up->AddRegexCommand("^([[:digit:]]+)[[:space:]]*$",
795                                          "thread backtrace -c %1") &&
796         bt_regex_cmd_up->AddRegexCommand("^-c ([[:digit:]]+)[[:space:]]*$",
797                                          "thread backtrace -c %1") &&
798         bt_regex_cmd_up->AddRegexCommand("^all[[:space:]]*$", "thread backtrace all") &&
799         bt_regex_cmd_up->AddRegexCommand("^[[:space:]]*$", "thread backtrace")) {
800       CommandObjectSP command_sp(bt_regex_cmd_up.release());
801       m_command_dict[std::string(command_sp->GetCommandName())] = command_sp;
802     }
803   }
804 
805   std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_up(
806       new CommandObjectRegexCommand(
807           *this, "_regexp-list",
808           "List relevant source code using one of several shorthand formats.",
809           "\n"
810           "_regexp-list <file>:<line>   // List around specific file/line\n"
811           "_regexp-list <line>          // List current file around specified "
812           "line\n"
813           "_regexp-list <function-name> // List specified function\n"
814           "_regexp-list 0x<address>     // List around specified address\n"
815           "_regexp-list -[<count>]      // List previous <count> lines\n"
816           "_regexp-list                 // List subsequent lines",
817           2, CommandCompletions::eSourceFileCompletion, false));
818   if (list_regex_cmd_up) {
819     if (list_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
820                                            "source list --line %1") &&
821         list_regex_cmd_up->AddRegexCommand(
822             "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
823             "]*$",
824             "source list --file '%1' --line %2") &&
825         list_regex_cmd_up->AddRegexCommand(
826             "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
827             "source list --address %1") &&
828         list_regex_cmd_up->AddRegexCommand("^-[[:space:]]*$",
829                                            "source list --reverse") &&
830         list_regex_cmd_up->AddRegexCommand(
831             "^-([[:digit:]]+)[[:space:]]*$",
832             "source list --reverse --count %1") &&
833         list_regex_cmd_up->AddRegexCommand("^(.+)$",
834                                            "source list --name \"%1\"") &&
835         list_regex_cmd_up->AddRegexCommand("^$", "source list")) {
836       CommandObjectSP list_regex_cmd_sp(list_regex_cmd_up.release());
837       m_command_dict[std::string(list_regex_cmd_sp->GetCommandName())] =
838           list_regex_cmd_sp;
839     }
840   }
841 
842   std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_up(
843       new CommandObjectRegexCommand(
844           *this, "_regexp-env",
845           "Shorthand for viewing and setting environment variables.",
846           "\n"
847           "_regexp-env                  // Show environment\n"
848           "_regexp-env <name>=<value>   // Set an environment variable",
849           2, 0, false));
850   if (env_regex_cmd_up) {
851     if (env_regex_cmd_up->AddRegexCommand("^$",
852                                           "settings show target.env-vars") &&
853         env_regex_cmd_up->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
854                                           "settings set target.env-vars %1")) {
855       CommandObjectSP env_regex_cmd_sp(env_regex_cmd_up.release());
856       m_command_dict[std::string(env_regex_cmd_sp->GetCommandName())] =
857           env_regex_cmd_sp;
858     }
859   }
860 
861   std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_up(
862       new CommandObjectRegexCommand(
863           *this, "_regexp-jump", "Set the program counter to a new address.",
864           "\n"
865           "_regexp-jump <line>\n"
866           "_regexp-jump +<line-offset> | -<line-offset>\n"
867           "_regexp-jump <file>:<line>\n"
868           "_regexp-jump *<addr>\n",
869           2, 0, false));
870   if (jump_regex_cmd_up) {
871     if (jump_regex_cmd_up->AddRegexCommand("^\\*(.*)$",
872                                            "thread jump --addr %1") &&
873         jump_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
874                                            "thread jump --line %1") &&
875         jump_regex_cmd_up->AddRegexCommand("^([^:]+):([0-9]+)$",
876                                            "thread jump --file %1 --line %2") &&
877         jump_regex_cmd_up->AddRegexCommand("^([+\\-][0-9]+)$",
878                                            "thread jump --by %1")) {
879       CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_up.release());
880       m_command_dict[std::string(jump_regex_cmd_sp->GetCommandName())] =
881           jump_regex_cmd_sp;
882     }
883   }
884 }
885 
886 int CommandInterpreter::GetCommandNamesMatchingPartialString(
887     const char *cmd_str, bool include_aliases, StringList &matches,
888     StringList &descriptions) {
889   AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
890                                 &descriptions);
891 
892   if (include_aliases) {
893     AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
894                                   &descriptions);
895   }
896 
897   return matches.GetSize();
898 }
899 
900 CommandObjectMultiword *CommandInterpreter::VerifyUserMultiwordCmdPath(
901     Args &path, bool leaf_is_command, Status &result) {
902   result.Clear();
903 
904   auto get_multi_or_report_error =
905       [&result](CommandObjectSP cmd_sp,
906                            const char *name) -> CommandObjectMultiword * {
907     if (!cmd_sp) {
908       result.SetErrorStringWithFormat("Path component: '%s' not found", name);
909       return nullptr;
910     }
911     if (!cmd_sp->IsUserCommand()) {
912       result.SetErrorStringWithFormat("Path component: '%s' is not a user "
913                                       "command",
914                                       name);
915       return nullptr;
916     }
917     CommandObjectMultiword *cmd_as_multi = cmd_sp->GetAsMultiwordCommand();
918     if (!cmd_as_multi) {
919       result.SetErrorStringWithFormat("Path component: '%s' is not a container "
920                                       "command",
921                                       name);
922       return nullptr;
923     }
924     return cmd_as_multi;
925   };
926 
927   size_t num_args = path.GetArgumentCount();
928   if (num_args == 0) {
929     result.SetErrorString("empty command path");
930     return nullptr;
931   }
932 
933   if (num_args == 1 && leaf_is_command) {
934     // We just got a leaf command to be added to the root.  That's not an error,
935     // just return null for the container.
936     return nullptr;
937   }
938 
939   // Start by getting the root command from the interpreter.
940   const char *cur_name = path.GetArgumentAtIndex(0);
941   CommandObjectSP cur_cmd_sp = GetCommandSPExact(cur_name);
942   CommandObjectMultiword *cur_as_multi =
943       get_multi_or_report_error(cur_cmd_sp, cur_name);
944   if (cur_as_multi == nullptr)
945     return nullptr;
946 
947   size_t num_path_elements = num_args - (leaf_is_command ? 1 : 0);
948   for (size_t cursor = 1; cursor < num_path_elements && cur_as_multi != nullptr;
949        cursor++) {
950     cur_name = path.GetArgumentAtIndex(cursor);
951     cur_cmd_sp = cur_as_multi->GetSubcommandSPExact(cur_name);
952     cur_as_multi = get_multi_or_report_error(cur_cmd_sp, cur_name);
953   }
954   return cur_as_multi;
955 }
956 
957 CommandObjectSP
958 CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
959                                  bool exact, StringList *matches,
960                                  StringList *descriptions) const {
961   CommandObjectSP command_sp;
962 
963   std::string cmd = std::string(cmd_str);
964 
965   if (HasCommands()) {
966     auto pos = m_command_dict.find(cmd);
967     if (pos != m_command_dict.end())
968       command_sp = pos->second;
969   }
970 
971   if (include_aliases && HasAliases()) {
972     auto alias_pos = m_alias_dict.find(cmd);
973     if (alias_pos != m_alias_dict.end())
974       command_sp = alias_pos->second;
975   }
976 
977   if (HasUserCommands()) {
978     auto pos = m_user_dict.find(cmd);
979     if (pos != m_user_dict.end())
980       command_sp = pos->second;
981   }
982 
983   if (HasUserMultiwordCommands()) {
984     auto pos = m_user_mw_dict.find(cmd);
985     if (pos != m_user_mw_dict.end())
986       command_sp = pos->second;
987   }
988 
989   if (!exact && !command_sp) {
990     // We will only get into here if we didn't find any exact matches.
991 
992     CommandObjectSP user_match_sp, user_mw_match_sp, alias_match_sp,
993         real_match_sp;
994 
995     StringList local_matches;
996     if (matches == nullptr)
997       matches = &local_matches;
998 
999     unsigned int num_cmd_matches = 0;
1000     unsigned int num_alias_matches = 0;
1001     unsigned int num_user_matches = 0;
1002     unsigned int num_user_mw_matches = 0;
1003 
1004     // Look through the command dictionaries one by one, and if we get only one
1005     // match from any of them in toto, then return that, otherwise return an
1006     // empty CommandObjectSP and the list of matches.
1007 
1008     if (HasCommands()) {
1009       num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
1010                                                       *matches, descriptions);
1011     }
1012 
1013     if (num_cmd_matches == 1) {
1014       cmd.assign(matches->GetStringAtIndex(0));
1015       auto pos = m_command_dict.find(cmd);
1016       if (pos != m_command_dict.end())
1017         real_match_sp = pos->second;
1018     }
1019 
1020     if (include_aliases && HasAliases()) {
1021       num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
1022                                                         *matches, descriptions);
1023     }
1024 
1025     if (num_alias_matches == 1) {
1026       cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
1027       auto alias_pos = m_alias_dict.find(cmd);
1028       if (alias_pos != m_alias_dict.end())
1029         alias_match_sp = alias_pos->second;
1030     }
1031 
1032     if (HasUserCommands()) {
1033       num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
1034                                                        *matches, descriptions);
1035     }
1036 
1037     if (num_user_matches == 1) {
1038       cmd.assign(
1039           matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
1040 
1041       auto pos = m_user_dict.find(cmd);
1042       if (pos != m_user_dict.end())
1043         user_match_sp = pos->second;
1044     }
1045 
1046     if (HasUserMultiwordCommands()) {
1047       num_user_mw_matches = AddNamesMatchingPartialString(
1048           m_user_mw_dict, cmd_str, *matches, descriptions);
1049     }
1050 
1051     if (num_user_mw_matches == 1) {
1052       cmd.assign(matches->GetStringAtIndex(num_cmd_matches + num_alias_matches +
1053                                            num_user_matches));
1054 
1055       auto pos = m_user_mw_dict.find(cmd);
1056       if (pos != m_user_mw_dict.end())
1057         user_mw_match_sp = pos->second;
1058     }
1059 
1060     // If we got exactly one match, return that, otherwise return the match
1061     // list.
1062 
1063     if (num_user_matches + num_user_mw_matches + num_cmd_matches +
1064             num_alias_matches ==
1065         1) {
1066       if (num_cmd_matches)
1067         return real_match_sp;
1068       else if (num_alias_matches)
1069         return alias_match_sp;
1070       else if (num_user_mw_matches)
1071         return user_mw_match_sp;
1072       else
1073         return user_match_sp;
1074     }
1075   } else if (matches && command_sp) {
1076     matches->AppendString(cmd_str);
1077     if (descriptions)
1078       descriptions->AppendString(command_sp->GetHelp());
1079   }
1080 
1081   return command_sp;
1082 }
1083 
1084 bool CommandInterpreter::AddCommand(llvm::StringRef name,
1085                                     const lldb::CommandObjectSP &cmd_sp,
1086                                     bool can_replace) {
1087   if (cmd_sp.get())
1088     lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
1089                "tried to add a CommandObject from a different interpreter");
1090 
1091   if (name.empty())
1092     return false;
1093 
1094   cmd_sp->SetIsUserCommand(false);
1095 
1096   std::string name_sstr(name);
1097   auto name_iter = m_command_dict.find(name_sstr);
1098   if (name_iter != m_command_dict.end()) {
1099     if (!can_replace || !name_iter->second->IsRemovable())
1100       return false;
1101     name_iter->second = cmd_sp;
1102   } else {
1103     m_command_dict[name_sstr] = cmd_sp;
1104   }
1105   return true;
1106 }
1107 
1108 Status CommandInterpreter::AddUserCommand(llvm::StringRef name,
1109                                           const lldb::CommandObjectSP &cmd_sp,
1110                                           bool can_replace) {
1111   Status result;
1112   if (cmd_sp.get())
1113     lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
1114                "tried to add a CommandObject from a different interpreter");
1115   if (name.empty()) {
1116     result.SetErrorString("can't use the empty string for a command name");
1117     return result;
1118   }
1119   // do not allow replacement of internal commands
1120   if (CommandExists(name)) {
1121     result.SetErrorString("can't replace builtin command");
1122     return result;
1123   }
1124 
1125   if (UserCommandExists(name)) {
1126     if (!can_replace) {
1127       result.SetErrorString("user command exists and force replace not set");
1128       return result;
1129     }
1130     if (cmd_sp->IsMultiwordObject()) {
1131       if (!m_user_mw_dict[std::string(name)]->IsRemovable()) {
1132         result.SetErrorString(
1133             "can't replace explicitly non-removable multi-word command");
1134         return result;
1135       }
1136     } else {
1137       if (!m_user_dict[std::string(name)]->IsRemovable()) {
1138         result.SetErrorString("can't replace explicitly non-removable command");
1139         return result;
1140       }
1141     }
1142   }
1143 
1144   cmd_sp->SetIsUserCommand(true);
1145 
1146   if (cmd_sp->IsMultiwordObject())
1147     m_user_mw_dict[std::string(name)] = cmd_sp;
1148   else
1149     m_user_dict[std::string(name)] = cmd_sp;
1150   return result;
1151 }
1152 
1153 CommandObjectSP
1154 CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
1155                                       bool include_aliases) const {
1156   // Break up the command string into words, in case it's a multi-word command.
1157   Args cmd_words(cmd_str);
1158 
1159   if (cmd_str.empty())
1160     return {};
1161 
1162   if (cmd_words.GetArgumentCount() == 1)
1163     return GetCommandSP(cmd_str, include_aliases, true);
1164 
1165   // We have a multi-word command (seemingly), so we need to do more work.
1166   // First, get the cmd_obj_sp for the first word in the command.
1167   CommandObjectSP cmd_obj_sp =
1168       GetCommandSP(cmd_words.GetArgumentAtIndex(0), include_aliases, true);
1169   if (!cmd_obj_sp)
1170     return {};
1171 
1172   // Loop through the rest of the words in the command (everything passed in
1173   // was supposed to be part of a command name), and find the appropriate
1174   // sub-command SP for each command word....
1175   size_t end = cmd_words.GetArgumentCount();
1176   for (size_t i = 1; i < end; ++i) {
1177     if (!cmd_obj_sp->IsMultiwordObject()) {
1178       // We have more words in the command name, but we don't have a
1179       // multiword object. Fail and return.
1180       return {};
1181     }
1182 
1183     cmd_obj_sp = cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(i));
1184     if (!cmd_obj_sp) {
1185       // The sub-command name was invalid.  Fail and return.
1186       return {};
1187     }
1188   }
1189 
1190   // We successfully looped through all the command words and got valid
1191   // command objects for them.
1192   return cmd_obj_sp;
1193 }
1194 
1195 CommandObject *
1196 CommandInterpreter::GetCommandObject(llvm::StringRef cmd_str,
1197                                      StringList *matches,
1198                                      StringList *descriptions) const {
1199   CommandObject *command_obj =
1200       GetCommandSP(cmd_str, false, true, matches, descriptions).get();
1201 
1202   // If we didn't find an exact match to the command string in the commands,
1203   // look in the aliases.
1204 
1205   if (command_obj)
1206     return command_obj;
1207 
1208   command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
1209 
1210   if (command_obj)
1211     return command_obj;
1212 
1213   // If there wasn't an exact match then look for an inexact one in just the
1214   // commands
1215   command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
1216 
1217   // Finally, if there wasn't an inexact match among the commands, look for an
1218   // inexact match in both the commands and aliases.
1219 
1220   if (command_obj) {
1221     if (matches)
1222       matches->AppendString(command_obj->GetCommandName());
1223     if (descriptions)
1224       descriptions->AppendString(command_obj->GetHelp());
1225     return command_obj;
1226   }
1227 
1228   return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
1229 }
1230 
1231 CommandObject *CommandInterpreter::GetUserCommandObject(
1232     llvm::StringRef cmd, StringList *matches, StringList *descriptions) const {
1233   std::string cmd_str(cmd);
1234   auto find_exact = [&](const CommandObject::CommandMap &map) {
1235     auto found_elem = map.find(std::string(cmd));
1236     if (found_elem == map.end())
1237       return (CommandObject *)nullptr;
1238     CommandObject *exact_cmd = found_elem->second.get();
1239     if (exact_cmd) {
1240       if (matches)
1241         matches->AppendString(exact_cmd->GetCommandName());
1242       if (descriptions)
1243         descriptions->AppendString(exact_cmd->GetHelp());
1244       return exact_cmd;
1245     }
1246     return (CommandObject *)nullptr;
1247   };
1248 
1249   CommandObject *exact_cmd = find_exact(GetUserCommands());
1250   if (exact_cmd)
1251     return exact_cmd;
1252 
1253   exact_cmd = find_exact(GetUserMultiwordCommands());
1254   if (exact_cmd)
1255     return exact_cmd;
1256 
1257   // We didn't have an exact command, so now look for partial matches.
1258   size_t num_found;
1259   StringList tmp_list;
1260   StringList *matches_ptr = matches ? matches : &tmp_list;
1261   num_found =
1262       AddNamesMatchingPartialString(GetUserCommands(), cmd_str, *matches_ptr);
1263   num_found += AddNamesMatchingPartialString(GetUserMultiwordCommands(),
1264                                              cmd_str, *matches_ptr);
1265 
1266   return {};
1267 }
1268 
1269 bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
1270   return m_command_dict.find(std::string(cmd)) != m_command_dict.end();
1271 }
1272 
1273 bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1274                                           std::string &full_name) const {
1275   bool exact_match =
1276       (m_alias_dict.find(std::string(cmd)) != m_alias_dict.end());
1277   if (exact_match) {
1278     full_name.assign(std::string(cmd));
1279     return exact_match;
1280   } else {
1281     StringList matches;
1282     size_t num_alias_matches;
1283     num_alias_matches =
1284         AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1285     if (num_alias_matches == 1) {
1286       // Make sure this isn't shadowing a command in the regular command space:
1287       StringList regular_matches;
1288       const bool include_aliases = false;
1289       const bool exact = false;
1290       CommandObjectSP cmd_obj_sp(
1291           GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1292       if (cmd_obj_sp || regular_matches.GetSize() > 0)
1293         return false;
1294       else {
1295         full_name.assign(matches.GetStringAtIndex(0));
1296         return true;
1297       }
1298     } else
1299       return false;
1300   }
1301 }
1302 
1303 bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
1304   return m_alias_dict.find(std::string(cmd)) != m_alias_dict.end();
1305 }
1306 
1307 bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
1308   return m_user_dict.find(std::string(cmd)) != m_user_dict.end();
1309 }
1310 
1311 bool CommandInterpreter::UserMultiwordCommandExists(llvm::StringRef cmd) const {
1312   return m_user_mw_dict.find(std::string(cmd)) != m_user_mw_dict.end();
1313 }
1314 
1315 CommandAlias *
1316 CommandInterpreter::AddAlias(llvm::StringRef alias_name,
1317                              lldb::CommandObjectSP &command_obj_sp,
1318                              llvm::StringRef args_string) {
1319   if (command_obj_sp.get())
1320     lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1321                "tried to add a CommandObject from a different interpreter");
1322 
1323   std::unique_ptr<CommandAlias> command_alias_up(
1324       new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1325 
1326   if (command_alias_up && command_alias_up->IsValid()) {
1327     m_alias_dict[std::string(alias_name)] =
1328         CommandObjectSP(command_alias_up.get());
1329     return command_alias_up.release();
1330   }
1331 
1332   return nullptr;
1333 }
1334 
1335 bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
1336   auto pos = m_alias_dict.find(std::string(alias_name));
1337   if (pos != m_alias_dict.end()) {
1338     m_alias_dict.erase(pos);
1339     return true;
1340   }
1341   return false;
1342 }
1343 
1344 bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
1345   auto pos = m_command_dict.find(std::string(cmd));
1346   if (pos != m_command_dict.end()) {
1347     if (pos->second->IsRemovable()) {
1348       // Only regular expression objects or python commands are removable
1349       m_command_dict.erase(pos);
1350       return true;
1351     }
1352   }
1353   return false;
1354 }
1355 
1356 bool CommandInterpreter::RemoveUser(llvm::StringRef user_name) {
1357   CommandObject::CommandMap::iterator pos =
1358       m_user_dict.find(std::string(user_name));
1359   if (pos != m_user_dict.end()) {
1360     m_user_dict.erase(pos);
1361     return true;
1362   }
1363   return false;
1364 }
1365 
1366 bool CommandInterpreter::RemoveUserMultiword(llvm::StringRef multi_name) {
1367   CommandObject::CommandMap::iterator pos =
1368       m_user_mw_dict.find(std::string(multi_name));
1369   if (pos != m_user_mw_dict.end()) {
1370     m_user_mw_dict.erase(pos);
1371     return true;
1372   }
1373   return false;
1374 }
1375 
1376 void CommandInterpreter::GetHelp(CommandReturnObject &result,
1377                                  uint32_t cmd_types) {
1378   llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1379   if (!help_prologue.empty()) {
1380     OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1381                             help_prologue);
1382   }
1383 
1384   CommandObject::CommandMap::const_iterator pos;
1385   size_t max_len = FindLongestCommandWord(m_command_dict);
1386 
1387   if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1388     result.AppendMessage("Debugger commands:");
1389     result.AppendMessage("");
1390 
1391     for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1392       if (!(cmd_types & eCommandTypesHidden) &&
1393           (pos->first.compare(0, 1, "_") == 0))
1394         continue;
1395 
1396       OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1397                               pos->second->GetHelp(), max_len);
1398     }
1399     result.AppendMessage("");
1400   }
1401 
1402   if (!m_alias_dict.empty() &&
1403       ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1404     result.AppendMessageWithFormat(
1405         "Current command abbreviations "
1406         "(type '%shelp command alias' for more info):\n",
1407         GetCommandPrefix());
1408     result.AppendMessage("");
1409     max_len = FindLongestCommandWord(m_alias_dict);
1410 
1411     for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1412          ++alias_pos) {
1413       OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
1414                               alias_pos->second->GetHelp(), max_len);
1415     }
1416     result.AppendMessage("");
1417   }
1418 
1419   if (!m_user_dict.empty() &&
1420       ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1421     result.AppendMessage("Current user-defined commands:");
1422     result.AppendMessage("");
1423     max_len = FindLongestCommandWord(m_user_dict);
1424     for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
1425       OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1426                               pos->second->GetHelp(), max_len);
1427     }
1428     result.AppendMessage("");
1429   }
1430 
1431   if (!m_user_mw_dict.empty() &&
1432       ((cmd_types & eCommandTypesUserMW) == eCommandTypesUserMW)) {
1433     result.AppendMessage("Current user-defined container commands:");
1434     result.AppendMessage("");
1435     max_len = FindLongestCommandWord(m_user_mw_dict);
1436     for (pos = m_user_dict.begin(); pos != m_user_mw_dict.end(); ++pos) {
1437       OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1438                               pos->second->GetHelp(), max_len);
1439     }
1440     result.AppendMessage("");
1441   }
1442 
1443   result.AppendMessageWithFormat(
1444       "For more information on any command, type '%shelp <command-name>'.\n",
1445       GetCommandPrefix());
1446 }
1447 
1448 CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1449     llvm::StringRef &command_string) {
1450   // This function finds the final, lowest-level, alias-resolved command object
1451   // whose 'Execute' function will eventually be invoked by the given command
1452   // line.
1453 
1454   CommandObject *cmd_obj = nullptr;
1455   size_t start = command_string.find_first_not_of(k_white_space);
1456   size_t end = 0;
1457   bool done = false;
1458   while (!done) {
1459     if (start != std::string::npos) {
1460       // Get the next word from command_string.
1461       end = command_string.find_first_of(k_white_space, start);
1462       if (end == std::string::npos)
1463         end = command_string.size();
1464       std::string cmd_word =
1465           std::string(command_string.substr(start, end - start));
1466 
1467       if (cmd_obj == nullptr)
1468         // Since cmd_obj is NULL we are on our first time through this loop.
1469         // Check to see if cmd_word is a valid command or alias.
1470         cmd_obj = GetCommandObject(cmd_word);
1471       else if (cmd_obj->IsMultiwordObject()) {
1472         // Our current object is a multi-word object; see if the cmd_word is a
1473         // valid sub-command for our object.
1474         CommandObject *sub_cmd_obj =
1475             cmd_obj->GetSubcommandObject(cmd_word.c_str());
1476         if (sub_cmd_obj)
1477           cmd_obj = sub_cmd_obj;
1478         else // cmd_word was not a valid sub-command word, so we are done
1479           done = true;
1480       } else
1481         // We have a cmd_obj and it is not a multi-word object, so we are done.
1482         done = true;
1483 
1484       // If we didn't find a valid command object, or our command object is not
1485       // a multi-word object, or we are at the end of the command_string, then
1486       // we are done.  Otherwise, find the start of the next word.
1487 
1488       if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1489           end >= command_string.size())
1490         done = true;
1491       else
1492         start = command_string.find_first_not_of(k_white_space, end);
1493     } else
1494       // Unable to find any more words.
1495       done = true;
1496   }
1497 
1498   command_string = command_string.substr(end);
1499   return cmd_obj;
1500 }
1501 
1502 static const char *k_valid_command_chars =
1503     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1504 static void StripLeadingSpaces(std::string &s) {
1505   if (!s.empty()) {
1506     size_t pos = s.find_first_not_of(k_white_space);
1507     if (pos == std::string::npos)
1508       s.clear();
1509     else if (pos == 0)
1510       return;
1511     s.erase(0, pos);
1512   }
1513 }
1514 
1515 static size_t FindArgumentTerminator(const std::string &s) {
1516   const size_t s_len = s.size();
1517   size_t offset = 0;
1518   while (offset < s_len) {
1519     size_t pos = s.find("--", offset);
1520     if (pos == std::string::npos)
1521       break;
1522     if (pos > 0) {
1523       if (llvm::isSpace(s[pos - 1])) {
1524         // Check if the string ends "\s--" (where \s is a space character) or
1525         // if we have "\s--\s".
1526         if ((pos + 2 >= s_len) || llvm::isSpace(s[pos + 2])) {
1527           return pos;
1528         }
1529       }
1530     }
1531     offset = pos + 2;
1532   }
1533   return std::string::npos;
1534 }
1535 
1536 static bool ExtractCommand(std::string &command_string, std::string &command,
1537                            std::string &suffix, char &quote_char) {
1538   command.clear();
1539   suffix.clear();
1540   StripLeadingSpaces(command_string);
1541 
1542   bool result = false;
1543   quote_char = '\0';
1544 
1545   if (!command_string.empty()) {
1546     const char first_char = command_string[0];
1547     if (first_char == '\'' || first_char == '"') {
1548       quote_char = first_char;
1549       const size_t end_quote_pos = command_string.find(quote_char, 1);
1550       if (end_quote_pos == std::string::npos) {
1551         command.swap(command_string);
1552         command_string.erase();
1553       } else {
1554         command.assign(command_string, 1, end_quote_pos - 1);
1555         if (end_quote_pos + 1 < command_string.size())
1556           command_string.erase(0, command_string.find_first_not_of(
1557                                       k_white_space, end_quote_pos + 1));
1558         else
1559           command_string.erase();
1560       }
1561     } else {
1562       const size_t first_space_pos =
1563           command_string.find_first_of(k_white_space);
1564       if (first_space_pos == std::string::npos) {
1565         command.swap(command_string);
1566         command_string.erase();
1567       } else {
1568         command.assign(command_string, 0, first_space_pos);
1569         command_string.erase(0, command_string.find_first_not_of(
1570                                     k_white_space, first_space_pos));
1571       }
1572     }
1573     result = true;
1574   }
1575 
1576   if (!command.empty()) {
1577     // actual commands can't start with '-' or '_'
1578     if (command[0] != '-' && command[0] != '_') {
1579       size_t pos = command.find_first_not_of(k_valid_command_chars);
1580       if (pos > 0 && pos != std::string::npos) {
1581         suffix.assign(command.begin() + pos, command.end());
1582         command.erase(pos);
1583       }
1584     }
1585   }
1586 
1587   return result;
1588 }
1589 
1590 CommandObject *CommandInterpreter::BuildAliasResult(
1591     llvm::StringRef alias_name, std::string &raw_input_string,
1592     std::string &alias_result, CommandReturnObject &result) {
1593   CommandObject *alias_cmd_obj = nullptr;
1594   Args cmd_args(raw_input_string);
1595   alias_cmd_obj = GetCommandObject(alias_name);
1596   StreamString result_str;
1597 
1598   if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1599     alias_result.clear();
1600     return alias_cmd_obj;
1601   }
1602   std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1603       ((CommandAlias *)alias_cmd_obj)->Desugar();
1604   OptionArgVectorSP option_arg_vector_sp = desugared.second;
1605   alias_cmd_obj = desugared.first.get();
1606   std::string alias_name_str = std::string(alias_name);
1607   if ((cmd_args.GetArgumentCount() == 0) ||
1608       (alias_name_str != cmd_args.GetArgumentAtIndex(0)))
1609     cmd_args.Unshift(alias_name_str);
1610 
1611   result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
1612 
1613   if (!option_arg_vector_sp.get()) {
1614     alias_result = std::string(result_str.GetString());
1615     return alias_cmd_obj;
1616   }
1617   OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1618 
1619   int value_type;
1620   std::string option;
1621   std::string value;
1622   for (const auto &entry : *option_arg_vector) {
1623     std::tie(option, value_type, value) = entry;
1624     if (option == "<argument>") {
1625       result_str.Printf(" %s", value.c_str());
1626       continue;
1627     }
1628 
1629     result_str.Printf(" %s", option.c_str());
1630     if (value_type == OptionParser::eNoArgument)
1631       continue;
1632 
1633     if (value_type != OptionParser::eOptionalArgument)
1634       result_str.Printf(" ");
1635     int index = GetOptionArgumentPosition(value.c_str());
1636     if (index == 0)
1637       result_str.Printf("%s", value.c_str());
1638     else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1639 
1640       result.AppendErrorWithFormat("Not enough arguments provided; you "
1641                                    "need at least %d arguments to use "
1642                                    "this alias.\n",
1643                                    index);
1644       return nullptr;
1645     } else {
1646       size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1647       if (strpos != std::string::npos)
1648         raw_input_string = raw_input_string.erase(
1649             strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1650       result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
1651     }
1652   }
1653 
1654   alias_result = std::string(result_str.GetString());
1655   return alias_cmd_obj;
1656 }
1657 
1658 Status CommandInterpreter::PreprocessCommand(std::string &command) {
1659   // The command preprocessor needs to do things to the command line before any
1660   // parsing of arguments or anything else is done. The only current stuff that
1661   // gets preprocessed is anything enclosed in backtick ('`') characters is
1662   // evaluated as an expression and the result of the expression must be a
1663   // scalar that can be substituted into the command. An example would be:
1664   // (lldb) memory read `$rsp + 20`
1665   Status error; // Status for any expressions that might not evaluate
1666   size_t start_backtick;
1667   size_t pos = 0;
1668   while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1669     // Stop if an error was encountered during the previous iteration.
1670     if (error.Fail())
1671       break;
1672 
1673     if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
1674       // The backtick was preceded by a '\' character, remove the slash and
1675       // don't treat the backtick as the start of an expression.
1676       command.erase(start_backtick - 1, 1);
1677       // No need to add one to start_backtick since we just deleted a char.
1678       pos = start_backtick;
1679       continue;
1680     }
1681 
1682     const size_t expr_content_start = start_backtick + 1;
1683     const size_t end_backtick = command.find('`', expr_content_start);
1684 
1685     if (end_backtick == std::string::npos) {
1686       // Stop if there's no end backtick.
1687       break;
1688     }
1689 
1690     if (end_backtick == expr_content_start) {
1691       // Skip over empty expression. (two backticks in a row)
1692       command.erase(start_backtick, 2);
1693       continue;
1694     }
1695 
1696     std::string expr_str(command, expr_content_start,
1697                          end_backtick - expr_content_start);
1698 
1699     ExecutionContext exe_ctx(GetExecutionContext());
1700 
1701     // Get a dummy target to allow for calculator mode while processing
1702     // backticks. This also helps break the infinite loop caused when target is
1703     // null.
1704     Target *exe_target = exe_ctx.GetTargetPtr();
1705     Target &target = exe_target ? *exe_target : m_debugger.GetDummyTarget();
1706 
1707     ValueObjectSP expr_result_valobj_sp;
1708 
1709     EvaluateExpressionOptions options;
1710     options.SetCoerceToId(false);
1711     options.SetUnwindOnError(true);
1712     options.SetIgnoreBreakpoints(true);
1713     options.SetKeepInMemory(false);
1714     options.SetTryAllThreads(true);
1715     options.SetTimeout(llvm::None);
1716 
1717     ExpressionResults expr_result =
1718         target.EvaluateExpression(expr_str.c_str(), exe_ctx.GetFramePtr(),
1719                                   expr_result_valobj_sp, options);
1720 
1721     if (expr_result == eExpressionCompleted) {
1722       Scalar scalar;
1723       if (expr_result_valobj_sp)
1724         expr_result_valobj_sp =
1725             expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1726                 expr_result_valobj_sp->GetDynamicValueType(), true);
1727       if (expr_result_valobj_sp->ResolveValue(scalar)) {
1728         command.erase(start_backtick, end_backtick - start_backtick + 1);
1729         StreamString value_strm;
1730         const bool show_type = false;
1731         scalar.GetValue(&value_strm, show_type);
1732         size_t value_string_size = value_strm.GetSize();
1733         if (value_string_size) {
1734           command.insert(start_backtick, std::string(value_strm.GetString()));
1735           pos = start_backtick + value_string_size;
1736           continue;
1737         } else {
1738           error.SetErrorStringWithFormat("expression value didn't result "
1739                                          "in a scalar value for the "
1740                                          "expression '%s'",
1741                                          expr_str.c_str());
1742           break;
1743         }
1744       } else {
1745         error.SetErrorStringWithFormat("expression value didn't result "
1746                                        "in a scalar value for the "
1747                                        "expression '%s'",
1748                                        expr_str.c_str());
1749         break;
1750       }
1751 
1752       continue;
1753     }
1754 
1755     if (expr_result_valobj_sp)
1756       error = expr_result_valobj_sp->GetError();
1757 
1758     if (error.Success()) {
1759       switch (expr_result) {
1760       case eExpressionSetupError:
1761         error.SetErrorStringWithFormat(
1762             "expression setup error for the expression '%s'", expr_str.c_str());
1763         break;
1764       case eExpressionParseError:
1765         error.SetErrorStringWithFormat(
1766             "expression parse error for the expression '%s'", expr_str.c_str());
1767         break;
1768       case eExpressionResultUnavailable:
1769         error.SetErrorStringWithFormat(
1770             "expression error fetching result for the expression '%s'",
1771             expr_str.c_str());
1772         break;
1773       case eExpressionCompleted:
1774         break;
1775       case eExpressionDiscarded:
1776         error.SetErrorStringWithFormat(
1777             "expression discarded for the expression '%s'", expr_str.c_str());
1778         break;
1779       case eExpressionInterrupted:
1780         error.SetErrorStringWithFormat(
1781             "expression interrupted for the expression '%s'", expr_str.c_str());
1782         break;
1783       case eExpressionHitBreakpoint:
1784         error.SetErrorStringWithFormat(
1785             "expression hit breakpoint for the expression '%s'",
1786             expr_str.c_str());
1787         break;
1788       case eExpressionTimedOut:
1789         error.SetErrorStringWithFormat(
1790             "expression timed out for the expression '%s'", expr_str.c_str());
1791         break;
1792       case eExpressionStoppedForDebug:
1793         error.SetErrorStringWithFormat("expression stop at entry point "
1794                                        "for debugging for the "
1795                                        "expression '%s'",
1796                                        expr_str.c_str());
1797         break;
1798       case eExpressionThreadVanished:
1799         error.SetErrorStringWithFormat(
1800             "expression thread vanished for the expression '%s'",
1801             expr_str.c_str());
1802         break;
1803       }
1804     }
1805   }
1806   return error;
1807 }
1808 
1809 bool CommandInterpreter::HandleCommand(const char *command_line,
1810                                        LazyBool lazy_add_to_history,
1811                                        const ExecutionContext &override_context,
1812                                        CommandReturnObject &result) {
1813 
1814   OverrideExecutionContext(override_context);
1815   bool status = HandleCommand(command_line, lazy_add_to_history, result);
1816   RestoreExecutionContext();
1817   return status;
1818 }
1819 
1820 bool CommandInterpreter::HandleCommand(const char *command_line,
1821                                        LazyBool lazy_add_to_history,
1822                                        CommandReturnObject &result) {
1823 
1824   std::string command_string(command_line);
1825   std::string original_command_string(command_line);
1826 
1827   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
1828   llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
1829                                    command_line);
1830 
1831   LLDB_LOGF(log, "Processing command: %s", command_line);
1832   LLDB_SCOPED_TIMERF("Processing command: %s.", command_line);
1833 
1834   if (WasInterrupted()) {
1835     result.AppendError("interrupted");
1836     return false;
1837   }
1838 
1839   bool add_to_history;
1840   if (lazy_add_to_history == eLazyBoolCalculate)
1841     add_to_history = (m_command_source_depth == 0);
1842   else
1843     add_to_history = (lazy_add_to_history == eLazyBoolYes);
1844 
1845   m_transcript_stream << "(lldb) " << command_line << '\n';
1846 
1847   bool empty_command = false;
1848   bool comment_command = false;
1849   if (command_string.empty())
1850     empty_command = true;
1851   else {
1852     const char *k_space_characters = "\t\n\v\f\r ";
1853 
1854     size_t non_space = command_string.find_first_not_of(k_space_characters);
1855     // Check for empty line or comment line (lines whose first non-space
1856     // character is the comment character for this interpreter)
1857     if (non_space == std::string::npos)
1858       empty_command = true;
1859     else if (command_string[non_space] == m_comment_char)
1860       comment_command = true;
1861     else if (command_string[non_space] == CommandHistory::g_repeat_char) {
1862       llvm::StringRef search_str(command_string);
1863       search_str = search_str.drop_front(non_space);
1864       if (auto hist_str = m_command_history.FindString(search_str)) {
1865         add_to_history = false;
1866         command_string = std::string(*hist_str);
1867         original_command_string = std::string(*hist_str);
1868       } else {
1869         result.AppendErrorWithFormat("Could not find entry: %s in history",
1870                                      command_string.c_str());
1871         return false;
1872       }
1873     }
1874   }
1875 
1876   if (empty_command) {
1877     if (!GetRepeatPreviousCommand()) {
1878       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1879       return true;
1880     }
1881 
1882     if (m_command_history.IsEmpty()) {
1883       result.AppendError("empty command");
1884       return false;
1885     }
1886 
1887     command_line = m_repeat_command.c_str();
1888     command_string = command_line;
1889     original_command_string = command_line;
1890     if (m_repeat_command.empty()) {
1891       result.AppendError("No auto repeat.");
1892       return false;
1893     }
1894 
1895     add_to_history = false;
1896   } else if (comment_command) {
1897     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1898     return true;
1899   }
1900 
1901   Status error(PreprocessCommand(command_string));
1902 
1903   if (error.Fail()) {
1904     result.AppendError(error.AsCString());
1905     return false;
1906   }
1907 
1908   // Phase 1.
1909 
1910   // Before we do ANY kind of argument processing, we need to figure out what
1911   // the real/final command object is for the specified command.  This gets
1912   // complicated by the fact that the user could have specified an alias, and,
1913   // in translating the alias, there may also be command options and/or even
1914   // data (including raw text strings) that need to be found and inserted into
1915   // the command line as part of the translation.  So this first step is plain
1916   // look-up and replacement, resulting in:
1917   //    1. the command object whose Execute method will actually be called
1918   //    2. a revised command string, with all substitutions and replacements
1919   //       taken care of
1920   // From 1 above, we can determine whether the Execute function wants raw
1921   // input or not.
1922 
1923   CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1924 
1925   // Although the user may have abbreviated the command, the command_string now
1926   // has the command expanded to the full name.  For example, if the input was
1927   // "br s -n main", command_string is now "breakpoint set -n main".
1928   if (log) {
1929     llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1930     LLDB_LOGF(log, "HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
1931     LLDB_LOGF(log, "HandleCommand, (revised) command_string: '%s'",
1932               command_string.c_str());
1933     const bool wants_raw_input =
1934         (cmd_obj != nullptr) ? cmd_obj->WantsRawCommandString() : false;
1935     LLDB_LOGF(log, "HandleCommand, wants_raw_input:'%s'",
1936               wants_raw_input ? "True" : "False");
1937   }
1938 
1939   // Phase 2.
1940   // Take care of things like setting up the history command & calling the
1941   // appropriate Execute method on the CommandObject, with the appropriate
1942   // arguments.
1943 
1944   if (cmd_obj != nullptr) {
1945     if (add_to_history) {
1946       Args command_args(command_string);
1947       const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1948       if (repeat_command != nullptr)
1949         m_repeat_command.assign(repeat_command);
1950       else
1951         m_repeat_command.assign(original_command_string);
1952 
1953       m_command_history.AppendString(original_command_string);
1954     }
1955 
1956     std::string remainder;
1957     const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
1958     if (actual_cmd_name_len < command_string.length())
1959       remainder = command_string.substr(actual_cmd_name_len);
1960 
1961     // Remove any initial spaces
1962     size_t pos = remainder.find_first_not_of(k_white_space);
1963     if (pos != 0 && pos != std::string::npos)
1964       remainder.erase(0, pos);
1965 
1966     LLDB_LOGF(
1967         log, "HandleCommand, command line after removing command name(s): '%s'",
1968         remainder.c_str());
1969 
1970     cmd_obj->Execute(remainder.c_str(), result);
1971   }
1972 
1973   LLDB_LOGF(log, "HandleCommand, command %s",
1974             (result.Succeeded() ? "succeeded" : "did not succeed"));
1975 
1976   m_transcript_stream << result.GetOutputData();
1977   m_transcript_stream << result.GetErrorData();
1978 
1979   return result.Succeeded();
1980 }
1981 
1982 void CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
1983   bool look_for_subcommand = false;
1984 
1985   // For any of the command completions a unique match will be a complete word.
1986 
1987   if (request.GetParsedLine().GetArgumentCount() == 0) {
1988     // We got nothing on the command line, so return the list of commands
1989     bool include_aliases = true;
1990     StringList new_matches, descriptions;
1991     GetCommandNamesMatchingPartialString("", include_aliases, new_matches,
1992                                          descriptions);
1993     request.AddCompletions(new_matches, descriptions);
1994   } else if (request.GetCursorIndex() == 0) {
1995     // The cursor is in the first argument, so just do a lookup in the
1996     // dictionary.
1997     StringList new_matches, new_descriptions;
1998     CommandObject *cmd_obj =
1999         GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
2000                          &new_matches, &new_descriptions);
2001 
2002     if (new_matches.GetSize() && cmd_obj && cmd_obj->IsMultiwordObject() &&
2003         new_matches.GetStringAtIndex(0) != nullptr &&
2004         strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
2005                new_matches.GetStringAtIndex(0)) == 0) {
2006       if (request.GetParsedLine().GetArgumentCount() != 1) {
2007         look_for_subcommand = true;
2008         new_matches.DeleteStringAtIndex(0);
2009         new_descriptions.DeleteStringAtIndex(0);
2010         request.AppendEmptyArgument();
2011       }
2012     }
2013     request.AddCompletions(new_matches, new_descriptions);
2014   }
2015 
2016   if (request.GetCursorIndex() > 0 || look_for_subcommand) {
2017     // We are completing further on into a commands arguments, so find the
2018     // command and tell it to complete the command. First see if there is a
2019     // matching initial command:
2020     CommandObject *command_object =
2021         GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
2022     if (command_object) {
2023       request.ShiftArguments();
2024       command_object->HandleCompletion(request);
2025     }
2026   }
2027 }
2028 
2029 void CommandInterpreter::HandleCompletion(CompletionRequest &request) {
2030 
2031   // Don't complete comments, and if the line we are completing is just the
2032   // history repeat character, substitute the appropriate history line.
2033   llvm::StringRef first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
2034 
2035   if (!first_arg.empty()) {
2036     if (first_arg.front() == m_comment_char)
2037       return;
2038     if (first_arg.front() == CommandHistory::g_repeat_char) {
2039       if (auto hist_str = m_command_history.FindString(first_arg))
2040         request.AddCompletion(*hist_str, "Previous command history event",
2041                               CompletionMode::RewriteLine);
2042       return;
2043     }
2044   }
2045 
2046   HandleCompletionMatches(request);
2047 }
2048 
2049 llvm::Optional<std::string>
2050 CommandInterpreter::GetAutoSuggestionForCommand(llvm::StringRef line) {
2051   if (line.empty())
2052     return llvm::None;
2053   const size_t s = m_command_history.GetSize();
2054   for (int i = s - 1; i >= 0; --i) {
2055     llvm::StringRef entry = m_command_history.GetStringAtIndex(i);
2056     if (entry.consume_front(line))
2057       return entry.str();
2058   }
2059   return llvm::None;
2060 }
2061 
2062 void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
2063   EventSP prompt_change_event_sp(
2064       new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
2065   ;
2066   BroadcastEvent(prompt_change_event_sp);
2067   if (m_command_io_handler_sp)
2068     m_command_io_handler_sp->SetPrompt(new_prompt);
2069 }
2070 
2071 bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
2072   // Check AutoConfirm first:
2073   if (m_debugger.GetAutoConfirm())
2074     return default_answer;
2075 
2076   IOHandlerConfirm *confirm =
2077       new IOHandlerConfirm(m_debugger, message, default_answer);
2078   IOHandlerSP io_handler_sp(confirm);
2079   m_debugger.RunIOHandlerSync(io_handler_sp);
2080   return confirm->GetResponse();
2081 }
2082 
2083 const CommandAlias *
2084 CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
2085   OptionArgVectorSP ret_val;
2086 
2087   auto pos = m_alias_dict.find(std::string(alias_name));
2088   if (pos != m_alias_dict.end())
2089     return (CommandAlias *)pos->second.get();
2090 
2091   return nullptr;
2092 }
2093 
2094 bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
2095 
2096 bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
2097 
2098 bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
2099 
2100 bool CommandInterpreter::HasUserMultiwordCommands() const {
2101   return (!m_user_mw_dict.empty());
2102 }
2103 
2104 bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
2105 
2106 void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
2107                                                const char *alias_name,
2108                                                Args &cmd_args,
2109                                                std::string &raw_input_string,
2110                                                CommandReturnObject &result) {
2111   OptionArgVectorSP option_arg_vector_sp =
2112       GetAlias(alias_name)->GetOptionArguments();
2113 
2114   bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
2115 
2116   // Make sure that the alias name is the 0th element in cmd_args
2117   std::string alias_name_str = alias_name;
2118   if (alias_name_str != cmd_args.GetArgumentAtIndex(0))
2119     cmd_args.Unshift(alias_name_str);
2120 
2121   Args new_args(alias_cmd_obj->GetCommandName());
2122   if (new_args.GetArgumentCount() == 2)
2123     new_args.Shift();
2124 
2125   if (option_arg_vector_sp.get()) {
2126     if (wants_raw_input) {
2127       // We have a command that both has command options and takes raw input.
2128       // Make *sure* it has a " -- " in the right place in the
2129       // raw_input_string.
2130       size_t pos = raw_input_string.find(" -- ");
2131       if (pos == std::string::npos) {
2132         // None found; assume it goes at the beginning of the raw input string
2133         raw_input_string.insert(0, " -- ");
2134       }
2135     }
2136 
2137     OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2138     const size_t old_size = cmd_args.GetArgumentCount();
2139     std::vector<bool> used(old_size + 1, false);
2140 
2141     used[0] = true;
2142 
2143     int value_type;
2144     std::string option;
2145     std::string value;
2146     for (const auto &option_entry : *option_arg_vector) {
2147       std::tie(option, value_type, value) = option_entry;
2148       if (option == "<argument>") {
2149         if (!wants_raw_input || (value != "--")) {
2150           // Since we inserted this above, make sure we don't insert it twice
2151           new_args.AppendArgument(value);
2152         }
2153         continue;
2154       }
2155 
2156       if (value_type != OptionParser::eOptionalArgument)
2157         new_args.AppendArgument(option);
2158 
2159       if (value == "<no-argument>")
2160         continue;
2161 
2162       int index = GetOptionArgumentPosition(value.c_str());
2163       if (index == 0) {
2164         // value was NOT a positional argument; must be a real value
2165         if (value_type != OptionParser::eOptionalArgument)
2166           new_args.AppendArgument(value);
2167         else {
2168           new_args.AppendArgument(option + value);
2169         }
2170 
2171       } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
2172         result.AppendErrorWithFormat("Not enough arguments provided; you "
2173                                      "need at least %d arguments to use "
2174                                      "this alias.\n",
2175                                      index);
2176         return;
2177       } else {
2178         // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2179         size_t strpos =
2180             raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2181         if (strpos != std::string::npos) {
2182           raw_input_string = raw_input_string.erase(
2183               strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2184         }
2185 
2186         if (value_type != OptionParser::eOptionalArgument)
2187           new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2188         else {
2189           new_args.AppendArgument(option + cmd_args.GetArgumentAtIndex(index));
2190         }
2191         used[index] = true;
2192       }
2193     }
2194 
2195     for (auto entry : llvm::enumerate(cmd_args.entries())) {
2196       if (!used[entry.index()] && !wants_raw_input)
2197         new_args.AppendArgument(entry.value().ref());
2198     }
2199 
2200     cmd_args.Clear();
2201     cmd_args.SetArguments(new_args.GetArgumentCount(),
2202                           new_args.GetConstArgumentVector());
2203   } else {
2204     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2205     // This alias was not created with any options; nothing further needs to be
2206     // done, unless it is a command that wants raw input, in which case we need
2207     // to clear the rest of the data from cmd_args, since its in the raw input
2208     // string.
2209     if (wants_raw_input) {
2210       cmd_args.Clear();
2211       cmd_args.SetArguments(new_args.GetArgumentCount(),
2212                             new_args.GetConstArgumentVector());
2213     }
2214     return;
2215   }
2216 
2217   result.SetStatus(eReturnStatusSuccessFinishNoResult);
2218   return;
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   return;
2567 }
2568 
2569 // Make flags that we can pass into the IOHandler so our delegates can do the
2570 // right thing
2571 enum {
2572   eHandleCommandFlagStopOnContinue = (1u << 0),
2573   eHandleCommandFlagStopOnError = (1u << 1),
2574   eHandleCommandFlagEchoCommand = (1u << 2),
2575   eHandleCommandFlagEchoCommentCommand = (1u << 3),
2576   eHandleCommandFlagPrintResult = (1u << 4),
2577   eHandleCommandFlagPrintErrors = (1u << 5),
2578   eHandleCommandFlagStopOnCrash = (1u << 6)
2579 };
2580 
2581 void CommandInterpreter::HandleCommandsFromFile(
2582     FileSpec &cmd_file, const ExecutionContext &context,
2583     const CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2584   OverrideExecutionContext(context);
2585   HandleCommandsFromFile(cmd_file, options, result);
2586   RestoreExecutionContext();
2587 }
2588 
2589 void CommandInterpreter::HandleCommandsFromFile(FileSpec &cmd_file,
2590     const CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2591   if (!FileSystem::Instance().Exists(cmd_file)) {
2592     result.AppendErrorWithFormat(
2593         "Error reading commands from file %s - file not found.\n",
2594         cmd_file.GetFilename().AsCString("<Unknown>"));
2595     return;
2596   }
2597 
2598   std::string cmd_file_path = cmd_file.GetPath();
2599   auto input_file_up =
2600       FileSystem::Instance().Open(cmd_file, File::eOpenOptionReadOnly);
2601   if (!input_file_up) {
2602     std::string error = llvm::toString(input_file_up.takeError());
2603     result.AppendErrorWithFormatv(
2604         "error: an error occurred read file '{0}': {1}\n", cmd_file_path,
2605         llvm::fmt_consume(input_file_up.takeError()));
2606     return;
2607   }
2608   FileSP input_file_sp = FileSP(std::move(input_file_up.get()));
2609 
2610   Debugger &debugger = GetDebugger();
2611 
2612   uint32_t flags = 0;
2613 
2614   if (options.m_stop_on_continue == eLazyBoolCalculate) {
2615     if (m_command_source_flags.empty()) {
2616       // Stop on continue by default
2617       flags |= eHandleCommandFlagStopOnContinue;
2618     } else if (m_command_source_flags.back() &
2619                eHandleCommandFlagStopOnContinue) {
2620       flags |= eHandleCommandFlagStopOnContinue;
2621     }
2622   } else if (options.m_stop_on_continue == eLazyBoolYes) {
2623     flags |= eHandleCommandFlagStopOnContinue;
2624   }
2625 
2626   if (options.m_stop_on_error == eLazyBoolCalculate) {
2627     if (m_command_source_flags.empty()) {
2628       if (GetStopCmdSourceOnError())
2629         flags |= eHandleCommandFlagStopOnError;
2630     } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2631       flags |= eHandleCommandFlagStopOnError;
2632     }
2633   } else if (options.m_stop_on_error == eLazyBoolYes) {
2634     flags |= eHandleCommandFlagStopOnError;
2635   }
2636 
2637   // stop-on-crash can only be set, if it is present in all levels of
2638   // pushed flag sets.
2639   if (options.GetStopOnCrash()) {
2640     if (m_command_source_flags.empty()) {
2641       flags |= eHandleCommandFlagStopOnCrash;
2642     } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2643       flags |= eHandleCommandFlagStopOnCrash;
2644     }
2645   }
2646 
2647   if (options.m_echo_commands == eLazyBoolCalculate) {
2648     if (m_command_source_flags.empty()) {
2649       // Echo command by default
2650       flags |= eHandleCommandFlagEchoCommand;
2651     } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2652       flags |= eHandleCommandFlagEchoCommand;
2653     }
2654   } else if (options.m_echo_commands == eLazyBoolYes) {
2655     flags |= eHandleCommandFlagEchoCommand;
2656   }
2657 
2658   // We will only ever ask for this flag, if we echo commands in general.
2659   if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2660     if (m_command_source_flags.empty()) {
2661       // Echo comments by default
2662       flags |= eHandleCommandFlagEchoCommentCommand;
2663     } else if (m_command_source_flags.back() &
2664                eHandleCommandFlagEchoCommentCommand) {
2665       flags |= eHandleCommandFlagEchoCommentCommand;
2666     }
2667   } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2668     flags |= eHandleCommandFlagEchoCommentCommand;
2669   }
2670 
2671   if (options.m_print_results == eLazyBoolCalculate) {
2672     if (m_command_source_flags.empty()) {
2673       // Print output by default
2674       flags |= eHandleCommandFlagPrintResult;
2675     } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2676       flags |= eHandleCommandFlagPrintResult;
2677     }
2678   } else if (options.m_print_results == eLazyBoolYes) {
2679     flags |= eHandleCommandFlagPrintResult;
2680   }
2681 
2682   if (options.m_print_errors == eLazyBoolCalculate) {
2683     if (m_command_source_flags.empty()) {
2684       // Print output by default
2685       flags |= eHandleCommandFlagPrintErrors;
2686     } else if (m_command_source_flags.back() & eHandleCommandFlagPrintErrors) {
2687       flags |= eHandleCommandFlagPrintErrors;
2688     }
2689   } else if (options.m_print_errors == eLazyBoolYes) {
2690     flags |= eHandleCommandFlagPrintErrors;
2691   }
2692 
2693   if (flags & eHandleCommandFlagPrintResult) {
2694     debugger.GetOutputFile().Printf("Executing commands in '%s'.\n",
2695                                     cmd_file_path.c_str());
2696   }
2697 
2698   // Used for inheriting the right settings when "command source" might
2699   // have nested "command source" commands
2700   lldb::StreamFileSP empty_stream_sp;
2701   m_command_source_flags.push_back(flags);
2702   IOHandlerSP io_handler_sp(new IOHandlerEditline(
2703       debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2704       empty_stream_sp, // Pass in an empty stream so we inherit the top
2705                        // input reader output stream
2706       empty_stream_sp, // Pass in an empty stream so we inherit the top
2707                        // input reader error stream
2708       flags,
2709       nullptr, // Pass in NULL for "editline_name" so no history is saved,
2710                // or written
2711       debugger.GetPrompt(), llvm::StringRef(),
2712       false, // Not multi-line
2713       debugger.GetUseColor(), 0, *this, nullptr));
2714   const bool old_async_execution = debugger.GetAsyncExecution();
2715 
2716   // Set synchronous execution if we are not stopping on continue
2717   if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2718     debugger.SetAsyncExecution(false);
2719 
2720   m_command_source_depth++;
2721   m_command_source_dirs.push_back(cmd_file.CopyByRemovingLastPathComponent());
2722 
2723   debugger.RunIOHandlerSync(io_handler_sp);
2724   if (!m_command_source_flags.empty())
2725     m_command_source_flags.pop_back();
2726 
2727   m_command_source_dirs.pop_back();
2728   m_command_source_depth--;
2729 
2730   result.SetStatus(eReturnStatusSuccessFinishNoResult);
2731   debugger.SetAsyncExecution(old_async_execution);
2732 }
2733 
2734 bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2735 
2736 void CommandInterpreter::SetSynchronous(bool value) {
2737   // Asynchronous mode is not supported during reproducer replay.
2738   if (repro::Reproducer::Instance().GetLoader())
2739     return;
2740   m_synchronous_execution = value;
2741 }
2742 
2743 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2744                                                  llvm::StringRef prefix,
2745                                                  llvm::StringRef help_text) {
2746   const uint32_t max_columns = m_debugger.GetTerminalWidth();
2747 
2748   size_t line_width_max = max_columns - prefix.size();
2749   if (line_width_max < 16)
2750     line_width_max = help_text.size() + prefix.size();
2751 
2752   strm.IndentMore(prefix.size());
2753   bool prefixed_yet = false;
2754   // Even if we have no help text we still want to emit the command name.
2755   if (help_text.empty())
2756     help_text = "No help text";
2757   while (!help_text.empty()) {
2758     // Prefix the first line, indent subsequent lines to line up
2759     if (!prefixed_yet) {
2760       strm << prefix;
2761       prefixed_yet = true;
2762     } else
2763       strm.Indent();
2764 
2765     // Never print more than the maximum on one line.
2766     llvm::StringRef this_line = help_text.substr(0, line_width_max);
2767 
2768     // Always break on an explicit newline.
2769     std::size_t first_newline = this_line.find_first_of("\n");
2770 
2771     // Don't break on space/tab unless the text is too long to fit on one line.
2772     std::size_t last_space = llvm::StringRef::npos;
2773     if (this_line.size() != help_text.size())
2774       last_space = this_line.find_last_of(" \t");
2775 
2776     // Break at whichever condition triggered first.
2777     this_line = this_line.substr(0, std::min(first_newline, last_space));
2778     strm.PutCString(this_line);
2779     strm.EOL();
2780 
2781     // Remove whitespace / newlines after breaking.
2782     help_text = help_text.drop_front(this_line.size()).ltrim();
2783   }
2784   strm.IndentLess(prefix.size());
2785 }
2786 
2787 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2788                                                  llvm::StringRef word_text,
2789                                                  llvm::StringRef separator,
2790                                                  llvm::StringRef help_text,
2791                                                  size_t max_word_len) {
2792   StreamString prefix_stream;
2793   prefix_stream.Printf("  %-*s %*s ", (int)max_word_len, word_text.data(),
2794                        (int)separator.size(), separator.data());
2795   OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2796 }
2797 
2798 void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2799                                         llvm::StringRef separator,
2800                                         llvm::StringRef help_text,
2801                                         uint32_t max_word_len) {
2802   int indent_size = max_word_len + separator.size() + 2;
2803 
2804   strm.IndentMore(indent_size);
2805 
2806   StreamString text_strm;
2807   text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2808   text_strm << separator << " " << help_text;
2809 
2810   const uint32_t max_columns = m_debugger.GetTerminalWidth();
2811 
2812   llvm::StringRef text = text_strm.GetString();
2813 
2814   uint32_t chars_left = max_columns;
2815 
2816   auto nextWordLength = [](llvm::StringRef S) {
2817     size_t pos = S.find(' ');
2818     return pos == llvm::StringRef::npos ? S.size() : pos;
2819   };
2820 
2821   while (!text.empty()) {
2822     if (text.front() == '\n' ||
2823         (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
2824       strm.EOL();
2825       strm.Indent();
2826       chars_left = max_columns - indent_size;
2827       if (text.front() == '\n')
2828         text = text.drop_front();
2829       else
2830         text = text.ltrim(' ');
2831     } else {
2832       strm.PutChar(text.front());
2833       --chars_left;
2834       text = text.drop_front();
2835     }
2836   }
2837 
2838   strm.EOL();
2839   strm.IndentLess(indent_size);
2840 }
2841 
2842 void CommandInterpreter::FindCommandsForApropos(
2843     llvm::StringRef search_word, StringList &commands_found,
2844     StringList &commands_help, CommandObject::CommandMap &command_map) {
2845   CommandObject::CommandMap::const_iterator pos;
2846 
2847   for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
2848     llvm::StringRef command_name = pos->first;
2849     CommandObject *cmd_obj = pos->second.get();
2850 
2851     const bool search_short_help = true;
2852     const bool search_long_help = false;
2853     const bool search_syntax = false;
2854     const bool search_options = false;
2855     if (command_name.contains_insensitive(search_word) ||
2856         cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2857                                       search_long_help, search_syntax,
2858                                       search_options)) {
2859       commands_found.AppendString(cmd_obj->GetCommandName());
2860       commands_help.AppendString(cmd_obj->GetHelp());
2861     }
2862 
2863     if (cmd_obj->IsMultiwordObject()) {
2864       CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2865       FindCommandsForApropos(search_word, commands_found, commands_help,
2866                              cmd_multiword->GetSubcommandDictionary());
2867     }
2868   }
2869 }
2870 
2871 void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
2872                                                 StringList &commands_found,
2873                                                 StringList &commands_help,
2874                                                 bool search_builtin_commands,
2875                                                 bool search_user_commands,
2876                                                 bool search_alias_commands,
2877                                                 bool search_user_mw_commands) {
2878   CommandObject::CommandMap::const_iterator pos;
2879 
2880   if (search_builtin_commands)
2881     FindCommandsForApropos(search_word, commands_found, commands_help,
2882                            m_command_dict);
2883 
2884   if (search_user_commands)
2885     FindCommandsForApropos(search_word, commands_found, commands_help,
2886                            m_user_dict);
2887 
2888   if (search_user_mw_commands)
2889     FindCommandsForApropos(search_word, commands_found, commands_help,
2890                            m_user_mw_dict);
2891 
2892   if (search_alias_commands)
2893     FindCommandsForApropos(search_word, commands_found, commands_help,
2894                            m_alias_dict);
2895 }
2896 
2897 ExecutionContext CommandInterpreter::GetExecutionContext() const {
2898   return !m_overriden_exe_contexts.empty()
2899              ? m_overriden_exe_contexts.top()
2900              : m_debugger.GetSelectedExecutionContext();
2901 }
2902 
2903 void CommandInterpreter::OverrideExecutionContext(
2904     const ExecutionContext &override_context) {
2905   m_overriden_exe_contexts.push(override_context);
2906 }
2907 
2908 void CommandInterpreter::RestoreExecutionContext() {
2909   if (!m_overriden_exe_contexts.empty())
2910     m_overriden_exe_contexts.pop();
2911 }
2912 
2913 void CommandInterpreter::GetProcessOutput() {
2914   if (ProcessSP process_sp = GetExecutionContext().GetProcessSP())
2915     m_debugger.FlushProcessOutput(*process_sp, /*flush_stdout*/ true,
2916                                   /*flush_stderr*/ true);
2917 }
2918 
2919 void CommandInterpreter::StartHandlingCommand() {
2920   auto idle_state = CommandHandlingState::eIdle;
2921   if (m_command_state.compare_exchange_strong(
2922           idle_state, CommandHandlingState::eInProgress))
2923     lldbassert(m_iohandler_nesting_level == 0);
2924   else
2925     lldbassert(m_iohandler_nesting_level > 0);
2926   ++m_iohandler_nesting_level;
2927 }
2928 
2929 void CommandInterpreter::FinishHandlingCommand() {
2930   lldbassert(m_iohandler_nesting_level > 0);
2931   if (--m_iohandler_nesting_level == 0) {
2932     auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2933     lldbassert(prev_state != CommandHandlingState::eIdle);
2934   }
2935 }
2936 
2937 bool CommandInterpreter::InterruptCommand() {
2938   auto in_progress = CommandHandlingState::eInProgress;
2939   return m_command_state.compare_exchange_strong(
2940       in_progress, CommandHandlingState::eInterrupted);
2941 }
2942 
2943 bool CommandInterpreter::WasInterrupted() const {
2944   bool was_interrupted =
2945       (m_command_state == CommandHandlingState::eInterrupted);
2946   lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2947   return was_interrupted;
2948 }
2949 
2950 void CommandInterpreter::PrintCommandOutput(Stream &stream,
2951                                             llvm::StringRef str) {
2952   // Split the output into lines and poll for interrupt requests
2953   const char *data = str.data();
2954   size_t size = str.size();
2955   while (size > 0 && !WasInterrupted()) {
2956     size_t chunk_size = 0;
2957     for (; chunk_size < size; ++chunk_size) {
2958       lldbassert(data[chunk_size] != '\0');
2959       if (data[chunk_size] == '\n') {
2960         ++chunk_size;
2961         break;
2962       }
2963     }
2964     chunk_size = stream.Write(data, chunk_size);
2965     lldbassert(size >= chunk_size);
2966     data += chunk_size;
2967     size -= chunk_size;
2968   }
2969   if (size > 0) {
2970     stream.Printf("\n... Interrupted.\n");
2971   }
2972 }
2973 
2974 bool CommandInterpreter::EchoCommandNonInteractive(
2975     llvm::StringRef line, const Flags &io_handler_flags) const {
2976   if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2977     return false;
2978 
2979   llvm::StringRef command = line.trim();
2980   if (command.empty())
2981     return true;
2982 
2983   if (command.front() == m_comment_char)
2984     return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2985 
2986   return true;
2987 }
2988 
2989 void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2990                                                 std::string &line) {
2991     // If we were interrupted, bail out...
2992     if (WasInterrupted())
2993       return;
2994 
2995   const bool is_interactive = io_handler.GetIsInteractive();
2996   if (!is_interactive) {
2997     // When we are not interactive, don't execute blank lines. This will happen
2998     // sourcing a commands file. We don't want blank lines to repeat the
2999     // previous command and cause any errors to occur (like redefining an
3000     // alias, get an error and stop parsing the commands file).
3001     if (line.empty())
3002       return;
3003 
3004     // When using a non-interactive file handle (like when sourcing commands
3005     // from a file) we need to echo the command out so we don't just see the
3006     // command output and no command...
3007     if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
3008       io_handler.GetOutputStreamFileSP()->Printf(
3009           "%s%s\n", io_handler.GetPrompt(), line.c_str());
3010   }
3011 
3012   StartHandlingCommand();
3013 
3014   OverrideExecutionContext(m_debugger.GetSelectedExecutionContext());
3015   auto finalize = llvm::make_scope_exit([this]() {
3016     RestoreExecutionContext();
3017   });
3018 
3019   lldb_private::CommandReturnObject result(m_debugger.GetUseColor());
3020   HandleCommand(line.c_str(), eLazyBoolCalculate, result);
3021 
3022   // Now emit the command output text from the command we just executed
3023   if ((result.Succeeded() &&
3024        io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) ||
3025       io_handler.GetFlags().Test(eHandleCommandFlagPrintErrors)) {
3026     // Display any STDOUT/STDERR _prior_ to emitting the command result text
3027     GetProcessOutput();
3028 
3029     if (!result.GetImmediateOutputStream()) {
3030       llvm::StringRef output = result.GetOutputData();
3031       PrintCommandOutput(*io_handler.GetOutputStreamFileSP(), output);
3032     }
3033 
3034     // Now emit the command error text from the command we just executed
3035     if (!result.GetImmediateErrorStream()) {
3036       llvm::StringRef error = result.GetErrorData();
3037       PrintCommandOutput(*io_handler.GetErrorStreamFileSP(), error);
3038     }
3039   }
3040 
3041   FinishHandlingCommand();
3042 
3043   switch (result.GetStatus()) {
3044   case eReturnStatusInvalid:
3045   case eReturnStatusSuccessFinishNoResult:
3046   case eReturnStatusSuccessFinishResult:
3047   case eReturnStatusStarted:
3048     break;
3049 
3050   case eReturnStatusSuccessContinuingNoResult:
3051   case eReturnStatusSuccessContinuingResult:
3052     if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3053       io_handler.SetIsDone(true);
3054     break;
3055 
3056   case eReturnStatusFailed:
3057     m_result.IncrementNumberOfErrors();
3058     if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError)) {
3059       m_result.SetResult(lldb::eCommandInterpreterResultCommandError);
3060       io_handler.SetIsDone(true);
3061     }
3062     break;
3063 
3064   case eReturnStatusQuit:
3065     m_result.SetResult(lldb::eCommandInterpreterResultQuitRequested);
3066     io_handler.SetIsDone(true);
3067     break;
3068   }
3069 
3070   // Finally, if we're going to stop on crash, check that here:
3071   if (m_result.IsResult(lldb::eCommandInterpreterResultSuccess) &&
3072       result.GetDidChangeProcessState() &&
3073       io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash) &&
3074       DidProcessStopAbnormally()) {
3075     io_handler.SetIsDone(true);
3076     m_result.SetResult(lldb::eCommandInterpreterResultInferiorCrash);
3077   }
3078 }
3079 
3080 bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
3081   ExecutionContext exe_ctx(GetExecutionContext());
3082   Process *process = exe_ctx.GetProcessPtr();
3083 
3084   if (InterruptCommand())
3085     return true;
3086 
3087   if (process) {
3088     StateType state = process->GetState();
3089     if (StateIsRunningState(state)) {
3090       process->Halt();
3091       return true; // Don't do any updating when we are running
3092     }
3093   }
3094 
3095   ScriptInterpreter *script_interpreter =
3096       m_debugger.GetScriptInterpreter(false);
3097   if (script_interpreter) {
3098     if (script_interpreter->Interrupt())
3099       return true;
3100   }
3101   return false;
3102 }
3103 
3104 bool CommandInterpreter::SaveTranscript(
3105     CommandReturnObject &result, llvm::Optional<std::string> output_file) {
3106   if (output_file == llvm::None || output_file->empty()) {
3107     std::string now = llvm::to_string(std::chrono::system_clock::now());
3108     std::replace(now.begin(), now.end(), ' ', '_');
3109     const std::string file_name = "lldb_session_" + now + ".log";
3110 
3111     FileSpec save_location = GetSaveSessionDirectory();
3112 
3113     if (!save_location)
3114       save_location = HostInfo::GetGlobalTempDir();
3115 
3116     FileSystem::Instance().Resolve(save_location);
3117     save_location.AppendPathComponent(file_name);
3118     output_file = save_location.GetPath();
3119   }
3120 
3121   auto error_out = [&](llvm::StringRef error_message, std::string description) {
3122     LLDB_LOG(GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS), "{0} ({1}:{2})",
3123              error_message, output_file, description);
3124     result.AppendErrorWithFormatv(
3125         "Failed to save session's transcripts to {0}!", *output_file);
3126     return false;
3127   };
3128 
3129   File::OpenOptions flags = File::eOpenOptionWriteOnly |
3130                             File::eOpenOptionCanCreate |
3131                             File::eOpenOptionTruncate;
3132 
3133   auto opened_file = FileSystem::Instance().Open(FileSpec(*output_file), flags);
3134 
3135   if (!opened_file)
3136     return error_out("Unable to create file",
3137                      llvm::toString(opened_file.takeError()));
3138 
3139   FileUP file = std::move(opened_file.get());
3140 
3141   size_t byte_size = m_transcript_stream.GetSize();
3142 
3143   Status error = file->Write(m_transcript_stream.GetData(), byte_size);
3144 
3145   if (error.Fail() || byte_size != m_transcript_stream.GetSize())
3146     return error_out("Unable to write to destination file",
3147                      "Bytes written do not match transcript size.");
3148 
3149   result.SetStatus(eReturnStatusSuccessFinishNoResult);
3150   result.AppendMessageWithFormat("Session's transcripts saved to %s\n",
3151                                  output_file->c_str());
3152 
3153   return true;
3154 }
3155 
3156 FileSpec CommandInterpreter::GetCurrentSourceDir() {
3157   if (m_command_source_dirs.empty())
3158     return {};
3159   return m_command_source_dirs.back();
3160 }
3161 
3162 void CommandInterpreter::GetLLDBCommandsFromIOHandler(
3163     const char *prompt, IOHandlerDelegate &delegate, void *baton) {
3164   Debugger &debugger = GetDebugger();
3165   IOHandlerSP io_handler_sp(
3166       new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
3167                             "lldb", // Name of input reader for history
3168                             llvm::StringRef(prompt), // Prompt
3169                             llvm::StringRef(),       // Continuation prompt
3170                             true,                    // Get multiple lines
3171                             debugger.GetUseColor(),
3172                             0,         // Don't show line numbers
3173                             delegate,  // IOHandlerDelegate
3174                             nullptr)); // FileShadowCollector
3175 
3176   if (io_handler_sp) {
3177     io_handler_sp->SetUserData(baton);
3178     debugger.RunIOHandlerAsync(io_handler_sp);
3179   }
3180 }
3181 
3182 void CommandInterpreter::GetPythonCommandsFromIOHandler(
3183     const char *prompt, IOHandlerDelegate &delegate, void *baton) {
3184   Debugger &debugger = GetDebugger();
3185   IOHandlerSP io_handler_sp(
3186       new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
3187                             "lldb-python", // Name of input reader for history
3188                             llvm::StringRef(prompt), // Prompt
3189                             llvm::StringRef(),       // Continuation prompt
3190                             true,                    // Get multiple lines
3191                             debugger.GetUseColor(),
3192                             0,         // Don't show line numbers
3193                             delegate,  // IOHandlerDelegate
3194                             nullptr)); // FileShadowCollector
3195 
3196   if (io_handler_sp) {
3197     io_handler_sp->SetUserData(baton);
3198     debugger.RunIOHandlerAsync(io_handler_sp);
3199   }
3200 }
3201 
3202 bool CommandInterpreter::IsActive() {
3203   return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
3204 }
3205 
3206 lldb::IOHandlerSP
3207 CommandInterpreter::GetIOHandler(bool force_create,
3208                                  CommandInterpreterRunOptions *options) {
3209   // Always re-create the IOHandlerEditline in case the input changed. The old
3210   // instance might have had a non-interactive input and now it does or vice
3211   // versa.
3212   if (force_create || !m_command_io_handler_sp) {
3213     // Always re-create the IOHandlerEditline in case the input changed. The
3214     // old instance might have had a non-interactive input and now it does or
3215     // vice versa.
3216     uint32_t flags = 0;
3217 
3218     if (options) {
3219       if (options->m_stop_on_continue == eLazyBoolYes)
3220         flags |= eHandleCommandFlagStopOnContinue;
3221       if (options->m_stop_on_error == eLazyBoolYes)
3222         flags |= eHandleCommandFlagStopOnError;
3223       if (options->m_stop_on_crash == eLazyBoolYes)
3224         flags |= eHandleCommandFlagStopOnCrash;
3225       if (options->m_echo_commands != eLazyBoolNo)
3226         flags |= eHandleCommandFlagEchoCommand;
3227       if (options->m_echo_comment_commands != eLazyBoolNo)
3228         flags |= eHandleCommandFlagEchoCommentCommand;
3229       if (options->m_print_results != eLazyBoolNo)
3230         flags |= eHandleCommandFlagPrintResult;
3231       if (options->m_print_errors != eLazyBoolNo)
3232         flags |= eHandleCommandFlagPrintErrors;
3233     } else {
3234       flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult |
3235               eHandleCommandFlagPrintErrors;
3236     }
3237 
3238     m_command_io_handler_sp = std::make_shared<IOHandlerEditline>(
3239         m_debugger, IOHandler::Type::CommandInterpreter,
3240         m_debugger.GetInputFileSP(), m_debugger.GetOutputStreamSP(),
3241         m_debugger.GetErrorStreamSP(), flags, "lldb", m_debugger.GetPrompt(),
3242         llvm::StringRef(), // Continuation prompt
3243         false, // Don't enable multiple line input, just single line commands
3244         m_debugger.GetUseColor(),
3245         0,     // Don't show line numbers
3246         *this, // IOHandlerDelegate
3247         GetDebugger().GetInputRecorder());
3248   }
3249   return m_command_io_handler_sp;
3250 }
3251 
3252 CommandInterpreterRunResult CommandInterpreter::RunCommandInterpreter(
3253     CommandInterpreterRunOptions &options) {
3254   // Always re-create the command interpreter when we run it in case any file
3255   // handles have changed.
3256   bool force_create = true;
3257   m_debugger.RunIOHandlerAsync(GetIOHandler(force_create, &options));
3258   m_result = CommandInterpreterRunResult();
3259 
3260   if (options.GetAutoHandleEvents())
3261     m_debugger.StartEventHandlerThread();
3262 
3263   if (options.GetSpawnThread()) {
3264     m_debugger.StartIOHandlerThread();
3265   } else {
3266     m_debugger.RunIOHandlers();
3267 
3268     if (options.GetAutoHandleEvents())
3269       m_debugger.StopEventHandlerThread();
3270   }
3271 
3272   return m_result;
3273 }
3274 
3275 CommandObject *
3276 CommandInterpreter::ResolveCommandImpl(std::string &command_line,
3277                                        CommandReturnObject &result) {
3278   std::string scratch_command(command_line); // working copy so we don't modify
3279                                              // command_line unless we succeed
3280   CommandObject *cmd_obj = nullptr;
3281   StreamString revised_command_line;
3282   bool wants_raw_input = false;
3283   std::string next_word;
3284   StringList matches;
3285   bool done = false;
3286   while (!done) {
3287     char quote_char = '\0';
3288     std::string suffix;
3289     ExtractCommand(scratch_command, next_word, suffix, quote_char);
3290     if (cmd_obj == nullptr) {
3291       std::string full_name;
3292       bool is_alias = GetAliasFullName(next_word, full_name);
3293       cmd_obj = GetCommandObject(next_word, &matches);
3294       bool is_real_command =
3295           (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
3296       if (!is_real_command) {
3297         matches.Clear();
3298         std::string alias_result;
3299         cmd_obj =
3300             BuildAliasResult(full_name, scratch_command, alias_result, result);
3301         revised_command_line.Printf("%s", alias_result.c_str());
3302         if (cmd_obj) {
3303           wants_raw_input = cmd_obj->WantsRawCommandString();
3304         }
3305       } else {
3306         if (cmd_obj) {
3307           llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3308           revised_command_line.Printf("%s", cmd_name.str().c_str());
3309           wants_raw_input = cmd_obj->WantsRawCommandString();
3310         } else {
3311           revised_command_line.Printf("%s", next_word.c_str());
3312         }
3313       }
3314     } else {
3315       if (cmd_obj->IsMultiwordObject()) {
3316         CommandObject *sub_cmd_obj =
3317             cmd_obj->GetSubcommandObject(next_word.c_str());
3318         if (sub_cmd_obj) {
3319           // The subcommand's name includes the parent command's name, so
3320           // restart rather than append to the revised_command_line.
3321           llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3322           revised_command_line.Clear();
3323           revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
3324           cmd_obj = sub_cmd_obj;
3325           wants_raw_input = cmd_obj->WantsRawCommandString();
3326         } else {
3327           if (quote_char)
3328             revised_command_line.Printf(" %c%s%s%c", quote_char,
3329                                         next_word.c_str(), suffix.c_str(),
3330                                         quote_char);
3331           else
3332             revised_command_line.Printf(" %s%s", next_word.c_str(),
3333                                         suffix.c_str());
3334           done = true;
3335         }
3336       } else {
3337         if (quote_char)
3338           revised_command_line.Printf(" %c%s%s%c", quote_char,
3339                                       next_word.c_str(), suffix.c_str(),
3340                                       quote_char);
3341         else
3342           revised_command_line.Printf(" %s%s", next_word.c_str(),
3343                                       suffix.c_str());
3344         done = true;
3345       }
3346     }
3347 
3348     if (cmd_obj == nullptr) {
3349       const size_t num_matches = matches.GetSize();
3350       if (matches.GetSize() > 1) {
3351         StreamString error_msg;
3352         error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3353                          next_word.c_str());
3354 
3355         for (uint32_t i = 0; i < num_matches; ++i) {
3356           error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3357         }
3358         result.AppendRawError(error_msg.GetString());
3359       } else {
3360         // We didn't have only one match, otherwise we wouldn't get here.
3361         lldbassert(num_matches == 0);
3362         result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3363                                      next_word.c_str());
3364       }
3365       return nullptr;
3366     }
3367 
3368     if (cmd_obj->IsMultiwordObject()) {
3369       if (!suffix.empty()) {
3370         result.AppendErrorWithFormat(
3371             "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3372             "might be invalid).\n",
3373             cmd_obj->GetCommandName().str().c_str(),
3374             next_word.empty() ? "" : next_word.c_str(),
3375             next_word.empty() ? " -- " : " ", suffix.c_str());
3376         return nullptr;
3377       }
3378     } else {
3379       // If we found a normal command, we are done
3380       done = true;
3381       if (!suffix.empty()) {
3382         switch (suffix[0]) {
3383         case '/':
3384           // GDB format suffixes
3385           {
3386             Options *command_options = cmd_obj->GetOptions();
3387             if (command_options &&
3388                 command_options->SupportsLongOption("gdb-format")) {
3389               std::string gdb_format_option("--gdb-format=");
3390               gdb_format_option += (suffix.c_str() + 1);
3391 
3392               std::string cmd = std::string(revised_command_line.GetString());
3393               size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3394               if (arg_terminator_idx != std::string::npos) {
3395                 // Insert the gdb format option before the "--" that terminates
3396                 // options
3397                 gdb_format_option.append(1, ' ');
3398                 cmd.insert(arg_terminator_idx, gdb_format_option);
3399                 revised_command_line.Clear();
3400                 revised_command_line.PutCString(cmd);
3401               } else
3402                 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3403 
3404               if (wants_raw_input &&
3405                   FindArgumentTerminator(cmd) == std::string::npos)
3406                 revised_command_line.PutCString(" --");
3407             } else {
3408               result.AppendErrorWithFormat(
3409                   "the '%s' command doesn't support the --gdb-format option\n",
3410                   cmd_obj->GetCommandName().str().c_str());
3411               return nullptr;
3412             }
3413           }
3414           break;
3415 
3416         default:
3417           result.AppendErrorWithFormat(
3418               "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3419           return nullptr;
3420         }
3421       }
3422     }
3423     if (scratch_command.empty())
3424       done = true;
3425   }
3426 
3427   if (!scratch_command.empty())
3428     revised_command_line.Printf(" %s", scratch_command.c_str());
3429 
3430   if (cmd_obj != nullptr)
3431     command_line = std::string(revised_command_line.GetString());
3432 
3433   return cmd_obj;
3434 }
3435