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