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