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   StringList tmp_list;
1259   StringList *matches_ptr = matches ? matches : &tmp_list;
1260   AddNamesMatchingPartialString(GetUserCommands(), cmd_str, *matches_ptr);
1261   AddNamesMatchingPartialString(GetUserMultiwordCommands(),
1262                                 cmd_str, *matches_ptr);
1263 
1264   return {};
1265 }
1266 
1267 bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
1268   return m_command_dict.find(std::string(cmd)) != m_command_dict.end();
1269 }
1270 
1271 bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1272                                           std::string &full_name) const {
1273   bool exact_match =
1274       (m_alias_dict.find(std::string(cmd)) != m_alias_dict.end());
1275   if (exact_match) {
1276     full_name.assign(std::string(cmd));
1277     return exact_match;
1278   } else {
1279     StringList matches;
1280     size_t num_alias_matches;
1281     num_alias_matches =
1282         AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1283     if (num_alias_matches == 1) {
1284       // Make sure this isn't shadowing a command in the regular command space:
1285       StringList regular_matches;
1286       const bool include_aliases = false;
1287       const bool exact = false;
1288       CommandObjectSP cmd_obj_sp(
1289           GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1290       if (cmd_obj_sp || regular_matches.GetSize() > 0)
1291         return false;
1292       else {
1293         full_name.assign(matches.GetStringAtIndex(0));
1294         return true;
1295       }
1296     } else
1297       return false;
1298   }
1299 }
1300 
1301 bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
1302   return m_alias_dict.find(std::string(cmd)) != m_alias_dict.end();
1303 }
1304 
1305 bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
1306   return m_user_dict.find(std::string(cmd)) != m_user_dict.end();
1307 }
1308 
1309 bool CommandInterpreter::UserMultiwordCommandExists(llvm::StringRef cmd) const {
1310   return m_user_mw_dict.find(std::string(cmd)) != m_user_mw_dict.end();
1311 }
1312 
1313 CommandAlias *
1314 CommandInterpreter::AddAlias(llvm::StringRef alias_name,
1315                              lldb::CommandObjectSP &command_obj_sp,
1316                              llvm::StringRef args_string) {
1317   if (command_obj_sp.get())
1318     lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1319                "tried to add a CommandObject from a different interpreter");
1320 
1321   std::unique_ptr<CommandAlias> command_alias_up(
1322       new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1323 
1324   if (command_alias_up && command_alias_up->IsValid()) {
1325     m_alias_dict[std::string(alias_name)] =
1326         CommandObjectSP(command_alias_up.get());
1327     return command_alias_up.release();
1328   }
1329 
1330   return nullptr;
1331 }
1332 
1333 bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
1334   auto pos = m_alias_dict.find(std::string(alias_name));
1335   if (pos != m_alias_dict.end()) {
1336     m_alias_dict.erase(pos);
1337     return true;
1338   }
1339   return false;
1340 }
1341 
1342 bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
1343   auto pos = m_command_dict.find(std::string(cmd));
1344   if (pos != m_command_dict.end()) {
1345     if (pos->second->IsRemovable()) {
1346       // Only regular expression objects or python commands are removable
1347       m_command_dict.erase(pos);
1348       return true;
1349     }
1350   }
1351   return false;
1352 }
1353 
1354 bool CommandInterpreter::RemoveUser(llvm::StringRef user_name) {
1355   CommandObject::CommandMap::iterator pos =
1356       m_user_dict.find(std::string(user_name));
1357   if (pos != m_user_dict.end()) {
1358     m_user_dict.erase(pos);
1359     return true;
1360   }
1361   return false;
1362 }
1363 
1364 bool CommandInterpreter::RemoveUserMultiword(llvm::StringRef multi_name) {
1365   CommandObject::CommandMap::iterator pos =
1366       m_user_mw_dict.find(std::string(multi_name));
1367   if (pos != m_user_mw_dict.end()) {
1368     m_user_mw_dict.erase(pos);
1369     return true;
1370   }
1371   return false;
1372 }
1373 
1374 void CommandInterpreter::GetHelp(CommandReturnObject &result,
1375                                  uint32_t cmd_types) {
1376   llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1377   if (!help_prologue.empty()) {
1378     OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1379                             help_prologue);
1380   }
1381 
1382   CommandObject::CommandMap::const_iterator pos;
1383   size_t max_len = FindLongestCommandWord(m_command_dict);
1384 
1385   if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1386     result.AppendMessage("Debugger commands:");
1387     result.AppendMessage("");
1388 
1389     for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1390       if (!(cmd_types & eCommandTypesHidden) &&
1391           (pos->first.compare(0, 1, "_") == 0))
1392         continue;
1393 
1394       OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1395                               pos->second->GetHelp(), max_len);
1396     }
1397     result.AppendMessage("");
1398   }
1399 
1400   if (!m_alias_dict.empty() &&
1401       ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1402     result.AppendMessageWithFormat(
1403         "Current command abbreviations "
1404         "(type '%shelp command alias' for more info):\n",
1405         GetCommandPrefix());
1406     result.AppendMessage("");
1407     max_len = FindLongestCommandWord(m_alias_dict);
1408 
1409     for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1410          ++alias_pos) {
1411       OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
1412                               alias_pos->second->GetHelp(), max_len);
1413     }
1414     result.AppendMessage("");
1415   }
1416 
1417   if (!m_user_dict.empty() &&
1418       ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1419     result.AppendMessage("Current user-defined commands:");
1420     result.AppendMessage("");
1421     max_len = FindLongestCommandWord(m_user_dict);
1422     for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
1423       OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1424                               pos->second->GetHelp(), max_len);
1425     }
1426     result.AppendMessage("");
1427   }
1428 
1429   if (!m_user_mw_dict.empty() &&
1430       ((cmd_types & eCommandTypesUserMW) == eCommandTypesUserMW)) {
1431     result.AppendMessage("Current user-defined container commands:");
1432     result.AppendMessage("");
1433     max_len = FindLongestCommandWord(m_user_mw_dict);
1434     for (pos = m_user_dict.begin(); pos != m_user_mw_dict.end(); ++pos) {
1435       OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1436                               pos->second->GetHelp(), max_len);
1437     }
1438     result.AppendMessage("");
1439   }
1440 
1441   result.AppendMessageWithFormat(
1442       "For more information on any command, type '%shelp <command-name>'.\n",
1443       GetCommandPrefix());
1444 }
1445 
1446 CommandObject *CommandInterpreter::GetCommandObjectForCommand(
1447     llvm::StringRef &command_string) {
1448   // This function finds the final, lowest-level, alias-resolved command object
1449   // whose 'Execute' function will eventually be invoked by the given command
1450   // line.
1451 
1452   CommandObject *cmd_obj = nullptr;
1453   size_t start = command_string.find_first_not_of(k_white_space);
1454   size_t end = 0;
1455   bool done = false;
1456   while (!done) {
1457     if (start != std::string::npos) {
1458       // Get the next word from command_string.
1459       end = command_string.find_first_of(k_white_space, start);
1460       if (end == std::string::npos)
1461         end = command_string.size();
1462       std::string cmd_word =
1463           std::string(command_string.substr(start, end - start));
1464 
1465       if (cmd_obj == nullptr)
1466         // Since cmd_obj is NULL we are on our first time through this loop.
1467         // Check to see if cmd_word is a valid command or alias.
1468         cmd_obj = GetCommandObject(cmd_word);
1469       else if (cmd_obj->IsMultiwordObject()) {
1470         // Our current object is a multi-word object; see if the cmd_word is a
1471         // valid sub-command for our object.
1472         CommandObject *sub_cmd_obj =
1473             cmd_obj->GetSubcommandObject(cmd_word.c_str());
1474         if (sub_cmd_obj)
1475           cmd_obj = sub_cmd_obj;
1476         else // cmd_word was not a valid sub-command word, so we are done
1477           done = true;
1478       } else
1479         // We have a cmd_obj and it is not a multi-word object, so we are done.
1480         done = true;
1481 
1482       // If we didn't find a valid command object, or our command object is not
1483       // a multi-word object, or we are at the end of the command_string, then
1484       // we are done.  Otherwise, find the start of the next word.
1485 
1486       if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1487           end >= command_string.size())
1488         done = true;
1489       else
1490         start = command_string.find_first_not_of(k_white_space, end);
1491     } else
1492       // Unable to find any more words.
1493       done = true;
1494   }
1495 
1496   command_string = command_string.substr(end);
1497   return cmd_obj;
1498 }
1499 
1500 static const char *k_valid_command_chars =
1501     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1502 static void StripLeadingSpaces(std::string &s) {
1503   if (!s.empty()) {
1504     size_t pos = s.find_first_not_of(k_white_space);
1505     if (pos == std::string::npos)
1506       s.clear();
1507     else if (pos == 0)
1508       return;
1509     s.erase(0, pos);
1510   }
1511 }
1512 
1513 static size_t FindArgumentTerminator(const std::string &s) {
1514   const size_t s_len = s.size();
1515   size_t offset = 0;
1516   while (offset < s_len) {
1517     size_t pos = s.find("--", offset);
1518     if (pos == std::string::npos)
1519       break;
1520     if (pos > 0) {
1521       if (llvm::isSpace(s[pos - 1])) {
1522         // Check if the string ends "\s--" (where \s is a space character) or
1523         // if we have "\s--\s".
1524         if ((pos + 2 >= s_len) || llvm::isSpace(s[pos + 2])) {
1525           return pos;
1526         }
1527       }
1528     }
1529     offset = pos + 2;
1530   }
1531   return std::string::npos;
1532 }
1533 
1534 static bool ExtractCommand(std::string &command_string, std::string &command,
1535                            std::string &suffix, char &quote_char) {
1536   command.clear();
1537   suffix.clear();
1538   StripLeadingSpaces(command_string);
1539 
1540   bool result = false;
1541   quote_char = '\0';
1542 
1543   if (!command_string.empty()) {
1544     const char first_char = command_string[0];
1545     if (first_char == '\'' || first_char == '"') {
1546       quote_char = first_char;
1547       const size_t end_quote_pos = command_string.find(quote_char, 1);
1548       if (end_quote_pos == std::string::npos) {
1549         command.swap(command_string);
1550         command_string.erase();
1551       } else {
1552         command.assign(command_string, 1, end_quote_pos - 1);
1553         if (end_quote_pos + 1 < command_string.size())
1554           command_string.erase(0, command_string.find_first_not_of(
1555                                       k_white_space, end_quote_pos + 1));
1556         else
1557           command_string.erase();
1558       }
1559     } else {
1560       const size_t first_space_pos =
1561           command_string.find_first_of(k_white_space);
1562       if (first_space_pos == std::string::npos) {
1563         command.swap(command_string);
1564         command_string.erase();
1565       } else {
1566         command.assign(command_string, 0, first_space_pos);
1567         command_string.erase(0, command_string.find_first_not_of(
1568                                     k_white_space, first_space_pos));
1569       }
1570     }
1571     result = true;
1572   }
1573 
1574   if (!command.empty()) {
1575     // actual commands can't start with '-' or '_'
1576     if (command[0] != '-' && command[0] != '_') {
1577       size_t pos = command.find_first_not_of(k_valid_command_chars);
1578       if (pos > 0 && pos != std::string::npos) {
1579         suffix.assign(command.begin() + pos, command.end());
1580         command.erase(pos);
1581       }
1582     }
1583   }
1584 
1585   return result;
1586 }
1587 
1588 CommandObject *CommandInterpreter::BuildAliasResult(
1589     llvm::StringRef alias_name, std::string &raw_input_string,
1590     std::string &alias_result, CommandReturnObject &result) {
1591   CommandObject *alias_cmd_obj = nullptr;
1592   Args cmd_args(raw_input_string);
1593   alias_cmd_obj = GetCommandObject(alias_name);
1594   StreamString result_str;
1595 
1596   if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1597     alias_result.clear();
1598     return alias_cmd_obj;
1599   }
1600   std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1601       ((CommandAlias *)alias_cmd_obj)->Desugar();
1602   OptionArgVectorSP option_arg_vector_sp = desugared.second;
1603   alias_cmd_obj = desugared.first.get();
1604   std::string alias_name_str = std::string(alias_name);
1605   if ((cmd_args.GetArgumentCount() == 0) ||
1606       (alias_name_str != cmd_args.GetArgumentAtIndex(0)))
1607     cmd_args.Unshift(alias_name_str);
1608 
1609   result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
1610 
1611   if (!option_arg_vector_sp.get()) {
1612     alias_result = std::string(result_str.GetString());
1613     return alias_cmd_obj;
1614   }
1615   OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1616 
1617   int value_type;
1618   std::string option;
1619   std::string value;
1620   for (const auto &entry : *option_arg_vector) {
1621     std::tie(option, value_type, value) = entry;
1622     if (option == "<argument>") {
1623       result_str.Printf(" %s", value.c_str());
1624       continue;
1625     }
1626 
1627     result_str.Printf(" %s", option.c_str());
1628     if (value_type == OptionParser::eNoArgument)
1629       continue;
1630 
1631     if (value_type != OptionParser::eOptionalArgument)
1632       result_str.Printf(" ");
1633     int index = GetOptionArgumentPosition(value.c_str());
1634     if (index == 0)
1635       result_str.Printf("%s", value.c_str());
1636     else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1637 
1638       result.AppendErrorWithFormat("Not enough arguments provided; you "
1639                                    "need at least %d arguments to use "
1640                                    "this alias.\n",
1641                                    index);
1642       return nullptr;
1643     } else {
1644       size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1645       if (strpos != std::string::npos)
1646         raw_input_string = raw_input_string.erase(
1647             strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1648       result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
1649     }
1650   }
1651 
1652   alias_result = std::string(result_str.GetString());
1653   return alias_cmd_obj;
1654 }
1655 
1656 Status CommandInterpreter::PreprocessCommand(std::string &command) {
1657   // The command preprocessor needs to do things to the command line before any
1658   // parsing of arguments or anything else is done. The only current stuff that
1659   // gets preprocessed is anything enclosed in backtick ('`') characters is
1660   // evaluated as an expression and the result of the expression must be a
1661   // scalar that can be substituted into the command. An example would be:
1662   // (lldb) memory read `$rsp + 20`
1663   Status error; // Status for any expressions that might not evaluate
1664   size_t start_backtick;
1665   size_t pos = 0;
1666   while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1667     // Stop if an error was encountered during the previous iteration.
1668     if (error.Fail())
1669       break;
1670 
1671     if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
1672       // The backtick was preceded by a '\' character, remove the slash and
1673       // don't treat the backtick as the start of an expression.
1674       command.erase(start_backtick - 1, 1);
1675       // No need to add one to start_backtick since we just deleted a char.
1676       pos = start_backtick;
1677       continue;
1678     }
1679 
1680     const size_t expr_content_start = start_backtick + 1;
1681     const size_t end_backtick = command.find('`', expr_content_start);
1682 
1683     if (end_backtick == std::string::npos) {
1684       // Stop if there's no end backtick.
1685       break;
1686     }
1687 
1688     if (end_backtick == expr_content_start) {
1689       // Skip over empty expression. (two backticks in a row)
1690       command.erase(start_backtick, 2);
1691       continue;
1692     }
1693 
1694     std::string expr_str(command, expr_content_start,
1695                          end_backtick - expr_content_start);
1696 
1697     ExecutionContext exe_ctx(GetExecutionContext());
1698 
1699     // Get a dummy target to allow for calculator mode while processing
1700     // backticks. This also helps break the infinite loop caused when target is
1701     // null.
1702     Target *exe_target = exe_ctx.GetTargetPtr();
1703     Target &target = exe_target ? *exe_target : m_debugger.GetDummyTarget();
1704 
1705     ValueObjectSP expr_result_valobj_sp;
1706 
1707     EvaluateExpressionOptions options;
1708     options.SetCoerceToId(false);
1709     options.SetUnwindOnError(true);
1710     options.SetIgnoreBreakpoints(true);
1711     options.SetKeepInMemory(false);
1712     options.SetTryAllThreads(true);
1713     options.SetTimeout(llvm::None);
1714 
1715     ExpressionResults expr_result =
1716         target.EvaluateExpression(expr_str.c_str(), exe_ctx.GetFramePtr(),
1717                                   expr_result_valobj_sp, options);
1718 
1719     if (expr_result == eExpressionCompleted) {
1720       Scalar scalar;
1721       if (expr_result_valobj_sp)
1722         expr_result_valobj_sp =
1723             expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1724                 expr_result_valobj_sp->GetDynamicValueType(), true);
1725       if (expr_result_valobj_sp->ResolveValue(scalar)) {
1726         command.erase(start_backtick, end_backtick - start_backtick + 1);
1727         StreamString value_strm;
1728         const bool show_type = false;
1729         scalar.GetValue(&value_strm, show_type);
1730         size_t value_string_size = value_strm.GetSize();
1731         if (value_string_size) {
1732           command.insert(start_backtick, std::string(value_strm.GetString()));
1733           pos = start_backtick + value_string_size;
1734           continue;
1735         } else {
1736           error.SetErrorStringWithFormat("expression value didn't result "
1737                                          "in a scalar value for the "
1738                                          "expression '%s'",
1739                                          expr_str.c_str());
1740           break;
1741         }
1742       } else {
1743         error.SetErrorStringWithFormat("expression value didn't result "
1744                                        "in a scalar value for the "
1745                                        "expression '%s'",
1746                                        expr_str.c_str());
1747         break;
1748       }
1749 
1750       continue;
1751     }
1752 
1753     if (expr_result_valobj_sp)
1754       error = expr_result_valobj_sp->GetError();
1755 
1756     if (error.Success()) {
1757       switch (expr_result) {
1758       case eExpressionSetupError:
1759         error.SetErrorStringWithFormat(
1760             "expression setup error for the expression '%s'", expr_str.c_str());
1761         break;
1762       case eExpressionParseError:
1763         error.SetErrorStringWithFormat(
1764             "expression parse error for the expression '%s'", expr_str.c_str());
1765         break;
1766       case eExpressionResultUnavailable:
1767         error.SetErrorStringWithFormat(
1768             "expression error fetching result for the expression '%s'",
1769             expr_str.c_str());
1770         break;
1771       case eExpressionCompleted:
1772         break;
1773       case eExpressionDiscarded:
1774         error.SetErrorStringWithFormat(
1775             "expression discarded for the expression '%s'", expr_str.c_str());
1776         break;
1777       case eExpressionInterrupted:
1778         error.SetErrorStringWithFormat(
1779             "expression interrupted for the expression '%s'", expr_str.c_str());
1780         break;
1781       case eExpressionHitBreakpoint:
1782         error.SetErrorStringWithFormat(
1783             "expression hit breakpoint for the expression '%s'",
1784             expr_str.c_str());
1785         break;
1786       case eExpressionTimedOut:
1787         error.SetErrorStringWithFormat(
1788             "expression timed out for the expression '%s'", expr_str.c_str());
1789         break;
1790       case eExpressionStoppedForDebug:
1791         error.SetErrorStringWithFormat("expression stop at entry point "
1792                                        "for debugging for the "
1793                                        "expression '%s'",
1794                                        expr_str.c_str());
1795         break;
1796       case eExpressionThreadVanished:
1797         error.SetErrorStringWithFormat(
1798             "expression thread vanished for the expression '%s'",
1799             expr_str.c_str());
1800         break;
1801       }
1802     }
1803   }
1804   return error;
1805 }
1806 
1807 bool CommandInterpreter::HandleCommand(const char *command_line,
1808                                        LazyBool lazy_add_to_history,
1809                                        const ExecutionContext &override_context,
1810                                        CommandReturnObject &result) {
1811 
1812   OverrideExecutionContext(override_context);
1813   bool status = HandleCommand(command_line, lazy_add_to_history, result);
1814   RestoreExecutionContext();
1815   return status;
1816 }
1817 
1818 bool CommandInterpreter::HandleCommand(const char *command_line,
1819                                        LazyBool lazy_add_to_history,
1820                                        CommandReturnObject &result) {
1821 
1822   std::string command_string(command_line);
1823   std::string original_command_string(command_line);
1824 
1825   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS));
1826   llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
1827                                    command_line);
1828 
1829   LLDB_LOGF(log, "Processing command: %s", command_line);
1830   LLDB_SCOPED_TIMERF("Processing command: %s.", command_line);
1831 
1832   if (WasInterrupted()) {
1833     result.AppendError("interrupted");
1834     return false;
1835   }
1836 
1837   bool add_to_history;
1838   if (lazy_add_to_history == eLazyBoolCalculate)
1839     add_to_history = (m_command_source_depth == 0);
1840   else
1841     add_to_history = (lazy_add_to_history == eLazyBoolYes);
1842 
1843   m_transcript_stream << "(lldb) " << command_line << '\n';
1844 
1845   bool empty_command = false;
1846   bool comment_command = false;
1847   if (command_string.empty())
1848     empty_command = true;
1849   else {
1850     const char *k_space_characters = "\t\n\v\f\r ";
1851 
1852     size_t non_space = command_string.find_first_not_of(k_space_characters);
1853     // Check for empty line or comment line (lines whose first non-space
1854     // character is the comment character for this interpreter)
1855     if (non_space == std::string::npos)
1856       empty_command = true;
1857     else if (command_string[non_space] == m_comment_char)
1858       comment_command = true;
1859     else if (command_string[non_space] == CommandHistory::g_repeat_char) {
1860       llvm::StringRef search_str(command_string);
1861       search_str = search_str.drop_front(non_space);
1862       if (auto hist_str = m_command_history.FindString(search_str)) {
1863         add_to_history = false;
1864         command_string = std::string(*hist_str);
1865         original_command_string = std::string(*hist_str);
1866       } else {
1867         result.AppendErrorWithFormat("Could not find entry: %s in history",
1868                                      command_string.c_str());
1869         return false;
1870       }
1871     }
1872   }
1873 
1874   if (empty_command) {
1875     if (!GetRepeatPreviousCommand()) {
1876       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1877       return true;
1878     }
1879 
1880     if (m_command_history.IsEmpty()) {
1881       result.AppendError("empty command");
1882       return false;
1883     }
1884 
1885     command_line = m_repeat_command.c_str();
1886     command_string = command_line;
1887     original_command_string = command_line;
1888     if (m_repeat_command.empty()) {
1889       result.AppendError("No auto repeat.");
1890       return false;
1891     }
1892 
1893     add_to_history = false;
1894   } else if (comment_command) {
1895     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1896     return true;
1897   }
1898 
1899   Status error(PreprocessCommand(command_string));
1900 
1901   if (error.Fail()) {
1902     result.AppendError(error.AsCString());
1903     return false;
1904   }
1905 
1906   // Phase 1.
1907 
1908   // Before we do ANY kind of argument processing, we need to figure out what
1909   // the real/final command object is for the specified command.  This gets
1910   // complicated by the fact that the user could have specified an alias, and,
1911   // in translating the alias, there may also be command options and/or even
1912   // data (including raw text strings) that need to be found and inserted into
1913   // the command line as part of the translation.  So this first step is plain
1914   // look-up and replacement, resulting in:
1915   //    1. the command object whose Execute method will actually be called
1916   //    2. a revised command string, with all substitutions and replacements
1917   //       taken care of
1918   // From 1 above, we can determine whether the Execute function wants raw
1919   // input or not.
1920 
1921   CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1922 
1923   // Although the user may have abbreviated the command, the command_string now
1924   // has the command expanded to the full name.  For example, if the input was
1925   // "br s -n main", command_string is now "breakpoint set -n main".
1926   if (log) {
1927     llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1928     LLDB_LOGF(log, "HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
1929     LLDB_LOGF(log, "HandleCommand, (revised) command_string: '%s'",
1930               command_string.c_str());
1931     const bool wants_raw_input =
1932         (cmd_obj != nullptr) ? cmd_obj->WantsRawCommandString() : false;
1933     LLDB_LOGF(log, "HandleCommand, wants_raw_input:'%s'",
1934               wants_raw_input ? "True" : "False");
1935   }
1936 
1937   // Phase 2.
1938   // Take care of things like setting up the history command & calling the
1939   // appropriate Execute method on the CommandObject, with the appropriate
1940   // arguments.
1941 
1942   if (cmd_obj != nullptr) {
1943     if (add_to_history) {
1944       Args command_args(command_string);
1945       const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1946       if (repeat_command != nullptr)
1947         m_repeat_command.assign(repeat_command);
1948       else
1949         m_repeat_command.assign(original_command_string);
1950 
1951       m_command_history.AppendString(original_command_string);
1952     }
1953 
1954     std::string remainder;
1955     const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
1956     if (actual_cmd_name_len < command_string.length())
1957       remainder = command_string.substr(actual_cmd_name_len);
1958 
1959     // Remove any initial spaces
1960     size_t pos = remainder.find_first_not_of(k_white_space);
1961     if (pos != 0 && pos != std::string::npos)
1962       remainder.erase(0, pos);
1963 
1964     LLDB_LOGF(
1965         log, "HandleCommand, command line after removing command name(s): '%s'",
1966         remainder.c_str());
1967 
1968     cmd_obj->Execute(remainder.c_str(), result);
1969   }
1970 
1971   LLDB_LOGF(log, "HandleCommand, command %s",
1972             (result.Succeeded() ? "succeeded" : "did not succeed"));
1973 
1974   m_transcript_stream << result.GetOutputData();
1975   m_transcript_stream << result.GetErrorData();
1976 
1977   return result.Succeeded();
1978 }
1979 
1980 void CommandInterpreter::HandleCompletionMatches(CompletionRequest &request) {
1981   bool look_for_subcommand = false;
1982 
1983   // For any of the command completions a unique match will be a complete word.
1984 
1985   if (request.GetParsedLine().GetArgumentCount() == 0) {
1986     // We got nothing on the command line, so return the list of commands
1987     bool include_aliases = true;
1988     StringList new_matches, descriptions;
1989     GetCommandNamesMatchingPartialString("", include_aliases, new_matches,
1990                                          descriptions);
1991     request.AddCompletions(new_matches, descriptions);
1992   } else if (request.GetCursorIndex() == 0) {
1993     // The cursor is in the first argument, so just do a lookup in the
1994     // dictionary.
1995     StringList new_matches, new_descriptions;
1996     CommandObject *cmd_obj =
1997         GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0),
1998                          &new_matches, &new_descriptions);
1999 
2000     if (new_matches.GetSize() && cmd_obj && cmd_obj->IsMultiwordObject() &&
2001         new_matches.GetStringAtIndex(0) != nullptr &&
2002         strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
2003                new_matches.GetStringAtIndex(0)) == 0) {
2004       if (request.GetParsedLine().GetArgumentCount() != 1) {
2005         look_for_subcommand = true;
2006         new_matches.DeleteStringAtIndex(0);
2007         new_descriptions.DeleteStringAtIndex(0);
2008         request.AppendEmptyArgument();
2009       }
2010     }
2011     request.AddCompletions(new_matches, new_descriptions);
2012   }
2013 
2014   if (request.GetCursorIndex() > 0 || look_for_subcommand) {
2015     // We are completing further on into a commands arguments, so find the
2016     // command and tell it to complete the command. First see if there is a
2017     // matching initial command:
2018     CommandObject *command_object =
2019         GetCommandObject(request.GetParsedLine().GetArgumentAtIndex(0));
2020     if (command_object) {
2021       request.ShiftArguments();
2022       command_object->HandleCompletion(request);
2023     }
2024   }
2025 }
2026 
2027 void CommandInterpreter::HandleCompletion(CompletionRequest &request) {
2028 
2029   // Don't complete comments, and if the line we are completing is just the
2030   // history repeat character, substitute the appropriate history line.
2031   llvm::StringRef first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
2032 
2033   if (!first_arg.empty()) {
2034     if (first_arg.front() == m_comment_char)
2035       return;
2036     if (first_arg.front() == CommandHistory::g_repeat_char) {
2037       if (auto hist_str = m_command_history.FindString(first_arg))
2038         request.AddCompletion(*hist_str, "Previous command history event",
2039                               CompletionMode::RewriteLine);
2040       return;
2041     }
2042   }
2043 
2044   HandleCompletionMatches(request);
2045 }
2046 
2047 llvm::Optional<std::string>
2048 CommandInterpreter::GetAutoSuggestionForCommand(llvm::StringRef line) {
2049   if (line.empty())
2050     return llvm::None;
2051   const size_t s = m_command_history.GetSize();
2052   for (int i = s - 1; i >= 0; --i) {
2053     llvm::StringRef entry = m_command_history.GetStringAtIndex(i);
2054     if (entry.consume_front(line))
2055       return entry.str();
2056   }
2057   return llvm::None;
2058 }
2059 
2060 void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
2061   EventSP prompt_change_event_sp(
2062       new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
2063   ;
2064   BroadcastEvent(prompt_change_event_sp);
2065   if (m_command_io_handler_sp)
2066     m_command_io_handler_sp->SetPrompt(new_prompt);
2067 }
2068 
2069 bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
2070   // Check AutoConfirm first:
2071   if (m_debugger.GetAutoConfirm())
2072     return default_answer;
2073 
2074   IOHandlerConfirm *confirm =
2075       new IOHandlerConfirm(m_debugger, message, default_answer);
2076   IOHandlerSP io_handler_sp(confirm);
2077   m_debugger.RunIOHandlerSync(io_handler_sp);
2078   return confirm->GetResponse();
2079 }
2080 
2081 const CommandAlias *
2082 CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
2083   OptionArgVectorSP ret_val;
2084 
2085   auto pos = m_alias_dict.find(std::string(alias_name));
2086   if (pos != m_alias_dict.end())
2087     return (CommandAlias *)pos->second.get();
2088 
2089   return nullptr;
2090 }
2091 
2092 bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
2093 
2094 bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
2095 
2096 bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
2097 
2098 bool CommandInterpreter::HasUserMultiwordCommands() const {
2099   return (!m_user_mw_dict.empty());
2100 }
2101 
2102 bool CommandInterpreter::HasAliasOptions() const { return HasAliases(); }
2103 
2104 void CommandInterpreter::BuildAliasCommandArgs(CommandObject *alias_cmd_obj,
2105                                                const char *alias_name,
2106                                                Args &cmd_args,
2107                                                std::string &raw_input_string,
2108                                                CommandReturnObject &result) {
2109   OptionArgVectorSP option_arg_vector_sp =
2110       GetAlias(alias_name)->GetOptionArguments();
2111 
2112   bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
2113 
2114   // Make sure that the alias name is the 0th element in cmd_args
2115   std::string alias_name_str = alias_name;
2116   if (alias_name_str != cmd_args.GetArgumentAtIndex(0))
2117     cmd_args.Unshift(alias_name_str);
2118 
2119   Args new_args(alias_cmd_obj->GetCommandName());
2120   if (new_args.GetArgumentCount() == 2)
2121     new_args.Shift();
2122 
2123   if (option_arg_vector_sp.get()) {
2124     if (wants_raw_input) {
2125       // We have a command that both has command options and takes raw input.
2126       // Make *sure* it has a " -- " in the right place in the
2127       // raw_input_string.
2128       size_t pos = raw_input_string.find(" -- ");
2129       if (pos == std::string::npos) {
2130         // None found; assume it goes at the beginning of the raw input string
2131         raw_input_string.insert(0, " -- ");
2132       }
2133     }
2134 
2135     OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2136     const size_t old_size = cmd_args.GetArgumentCount();
2137     std::vector<bool> used(old_size + 1, false);
2138 
2139     used[0] = true;
2140 
2141     int value_type;
2142     std::string option;
2143     std::string value;
2144     for (const auto &option_entry : *option_arg_vector) {
2145       std::tie(option, value_type, value) = option_entry;
2146       if (option == "<argument>") {
2147         if (!wants_raw_input || (value != "--")) {
2148           // Since we inserted this above, make sure we don't insert it twice
2149           new_args.AppendArgument(value);
2150         }
2151         continue;
2152       }
2153 
2154       if (value_type != OptionParser::eOptionalArgument)
2155         new_args.AppendArgument(option);
2156 
2157       if (value == "<no-argument>")
2158         continue;
2159 
2160       int index = GetOptionArgumentPosition(value.c_str());
2161       if (index == 0) {
2162         // value was NOT a positional argument; must be a real value
2163         if (value_type != OptionParser::eOptionalArgument)
2164           new_args.AppendArgument(value);
2165         else {
2166           new_args.AppendArgument(option + value);
2167         }
2168 
2169       } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
2170         result.AppendErrorWithFormat("Not enough arguments provided; you "
2171                                      "need at least %d arguments to use "
2172                                      "this alias.\n",
2173                                      index);
2174         return;
2175       } else {
2176         // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2177         size_t strpos =
2178             raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2179         if (strpos != std::string::npos) {
2180           raw_input_string = raw_input_string.erase(
2181               strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2182         }
2183 
2184         if (value_type != OptionParser::eOptionalArgument)
2185           new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2186         else {
2187           new_args.AppendArgument(option + cmd_args.GetArgumentAtIndex(index));
2188         }
2189         used[index] = true;
2190       }
2191     }
2192 
2193     for (auto entry : llvm::enumerate(cmd_args.entries())) {
2194       if (!used[entry.index()] && !wants_raw_input)
2195         new_args.AppendArgument(entry.value().ref());
2196     }
2197 
2198     cmd_args.Clear();
2199     cmd_args.SetArguments(new_args.GetArgumentCount(),
2200                           new_args.GetConstArgumentVector());
2201   } else {
2202     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2203     // This alias was not created with any options; nothing further needs to be
2204     // done, unless it is a command that wants raw input, in which case we need
2205     // to clear the rest of the data from cmd_args, since its in the raw input
2206     // string.
2207     if (wants_raw_input) {
2208       cmd_args.Clear();
2209       cmd_args.SetArguments(new_args.GetArgumentCount(),
2210                             new_args.GetConstArgumentVector());
2211     }
2212     return;
2213   }
2214 
2215   result.SetStatus(eReturnStatusSuccessFinishNoResult);
2216   return;
2217 }
2218 
2219 int CommandInterpreter::GetOptionArgumentPosition(const char *in_string) {
2220   int position = 0; // Any string that isn't an argument position, i.e. '%'
2221                     // followed by an integer, gets a position
2222                     // of zero.
2223 
2224   const char *cptr = in_string;
2225 
2226   // Does it start with '%'
2227   if (cptr[0] == '%') {
2228     ++cptr;
2229 
2230     // Is the rest of it entirely digits?
2231     if (isdigit(cptr[0])) {
2232       const char *start = cptr;
2233       while (isdigit(cptr[0]))
2234         ++cptr;
2235 
2236       // We've gotten to the end of the digits; are we at the end of the
2237       // string?
2238       if (cptr[0] == '\0')
2239         position = atoi(start);
2240     }
2241   }
2242 
2243   return position;
2244 }
2245 
2246 static void GetHomeInitFile(llvm::SmallVectorImpl<char> &init_file,
2247                             llvm::StringRef suffix = {}) {
2248   std::string init_file_name = ".lldbinit";
2249   if (!suffix.empty()) {
2250     init_file_name.append("-");
2251     init_file_name.append(suffix.str());
2252   }
2253 
2254   FileSystem::Instance().GetHomeDirectory(init_file);
2255   llvm::sys::path::append(init_file, init_file_name);
2256 
2257   FileSystem::Instance().Resolve(init_file);
2258 }
2259 
2260 static void GetHomeREPLInitFile(llvm::SmallVectorImpl<char> &init_file) {
2261   LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs();
2262   LanguageType language = eLanguageTypeUnknown;
2263   if (auto main_repl_language = repl_languages.GetSingularLanguage())
2264     language = *main_repl_language;
2265   else
2266     return;
2267 
2268   std::string init_file_name =
2269       (llvm::Twine(".lldbinit-") +
2270        llvm::Twine(Language::GetNameForLanguageType(language)) +
2271        llvm::Twine("-repl"))
2272           .str();
2273   FileSystem::Instance().GetHomeDirectory(init_file);
2274   llvm::sys::path::append(init_file, init_file_name);
2275   FileSystem::Instance().Resolve(init_file);
2276 }
2277 
2278 static void GetCwdInitFile(llvm::SmallVectorImpl<char> &init_file) {
2279   llvm::StringRef s = ".lldbinit";
2280   init_file.assign(s.begin(), s.end());
2281   FileSystem::Instance().Resolve(init_file);
2282 }
2283 
2284 void CommandInterpreter::SourceInitFile(FileSpec file,
2285                                         CommandReturnObject &result) {
2286   assert(!m_skip_lldbinit_files);
2287 
2288   if (!FileSystem::Instance().Exists(file)) {
2289     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2290     return;
2291   }
2292 
2293   // Use HandleCommand to 'source' the given file; this will do the actual
2294   // broadcasting of the commands back to any appropriate listener (see
2295   // CommandObjectSource::Execute for more details).
2296   const bool saved_batch = SetBatchCommandMode(true);
2297   CommandInterpreterRunOptions options;
2298   options.SetSilent(true);
2299   options.SetPrintErrors(true);
2300   options.SetStopOnError(false);
2301   options.SetStopOnContinue(true);
2302   HandleCommandsFromFile(file, options, result);
2303   SetBatchCommandMode(saved_batch);
2304 }
2305 
2306 void CommandInterpreter::SourceInitFileCwd(CommandReturnObject &result) {
2307   if (m_skip_lldbinit_files) {
2308     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2309     return;
2310   }
2311 
2312   llvm::SmallString<128> init_file;
2313   GetCwdInitFile(init_file);
2314   if (!FileSystem::Instance().Exists(init_file)) {
2315     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2316     return;
2317   }
2318 
2319   LoadCWDlldbinitFile should_load =
2320       Target::GetGlobalProperties().GetLoadCWDlldbinitFile();
2321 
2322   switch (should_load) {
2323   case eLoadCWDlldbinitFalse:
2324     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2325     break;
2326   case eLoadCWDlldbinitTrue:
2327     SourceInitFile(FileSpec(init_file.str()), result);
2328     break;
2329   case eLoadCWDlldbinitWarn: {
2330     llvm::SmallString<128> home_init_file;
2331     GetHomeInitFile(home_init_file);
2332     if (llvm::sys::path::parent_path(init_file) ==
2333         llvm::sys::path::parent_path(home_init_file)) {
2334       result.SetStatus(eReturnStatusSuccessFinishNoResult);
2335     } else {
2336       result.AppendError(InitFileWarning);
2337     }
2338   }
2339   }
2340 }
2341 
2342 /// We will first see if there is an application specific ".lldbinit" file
2343 /// whose name is "~/.lldbinit" followed by a "-" and the name of the program.
2344 /// If this file doesn't exist, we fall back to the REPL init file or the
2345 /// default home init file in "~/.lldbinit".
2346 void CommandInterpreter::SourceInitFileHome(CommandReturnObject &result,
2347                                             bool is_repl) {
2348   if (m_skip_lldbinit_files) {
2349     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2350     return;
2351   }
2352 
2353   llvm::SmallString<128> init_file;
2354 
2355   if (is_repl)
2356     GetHomeREPLInitFile(init_file);
2357 
2358   if (init_file.empty())
2359     GetHomeInitFile(init_file);
2360 
2361   if (!m_skip_app_init_files) {
2362     llvm::StringRef program_name =
2363         HostInfo::GetProgramFileSpec().GetFilename().GetStringRef();
2364     llvm::SmallString<128> program_init_file;
2365     GetHomeInitFile(program_init_file, program_name);
2366     if (FileSystem::Instance().Exists(program_init_file))
2367       init_file = program_init_file;
2368   }
2369 
2370   SourceInitFile(FileSpec(init_file.str()), result);
2371 }
2372 
2373 const char *CommandInterpreter::GetCommandPrefix() {
2374   const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2375   return prefix == nullptr ? "" : prefix;
2376 }
2377 
2378 PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2379   PlatformSP platform_sp;
2380   if (prefer_target_platform) {
2381     ExecutionContext exe_ctx(GetExecutionContext());
2382     Target *target = exe_ctx.GetTargetPtr();
2383     if (target)
2384       platform_sp = target->GetPlatform();
2385   }
2386 
2387   if (!platform_sp)
2388     platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2389   return platform_sp;
2390 }
2391 
2392 bool CommandInterpreter::DidProcessStopAbnormally() const {
2393   auto exe_ctx = GetExecutionContext();
2394   TargetSP target_sp = exe_ctx.GetTargetSP();
2395   if (!target_sp)
2396     return false;
2397 
2398   ProcessSP process_sp(target_sp->GetProcessSP());
2399   if (!process_sp)
2400     return false;
2401 
2402   if (eStateStopped != process_sp->GetState())
2403     return false;
2404 
2405   for (const auto &thread_sp : process_sp->GetThreadList().Threads()) {
2406     StopInfoSP stop_info = thread_sp->GetStopInfo();
2407     if (!stop_info)
2408       return false;
2409 
2410     const StopReason reason = stop_info->GetStopReason();
2411     if (reason == eStopReasonException ||
2412         reason == eStopReasonInstrumentation ||
2413         reason == eStopReasonProcessorTrace)
2414       return true;
2415 
2416     if (reason == eStopReasonSignal) {
2417       const auto stop_signal = static_cast<int32_t>(stop_info->GetValue());
2418       UnixSignalsSP signals_sp = process_sp->GetUnixSignals();
2419       if (!signals_sp || !signals_sp->SignalIsValid(stop_signal))
2420         // The signal is unknown, treat it as abnormal.
2421         return true;
2422 
2423       const auto sigint_num = signals_sp->GetSignalNumberFromName("SIGINT");
2424       const auto sigstop_num = signals_sp->GetSignalNumberFromName("SIGSTOP");
2425       if ((stop_signal != sigint_num) && (stop_signal != sigstop_num))
2426         // The signal very likely implies a crash.
2427         return true;
2428     }
2429   }
2430 
2431   return false;
2432 }
2433 
2434 void
2435 CommandInterpreter::HandleCommands(const StringList &commands,
2436                                    const ExecutionContext &override_context,
2437                                    const CommandInterpreterRunOptions &options,
2438                                    CommandReturnObject &result) {
2439 
2440   OverrideExecutionContext(override_context);
2441   HandleCommands(commands, options, result);
2442   RestoreExecutionContext();
2443 }
2444 
2445 void CommandInterpreter::HandleCommands(const StringList &commands,
2446                                         const CommandInterpreterRunOptions &options,
2447                                         CommandReturnObject &result) {
2448   size_t num_lines = commands.GetSize();
2449 
2450   // If we are going to continue past a "continue" then we need to run the
2451   // commands synchronously. Make sure you reset this value anywhere you return
2452   // from the function.
2453 
2454   bool old_async_execution = m_debugger.GetAsyncExecution();
2455 
2456   if (!options.GetStopOnContinue()) {
2457     m_debugger.SetAsyncExecution(false);
2458   }
2459 
2460   for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
2461     const char *cmd = commands.GetStringAtIndex(idx);
2462     if (cmd[0] == '\0')
2463       continue;
2464 
2465     if (options.GetEchoCommands()) {
2466       // TODO: Add Stream support.
2467       result.AppendMessageWithFormat("%s %s\n",
2468                                      m_debugger.GetPrompt().str().c_str(), cmd);
2469     }
2470 
2471     CommandReturnObject tmp_result(m_debugger.GetUseColor());
2472     tmp_result.SetInteractive(result.GetInteractive());
2473     tmp_result.SetSuppressImmediateOutput(true);
2474 
2475     // We might call into a regex or alias command, in which case the
2476     // add_to_history will get lost.  This m_command_source_depth dingus is the
2477     // way we turn off adding to the history in that case, so set it up here.
2478     if (!options.GetAddToHistory())
2479       m_command_source_depth++;
2480     bool success = HandleCommand(cmd, options.m_add_to_history, tmp_result);
2481     if (!options.GetAddToHistory())
2482       m_command_source_depth--;
2483 
2484     if (options.GetPrintResults()) {
2485       if (tmp_result.Succeeded())
2486         result.AppendMessage(tmp_result.GetOutputData());
2487     }
2488 
2489     if (!success || !tmp_result.Succeeded()) {
2490       llvm::StringRef error_msg = tmp_result.GetErrorData();
2491       if (error_msg.empty())
2492         error_msg = "<unknown error>.\n";
2493       if (options.GetStopOnError()) {
2494         result.AppendErrorWithFormat(
2495             "Aborting reading of commands after command #%" PRIu64
2496             ": '%s' failed with %s",
2497             (uint64_t)idx, cmd, error_msg.str().c_str());
2498         m_debugger.SetAsyncExecution(old_async_execution);
2499         return;
2500       } else if (options.GetPrintResults()) {
2501         result.AppendMessageWithFormat(
2502             "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2503             error_msg.str().c_str());
2504       }
2505     }
2506 
2507     if (result.GetImmediateOutputStream())
2508       result.GetImmediateOutputStream()->Flush();
2509 
2510     if (result.GetImmediateErrorStream())
2511       result.GetImmediateErrorStream()->Flush();
2512 
2513     // N.B. Can't depend on DidChangeProcessState, because the state coming
2514     // into the command execution could be running (for instance in Breakpoint
2515     // Commands. So we check the return value to see if it is has running in
2516     // it.
2517     if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2518         (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2519       if (options.GetStopOnContinue()) {
2520         // If we caused the target to proceed, and we're going to stop in that
2521         // case, set the status in our real result before returning.  This is
2522         // an error if the continue was not the last command in the set of
2523         // commands to be run.
2524         if (idx != num_lines - 1)
2525           result.AppendErrorWithFormat(
2526               "Aborting reading of commands after command #%" PRIu64
2527               ": '%s' continued the target.\n",
2528               (uint64_t)idx + 1, cmd);
2529         else
2530           result.AppendMessageWithFormat("Command #%" PRIu64
2531                                          " '%s' continued the target.\n",
2532                                          (uint64_t)idx + 1, cmd);
2533 
2534         result.SetStatus(tmp_result.GetStatus());
2535         m_debugger.SetAsyncExecution(old_async_execution);
2536 
2537         return;
2538       }
2539     }
2540 
2541     // Also check for "stop on crash here:
2542     if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash() &&
2543         DidProcessStopAbnormally()) {
2544       if (idx != num_lines - 1)
2545         result.AppendErrorWithFormat(
2546             "Aborting reading of commands after command #%" PRIu64
2547             ": '%s' stopped with a signal or exception.\n",
2548             (uint64_t)idx + 1, cmd);
2549       else
2550         result.AppendMessageWithFormat(
2551             "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2552             (uint64_t)idx + 1, cmd);
2553 
2554       result.SetStatus(tmp_result.GetStatus());
2555       m_debugger.SetAsyncExecution(old_async_execution);
2556 
2557       return;
2558     }
2559   }
2560 
2561   result.SetStatus(eReturnStatusSuccessFinishResult);
2562   m_debugger.SetAsyncExecution(old_async_execution);
2563 
2564   return;
2565 }
2566 
2567 // Make flags that we can pass into the IOHandler so our delegates can do the
2568 // right thing
2569 enum {
2570   eHandleCommandFlagStopOnContinue = (1u << 0),
2571   eHandleCommandFlagStopOnError = (1u << 1),
2572   eHandleCommandFlagEchoCommand = (1u << 2),
2573   eHandleCommandFlagEchoCommentCommand = (1u << 3),
2574   eHandleCommandFlagPrintResult = (1u << 4),
2575   eHandleCommandFlagPrintErrors = (1u << 5),
2576   eHandleCommandFlagStopOnCrash = (1u << 6)
2577 };
2578 
2579 void CommandInterpreter::HandleCommandsFromFile(
2580     FileSpec &cmd_file, const ExecutionContext &context,
2581     const CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2582   OverrideExecutionContext(context);
2583   HandleCommandsFromFile(cmd_file, options, result);
2584   RestoreExecutionContext();
2585 }
2586 
2587 void CommandInterpreter::HandleCommandsFromFile(FileSpec &cmd_file,
2588     const CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2589   if (!FileSystem::Instance().Exists(cmd_file)) {
2590     result.AppendErrorWithFormat(
2591         "Error reading commands from file %s - file not found.\n",
2592         cmd_file.GetFilename().AsCString("<Unknown>"));
2593     return;
2594   }
2595 
2596   std::string cmd_file_path = cmd_file.GetPath();
2597   auto input_file_up =
2598       FileSystem::Instance().Open(cmd_file, File::eOpenOptionReadOnly);
2599   if (!input_file_up) {
2600     std::string error = llvm::toString(input_file_up.takeError());
2601     result.AppendErrorWithFormatv(
2602         "error: an error occurred read file '{0}': {1}\n", cmd_file_path,
2603         llvm::fmt_consume(input_file_up.takeError()));
2604     return;
2605   }
2606   FileSP input_file_sp = FileSP(std::move(input_file_up.get()));
2607 
2608   Debugger &debugger = GetDebugger();
2609 
2610   uint32_t flags = 0;
2611 
2612   if (options.m_stop_on_continue == eLazyBoolCalculate) {
2613     if (m_command_source_flags.empty()) {
2614       // Stop on continue by default
2615       flags |= eHandleCommandFlagStopOnContinue;
2616     } else if (m_command_source_flags.back() &
2617                eHandleCommandFlagStopOnContinue) {
2618       flags |= eHandleCommandFlagStopOnContinue;
2619     }
2620   } else if (options.m_stop_on_continue == eLazyBoolYes) {
2621     flags |= eHandleCommandFlagStopOnContinue;
2622   }
2623 
2624   if (options.m_stop_on_error == eLazyBoolCalculate) {
2625     if (m_command_source_flags.empty()) {
2626       if (GetStopCmdSourceOnError())
2627         flags |= eHandleCommandFlagStopOnError;
2628     } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2629       flags |= eHandleCommandFlagStopOnError;
2630     }
2631   } else if (options.m_stop_on_error == eLazyBoolYes) {
2632     flags |= eHandleCommandFlagStopOnError;
2633   }
2634 
2635   // stop-on-crash can only be set, if it is present in all levels of
2636   // pushed flag sets.
2637   if (options.GetStopOnCrash()) {
2638     if (m_command_source_flags.empty()) {
2639       flags |= eHandleCommandFlagStopOnCrash;
2640     } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2641       flags |= eHandleCommandFlagStopOnCrash;
2642     }
2643   }
2644 
2645   if (options.m_echo_commands == eLazyBoolCalculate) {
2646     if (m_command_source_flags.empty()) {
2647       // Echo command by default
2648       flags |= eHandleCommandFlagEchoCommand;
2649     } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2650       flags |= eHandleCommandFlagEchoCommand;
2651     }
2652   } else if (options.m_echo_commands == eLazyBoolYes) {
2653     flags |= eHandleCommandFlagEchoCommand;
2654   }
2655 
2656   // We will only ever ask for this flag, if we echo commands in general.
2657   if (options.m_echo_comment_commands == eLazyBoolCalculate) {
2658     if (m_command_source_flags.empty()) {
2659       // Echo comments by default
2660       flags |= eHandleCommandFlagEchoCommentCommand;
2661     } else if (m_command_source_flags.back() &
2662                eHandleCommandFlagEchoCommentCommand) {
2663       flags |= eHandleCommandFlagEchoCommentCommand;
2664     }
2665   } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2666     flags |= eHandleCommandFlagEchoCommentCommand;
2667   }
2668 
2669   if (options.m_print_results == eLazyBoolCalculate) {
2670     if (m_command_source_flags.empty()) {
2671       // Print output by default
2672       flags |= eHandleCommandFlagPrintResult;
2673     } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2674       flags |= eHandleCommandFlagPrintResult;
2675     }
2676   } else if (options.m_print_results == eLazyBoolYes) {
2677     flags |= eHandleCommandFlagPrintResult;
2678   }
2679 
2680   if (options.m_print_errors == eLazyBoolCalculate) {
2681     if (m_command_source_flags.empty()) {
2682       // Print output by default
2683       flags |= eHandleCommandFlagPrintErrors;
2684     } else if (m_command_source_flags.back() & eHandleCommandFlagPrintErrors) {
2685       flags |= eHandleCommandFlagPrintErrors;
2686     }
2687   } else if (options.m_print_errors == eLazyBoolYes) {
2688     flags |= eHandleCommandFlagPrintErrors;
2689   }
2690 
2691   if (flags & eHandleCommandFlagPrintResult) {
2692     debugger.GetOutputFile().Printf("Executing commands in '%s'.\n",
2693                                     cmd_file_path.c_str());
2694   }
2695 
2696   // Used for inheriting the right settings when "command source" might
2697   // have nested "command source" commands
2698   lldb::StreamFileSP empty_stream_sp;
2699   m_command_source_flags.push_back(flags);
2700   IOHandlerSP io_handler_sp(new IOHandlerEditline(
2701       debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2702       empty_stream_sp, // Pass in an empty stream so we inherit the top
2703                        // input reader output stream
2704       empty_stream_sp, // Pass in an empty stream so we inherit the top
2705                        // input reader error stream
2706       flags,
2707       nullptr, // Pass in NULL for "editline_name" so no history is saved,
2708                // or written
2709       debugger.GetPrompt(), llvm::StringRef(),
2710       false, // Not multi-line
2711       debugger.GetUseColor(), 0, *this, nullptr));
2712   const bool old_async_execution = debugger.GetAsyncExecution();
2713 
2714   // Set synchronous execution if we are not stopping on continue
2715   if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2716     debugger.SetAsyncExecution(false);
2717 
2718   m_command_source_depth++;
2719   m_command_source_dirs.push_back(cmd_file.CopyByRemovingLastPathComponent());
2720 
2721   debugger.RunIOHandlerSync(io_handler_sp);
2722   if (!m_command_source_flags.empty())
2723     m_command_source_flags.pop_back();
2724 
2725   m_command_source_dirs.pop_back();
2726   m_command_source_depth--;
2727 
2728   result.SetStatus(eReturnStatusSuccessFinishNoResult);
2729   debugger.SetAsyncExecution(old_async_execution);
2730 }
2731 
2732 bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2733 
2734 void CommandInterpreter::SetSynchronous(bool value) {
2735   // Asynchronous mode is not supported during reproducer replay.
2736   if (repro::Reproducer::Instance().GetLoader())
2737     return;
2738   m_synchronous_execution = value;
2739 }
2740 
2741 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2742                                                  llvm::StringRef prefix,
2743                                                  llvm::StringRef help_text) {
2744   const uint32_t max_columns = m_debugger.GetTerminalWidth();
2745 
2746   size_t line_width_max = max_columns - prefix.size();
2747   if (line_width_max < 16)
2748     line_width_max = help_text.size() + prefix.size();
2749 
2750   strm.IndentMore(prefix.size());
2751   bool prefixed_yet = false;
2752   // Even if we have no help text we still want to emit the command name.
2753   if (help_text.empty())
2754     help_text = "No help text";
2755   while (!help_text.empty()) {
2756     // Prefix the first line, indent subsequent lines to line up
2757     if (!prefixed_yet) {
2758       strm << prefix;
2759       prefixed_yet = true;
2760     } else
2761       strm.Indent();
2762 
2763     // Never print more than the maximum on one line.
2764     llvm::StringRef this_line = help_text.substr(0, line_width_max);
2765 
2766     // Always break on an explicit newline.
2767     std::size_t first_newline = this_line.find_first_of("\n");
2768 
2769     // Don't break on space/tab unless the text is too long to fit on one line.
2770     std::size_t last_space = llvm::StringRef::npos;
2771     if (this_line.size() != help_text.size())
2772       last_space = this_line.find_last_of(" \t");
2773 
2774     // Break at whichever condition triggered first.
2775     this_line = this_line.substr(0, std::min(first_newline, last_space));
2776     strm.PutCString(this_line);
2777     strm.EOL();
2778 
2779     // Remove whitespace / newlines after breaking.
2780     help_text = help_text.drop_front(this_line.size()).ltrim();
2781   }
2782   strm.IndentLess(prefix.size());
2783 }
2784 
2785 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2786                                                  llvm::StringRef word_text,
2787                                                  llvm::StringRef separator,
2788                                                  llvm::StringRef help_text,
2789                                                  size_t max_word_len) {
2790   StreamString prefix_stream;
2791   prefix_stream.Printf("  %-*s %*s ", (int)max_word_len, word_text.data(),
2792                        (int)separator.size(), separator.data());
2793   OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2794 }
2795 
2796 void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2797                                         llvm::StringRef separator,
2798                                         llvm::StringRef help_text,
2799                                         uint32_t max_word_len) {
2800   int indent_size = max_word_len + separator.size() + 2;
2801 
2802   strm.IndentMore(indent_size);
2803 
2804   StreamString text_strm;
2805   text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2806   text_strm << separator << " " << help_text;
2807 
2808   const uint32_t max_columns = m_debugger.GetTerminalWidth();
2809 
2810   llvm::StringRef text = text_strm.GetString();
2811 
2812   uint32_t chars_left = max_columns;
2813 
2814   auto nextWordLength = [](llvm::StringRef S) {
2815     size_t pos = S.find(' ');
2816     return pos == llvm::StringRef::npos ? S.size() : pos;
2817   };
2818 
2819   while (!text.empty()) {
2820     if (text.front() == '\n' ||
2821         (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
2822       strm.EOL();
2823       strm.Indent();
2824       chars_left = max_columns - indent_size;
2825       if (text.front() == '\n')
2826         text = text.drop_front();
2827       else
2828         text = text.ltrim(' ');
2829     } else {
2830       strm.PutChar(text.front());
2831       --chars_left;
2832       text = text.drop_front();
2833     }
2834   }
2835 
2836   strm.EOL();
2837   strm.IndentLess(indent_size);
2838 }
2839 
2840 void CommandInterpreter::FindCommandsForApropos(
2841     llvm::StringRef search_word, StringList &commands_found,
2842     StringList &commands_help, CommandObject::CommandMap &command_map) {
2843   CommandObject::CommandMap::const_iterator pos;
2844 
2845   for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
2846     llvm::StringRef command_name = pos->first;
2847     CommandObject *cmd_obj = pos->second.get();
2848 
2849     const bool search_short_help = true;
2850     const bool search_long_help = false;
2851     const bool search_syntax = false;
2852     const bool search_options = false;
2853     if (command_name.contains_insensitive(search_word) ||
2854         cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2855                                       search_long_help, search_syntax,
2856                                       search_options)) {
2857       commands_found.AppendString(cmd_obj->GetCommandName());
2858       commands_help.AppendString(cmd_obj->GetHelp());
2859     }
2860 
2861     if (cmd_obj->IsMultiwordObject()) {
2862       CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2863       FindCommandsForApropos(search_word, commands_found, commands_help,
2864                              cmd_multiword->GetSubcommandDictionary());
2865     }
2866   }
2867 }
2868 
2869 void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
2870                                                 StringList &commands_found,
2871                                                 StringList &commands_help,
2872                                                 bool search_builtin_commands,
2873                                                 bool search_user_commands,
2874                                                 bool search_alias_commands,
2875                                                 bool search_user_mw_commands) {
2876   CommandObject::CommandMap::const_iterator pos;
2877 
2878   if (search_builtin_commands)
2879     FindCommandsForApropos(search_word, commands_found, commands_help,
2880                            m_command_dict);
2881 
2882   if (search_user_commands)
2883     FindCommandsForApropos(search_word, commands_found, commands_help,
2884                            m_user_dict);
2885 
2886   if (search_user_mw_commands)
2887     FindCommandsForApropos(search_word, commands_found, commands_help,
2888                            m_user_mw_dict);
2889 
2890   if (search_alias_commands)
2891     FindCommandsForApropos(search_word, commands_found, commands_help,
2892                            m_alias_dict);
2893 }
2894 
2895 ExecutionContext CommandInterpreter::GetExecutionContext() const {
2896   return !m_overriden_exe_contexts.empty()
2897              ? m_overriden_exe_contexts.top()
2898              : m_debugger.GetSelectedExecutionContext();
2899 }
2900 
2901 void CommandInterpreter::OverrideExecutionContext(
2902     const ExecutionContext &override_context) {
2903   m_overriden_exe_contexts.push(override_context);
2904 }
2905 
2906 void CommandInterpreter::RestoreExecutionContext() {
2907   if (!m_overriden_exe_contexts.empty())
2908     m_overriden_exe_contexts.pop();
2909 }
2910 
2911 void CommandInterpreter::GetProcessOutput() {
2912   if (ProcessSP process_sp = GetExecutionContext().GetProcessSP())
2913     m_debugger.FlushProcessOutput(*process_sp, /*flush_stdout*/ true,
2914                                   /*flush_stderr*/ true);
2915 }
2916 
2917 void CommandInterpreter::StartHandlingCommand() {
2918   auto idle_state = CommandHandlingState::eIdle;
2919   if (m_command_state.compare_exchange_strong(
2920           idle_state, CommandHandlingState::eInProgress))
2921     lldbassert(m_iohandler_nesting_level == 0);
2922   else
2923     lldbassert(m_iohandler_nesting_level > 0);
2924   ++m_iohandler_nesting_level;
2925 }
2926 
2927 void CommandInterpreter::FinishHandlingCommand() {
2928   lldbassert(m_iohandler_nesting_level > 0);
2929   if (--m_iohandler_nesting_level == 0) {
2930     auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2931     lldbassert(prev_state != CommandHandlingState::eIdle);
2932   }
2933 }
2934 
2935 bool CommandInterpreter::InterruptCommand() {
2936   auto in_progress = CommandHandlingState::eInProgress;
2937   return m_command_state.compare_exchange_strong(
2938       in_progress, CommandHandlingState::eInterrupted);
2939 }
2940 
2941 bool CommandInterpreter::WasInterrupted() const {
2942   bool was_interrupted =
2943       (m_command_state == CommandHandlingState::eInterrupted);
2944   lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2945   return was_interrupted;
2946 }
2947 
2948 void CommandInterpreter::PrintCommandOutput(Stream &stream,
2949                                             llvm::StringRef str) {
2950   // Split the output into lines and poll for interrupt requests
2951   const char *data = str.data();
2952   size_t size = str.size();
2953   while (size > 0 && !WasInterrupted()) {
2954     size_t chunk_size = 0;
2955     for (; chunk_size < size; ++chunk_size) {
2956       lldbassert(data[chunk_size] != '\0');
2957       if (data[chunk_size] == '\n') {
2958         ++chunk_size;
2959         break;
2960       }
2961     }
2962     chunk_size = stream.Write(data, chunk_size);
2963     lldbassert(size >= chunk_size);
2964     data += chunk_size;
2965     size -= chunk_size;
2966   }
2967   if (size > 0) {
2968     stream.Printf("\n... Interrupted.\n");
2969   }
2970 }
2971 
2972 bool CommandInterpreter::EchoCommandNonInteractive(
2973     llvm::StringRef line, const Flags &io_handler_flags) const {
2974   if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2975     return false;
2976 
2977   llvm::StringRef command = line.trim();
2978   if (command.empty())
2979     return true;
2980 
2981   if (command.front() == m_comment_char)
2982     return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2983 
2984   return true;
2985 }
2986 
2987 void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2988                                                 std::string &line) {
2989     // If we were interrupted, bail out...
2990     if (WasInterrupted())
2991       return;
2992 
2993   const bool is_interactive = io_handler.GetIsInteractive();
2994   if (!is_interactive) {
2995     // When we are not interactive, don't execute blank lines. This will happen
2996     // sourcing a commands file. We don't want blank lines to repeat the
2997     // previous command and cause any errors to occur (like redefining an
2998     // alias, get an error and stop parsing the commands file).
2999     if (line.empty())
3000       return;
3001 
3002     // When using a non-interactive file handle (like when sourcing commands
3003     // from a file) we need to echo the command out so we don't just see the
3004     // command output and no command...
3005     if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
3006       io_handler.GetOutputStreamFileSP()->Printf(
3007           "%s%s\n", io_handler.GetPrompt(), line.c_str());
3008   }
3009 
3010   StartHandlingCommand();
3011 
3012   OverrideExecutionContext(m_debugger.GetSelectedExecutionContext());
3013   auto finalize = llvm::make_scope_exit([this]() {
3014     RestoreExecutionContext();
3015   });
3016 
3017   lldb_private::CommandReturnObject result(m_debugger.GetUseColor());
3018   HandleCommand(line.c_str(), eLazyBoolCalculate, result);
3019 
3020   // Now emit the command output text from the command we just executed
3021   if ((result.Succeeded() &&
3022        io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) ||
3023       io_handler.GetFlags().Test(eHandleCommandFlagPrintErrors)) {
3024     // Display any STDOUT/STDERR _prior_ to emitting the command result text
3025     GetProcessOutput();
3026 
3027     if (!result.GetImmediateOutputStream()) {
3028       llvm::StringRef output = result.GetOutputData();
3029       PrintCommandOutput(*io_handler.GetOutputStreamFileSP(), output);
3030     }
3031 
3032     // Now emit the command error text from the command we just executed
3033     if (!result.GetImmediateErrorStream()) {
3034       llvm::StringRef error = result.GetErrorData();
3035       PrintCommandOutput(*io_handler.GetErrorStreamFileSP(), error);
3036     }
3037   }
3038 
3039   FinishHandlingCommand();
3040 
3041   switch (result.GetStatus()) {
3042   case eReturnStatusInvalid:
3043   case eReturnStatusSuccessFinishNoResult:
3044   case eReturnStatusSuccessFinishResult:
3045   case eReturnStatusStarted:
3046     break;
3047 
3048   case eReturnStatusSuccessContinuingNoResult:
3049   case eReturnStatusSuccessContinuingResult:
3050     if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3051       io_handler.SetIsDone(true);
3052     break;
3053 
3054   case eReturnStatusFailed:
3055     m_result.IncrementNumberOfErrors();
3056     if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError)) {
3057       m_result.SetResult(lldb::eCommandInterpreterResultCommandError);
3058       io_handler.SetIsDone(true);
3059     }
3060     break;
3061 
3062   case eReturnStatusQuit:
3063     m_result.SetResult(lldb::eCommandInterpreterResultQuitRequested);
3064     io_handler.SetIsDone(true);
3065     break;
3066   }
3067 
3068   // Finally, if we're going to stop on crash, check that here:
3069   if (m_result.IsResult(lldb::eCommandInterpreterResultSuccess) &&
3070       result.GetDidChangeProcessState() &&
3071       io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash) &&
3072       DidProcessStopAbnormally()) {
3073     io_handler.SetIsDone(true);
3074     m_result.SetResult(lldb::eCommandInterpreterResultInferiorCrash);
3075   }
3076 }
3077 
3078 bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
3079   ExecutionContext exe_ctx(GetExecutionContext());
3080   Process *process = exe_ctx.GetProcessPtr();
3081 
3082   if (InterruptCommand())
3083     return true;
3084 
3085   if (process) {
3086     StateType state = process->GetState();
3087     if (StateIsRunningState(state)) {
3088       process->Halt();
3089       return true; // Don't do any updating when we are running
3090     }
3091   }
3092 
3093   ScriptInterpreter *script_interpreter =
3094       m_debugger.GetScriptInterpreter(false);
3095   if (script_interpreter) {
3096     if (script_interpreter->Interrupt())
3097       return true;
3098   }
3099   return false;
3100 }
3101 
3102 bool CommandInterpreter::SaveTranscript(
3103     CommandReturnObject &result, llvm::Optional<std::string> output_file) {
3104   if (output_file == llvm::None || output_file->empty()) {
3105     std::string now = llvm::to_string(std::chrono::system_clock::now());
3106     std::replace(now.begin(), now.end(), ' ', '_');
3107     const std::string file_name = "lldb_session_" + now + ".log";
3108 
3109     FileSpec save_location = GetSaveSessionDirectory();
3110 
3111     if (!save_location)
3112       save_location = HostInfo::GetGlobalTempDir();
3113 
3114     FileSystem::Instance().Resolve(save_location);
3115     save_location.AppendPathComponent(file_name);
3116     output_file = save_location.GetPath();
3117   }
3118 
3119   auto error_out = [&](llvm::StringRef error_message, std::string description) {
3120     LLDB_LOG(GetLogIfAllCategoriesSet(LIBLLDB_LOG_COMMANDS), "{0} ({1}:{2})",
3121              error_message, output_file, description);
3122     result.AppendErrorWithFormatv(
3123         "Failed to save session's transcripts to {0}!", *output_file);
3124     return false;
3125   };
3126 
3127   File::OpenOptions flags = File::eOpenOptionWriteOnly |
3128                             File::eOpenOptionCanCreate |
3129                             File::eOpenOptionTruncate;
3130 
3131   auto opened_file = FileSystem::Instance().Open(FileSpec(*output_file), flags);
3132 
3133   if (!opened_file)
3134     return error_out("Unable to create file",
3135                      llvm::toString(opened_file.takeError()));
3136 
3137   FileUP file = std::move(opened_file.get());
3138 
3139   size_t byte_size = m_transcript_stream.GetSize();
3140 
3141   Status error = file->Write(m_transcript_stream.GetData(), byte_size);
3142 
3143   if (error.Fail() || byte_size != m_transcript_stream.GetSize())
3144     return error_out("Unable to write to destination file",
3145                      "Bytes written do not match transcript size.");
3146 
3147   result.SetStatus(eReturnStatusSuccessFinishNoResult);
3148   result.AppendMessageWithFormat("Session's transcripts saved to %s\n",
3149                                  output_file->c_str());
3150 
3151   return true;
3152 }
3153 
3154 FileSpec CommandInterpreter::GetCurrentSourceDir() {
3155   if (m_command_source_dirs.empty())
3156     return {};
3157   return m_command_source_dirs.back();
3158 }
3159 
3160 void CommandInterpreter::GetLLDBCommandsFromIOHandler(
3161     const char *prompt, IOHandlerDelegate &delegate, void *baton) {
3162   Debugger &debugger = GetDebugger();
3163   IOHandlerSP io_handler_sp(
3164       new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
3165                             "lldb", // Name of input reader for history
3166                             llvm::StringRef(prompt), // Prompt
3167                             llvm::StringRef(),       // Continuation prompt
3168                             true,                    // Get multiple lines
3169                             debugger.GetUseColor(),
3170                             0,         // Don't show line numbers
3171                             delegate,  // IOHandlerDelegate
3172                             nullptr)); // FileShadowCollector
3173 
3174   if (io_handler_sp) {
3175     io_handler_sp->SetUserData(baton);
3176     debugger.RunIOHandlerAsync(io_handler_sp);
3177   }
3178 }
3179 
3180 void CommandInterpreter::GetPythonCommandsFromIOHandler(
3181     const char *prompt, IOHandlerDelegate &delegate, void *baton) {
3182   Debugger &debugger = GetDebugger();
3183   IOHandlerSP io_handler_sp(
3184       new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
3185                             "lldb-python", // Name of input reader for history
3186                             llvm::StringRef(prompt), // Prompt
3187                             llvm::StringRef(),       // Continuation prompt
3188                             true,                    // Get multiple lines
3189                             debugger.GetUseColor(),
3190                             0,         // Don't show line numbers
3191                             delegate,  // IOHandlerDelegate
3192                             nullptr)); // FileShadowCollector
3193 
3194   if (io_handler_sp) {
3195     io_handler_sp->SetUserData(baton);
3196     debugger.RunIOHandlerAsync(io_handler_sp);
3197   }
3198 }
3199 
3200 bool CommandInterpreter::IsActive() {
3201   return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
3202 }
3203 
3204 lldb::IOHandlerSP
3205 CommandInterpreter::GetIOHandler(bool force_create,
3206                                  CommandInterpreterRunOptions *options) {
3207   // Always re-create the IOHandlerEditline in case the input changed. The old
3208   // instance might have had a non-interactive input and now it does or vice
3209   // versa.
3210   if (force_create || !m_command_io_handler_sp) {
3211     // Always re-create the IOHandlerEditline in case the input changed. The
3212     // old instance might have had a non-interactive input and now it does or
3213     // vice versa.
3214     uint32_t flags = 0;
3215 
3216     if (options) {
3217       if (options->m_stop_on_continue == eLazyBoolYes)
3218         flags |= eHandleCommandFlagStopOnContinue;
3219       if (options->m_stop_on_error == eLazyBoolYes)
3220         flags |= eHandleCommandFlagStopOnError;
3221       if (options->m_stop_on_crash == eLazyBoolYes)
3222         flags |= eHandleCommandFlagStopOnCrash;
3223       if (options->m_echo_commands != eLazyBoolNo)
3224         flags |= eHandleCommandFlagEchoCommand;
3225       if (options->m_echo_comment_commands != eLazyBoolNo)
3226         flags |= eHandleCommandFlagEchoCommentCommand;
3227       if (options->m_print_results != eLazyBoolNo)
3228         flags |= eHandleCommandFlagPrintResult;
3229       if (options->m_print_errors != eLazyBoolNo)
3230         flags |= eHandleCommandFlagPrintErrors;
3231     } else {
3232       flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult |
3233               eHandleCommandFlagPrintErrors;
3234     }
3235 
3236     m_command_io_handler_sp = std::make_shared<IOHandlerEditline>(
3237         m_debugger, IOHandler::Type::CommandInterpreter,
3238         m_debugger.GetInputFileSP(), m_debugger.GetOutputStreamSP(),
3239         m_debugger.GetErrorStreamSP(), flags, "lldb", m_debugger.GetPrompt(),
3240         llvm::StringRef(), // Continuation prompt
3241         false, // Don't enable multiple line input, just single line commands
3242         m_debugger.GetUseColor(),
3243         0,     // Don't show line numbers
3244         *this, // IOHandlerDelegate
3245         GetDebugger().GetInputRecorder());
3246   }
3247   return m_command_io_handler_sp;
3248 }
3249 
3250 CommandInterpreterRunResult CommandInterpreter::RunCommandInterpreter(
3251     CommandInterpreterRunOptions &options) {
3252   // Always re-create the command interpreter when we run it in case any file
3253   // handles have changed.
3254   bool force_create = true;
3255   m_debugger.RunIOHandlerAsync(GetIOHandler(force_create, &options));
3256   m_result = CommandInterpreterRunResult();
3257 
3258   if (options.GetAutoHandleEvents())
3259     m_debugger.StartEventHandlerThread();
3260 
3261   if (options.GetSpawnThread()) {
3262     m_debugger.StartIOHandlerThread();
3263   } else {
3264     m_debugger.RunIOHandlers();
3265 
3266     if (options.GetAutoHandleEvents())
3267       m_debugger.StopEventHandlerThread();
3268   }
3269 
3270   return m_result;
3271 }
3272 
3273 CommandObject *
3274 CommandInterpreter::ResolveCommandImpl(std::string &command_line,
3275                                        CommandReturnObject &result) {
3276   std::string scratch_command(command_line); // working copy so we don't modify
3277                                              // command_line unless we succeed
3278   CommandObject *cmd_obj = nullptr;
3279   StreamString revised_command_line;
3280   bool wants_raw_input = false;
3281   std::string next_word;
3282   StringList matches;
3283   bool done = false;
3284   while (!done) {
3285     char quote_char = '\0';
3286     std::string suffix;
3287     ExtractCommand(scratch_command, next_word, suffix, quote_char);
3288     if (cmd_obj == nullptr) {
3289       std::string full_name;
3290       bool is_alias = GetAliasFullName(next_word, full_name);
3291       cmd_obj = GetCommandObject(next_word, &matches);
3292       bool is_real_command =
3293           (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
3294       if (!is_real_command) {
3295         matches.Clear();
3296         std::string alias_result;
3297         cmd_obj =
3298             BuildAliasResult(full_name, scratch_command, alias_result, result);
3299         revised_command_line.Printf("%s", alias_result.c_str());
3300         if (cmd_obj) {
3301           wants_raw_input = cmd_obj->WantsRawCommandString();
3302         }
3303       } else {
3304         if (cmd_obj) {
3305           llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3306           revised_command_line.Printf("%s", cmd_name.str().c_str());
3307           wants_raw_input = cmd_obj->WantsRawCommandString();
3308         } else {
3309           revised_command_line.Printf("%s", next_word.c_str());
3310         }
3311       }
3312     } else {
3313       if (cmd_obj->IsMultiwordObject()) {
3314         CommandObject *sub_cmd_obj =
3315             cmd_obj->GetSubcommandObject(next_word.c_str());
3316         if (sub_cmd_obj) {
3317           // The subcommand's name includes the parent command's name, so
3318           // restart rather than append to the revised_command_line.
3319           llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3320           revised_command_line.Clear();
3321           revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
3322           cmd_obj = sub_cmd_obj;
3323           wants_raw_input = cmd_obj->WantsRawCommandString();
3324         } else {
3325           if (quote_char)
3326             revised_command_line.Printf(" %c%s%s%c", quote_char,
3327                                         next_word.c_str(), suffix.c_str(),
3328                                         quote_char);
3329           else
3330             revised_command_line.Printf(" %s%s", next_word.c_str(),
3331                                         suffix.c_str());
3332           done = true;
3333         }
3334       } else {
3335         if (quote_char)
3336           revised_command_line.Printf(" %c%s%s%c", quote_char,
3337                                       next_word.c_str(), suffix.c_str(),
3338                                       quote_char);
3339         else
3340           revised_command_line.Printf(" %s%s", next_word.c_str(),
3341                                       suffix.c_str());
3342         done = true;
3343       }
3344     }
3345 
3346     if (cmd_obj == nullptr) {
3347       const size_t num_matches = matches.GetSize();
3348       if (matches.GetSize() > 1) {
3349         StreamString error_msg;
3350         error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3351                          next_word.c_str());
3352 
3353         for (uint32_t i = 0; i < num_matches; ++i) {
3354           error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3355         }
3356         result.AppendRawError(error_msg.GetString());
3357       } else {
3358         // We didn't have only one match, otherwise we wouldn't get here.
3359         lldbassert(num_matches == 0);
3360         result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3361                                      next_word.c_str());
3362       }
3363       return nullptr;
3364     }
3365 
3366     if (cmd_obj->IsMultiwordObject()) {
3367       if (!suffix.empty()) {
3368         result.AppendErrorWithFormat(
3369             "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3370             "might be invalid).\n",
3371             cmd_obj->GetCommandName().str().c_str(),
3372             next_word.empty() ? "" : next_word.c_str(),
3373             next_word.empty() ? " -- " : " ", suffix.c_str());
3374         return nullptr;
3375       }
3376     } else {
3377       // If we found a normal command, we are done
3378       done = true;
3379       if (!suffix.empty()) {
3380         switch (suffix[0]) {
3381         case '/':
3382           // GDB format suffixes
3383           {
3384             Options *command_options = cmd_obj->GetOptions();
3385             if (command_options &&
3386                 command_options->SupportsLongOption("gdb-format")) {
3387               std::string gdb_format_option("--gdb-format=");
3388               gdb_format_option += (suffix.c_str() + 1);
3389 
3390               std::string cmd = std::string(revised_command_line.GetString());
3391               size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3392               if (arg_terminator_idx != std::string::npos) {
3393                 // Insert the gdb format option before the "--" that terminates
3394                 // options
3395                 gdb_format_option.append(1, ' ');
3396                 cmd.insert(arg_terminator_idx, gdb_format_option);
3397                 revised_command_line.Clear();
3398                 revised_command_line.PutCString(cmd);
3399               } else
3400                 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3401 
3402               if (wants_raw_input &&
3403                   FindArgumentTerminator(cmd) == std::string::npos)
3404                 revised_command_line.PutCString(" --");
3405             } else {
3406               result.AppendErrorWithFormat(
3407                   "the '%s' command doesn't support the --gdb-format option\n",
3408                   cmd_obj->GetCommandName().str().c_str());
3409               return nullptr;
3410             }
3411           }
3412           break;
3413 
3414         default:
3415           result.AppendErrorWithFormat(
3416               "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3417           return nullptr;
3418         }
3419       }
3420     }
3421     if (scratch_command.empty())
3422       done = true;
3423   }
3424 
3425   if (!scratch_command.empty())
3426     revised_command_line.Printf(" %s", scratch_command.c_str());
3427 
3428   if (cmd_obj != nullptr)
3429     command_line = std::string(revised_command_line.GetString());
3430 
3431   return cmd_obj;
3432 }
3433