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");
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);
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         if (!init_file.Exists())
2131           init_file.Clear();
2132       }
2133     }
2134 
2135     if (!init_file && !m_skip_lldbinit_files)
2136       init_file.SetFile(init_file_path, false);
2137   }
2138 
2139   // If the file exists, tell HandleCommand to 'source' it; this will do the
2140   // actual broadcasting of the commands back to any appropriate listener (see
2141   // CommandObjectSource::Execute for more details).
2142 
2143   if (init_file.Exists()) {
2144     const bool saved_batch = SetBatchCommandMode(true);
2145     CommandInterpreterRunOptions options;
2146     options.SetSilent(true);
2147     options.SetStopOnError(false);
2148     options.SetStopOnContinue(true);
2149 
2150     HandleCommandsFromFile(init_file,
2151                            nullptr, // Execution context
2152                            options, result);
2153     SetBatchCommandMode(saved_batch);
2154   } else {
2155     // nothing to be done if the file doesn't exist
2156     result.SetStatus(eReturnStatusSuccessFinishNoResult);
2157   }
2158 }
2159 
2160 const char *CommandInterpreter::GetCommandPrefix() {
2161   const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2162   return prefix == NULL ? "" : prefix;
2163 }
2164 
2165 PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2166   PlatformSP platform_sp;
2167   if (prefer_target_platform) {
2168     ExecutionContext exe_ctx(GetExecutionContext());
2169     Target *target = exe_ctx.GetTargetPtr();
2170     if (target)
2171       platform_sp = target->GetPlatform();
2172   }
2173 
2174   if (!platform_sp)
2175     platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2176   return platform_sp;
2177 }
2178 
2179 void CommandInterpreter::HandleCommands(const StringList &commands,
2180                                         ExecutionContext *override_context,
2181                                         CommandInterpreterRunOptions &options,
2182                                         CommandReturnObject &result) {
2183   size_t num_lines = commands.GetSize();
2184 
2185   // If we are going to continue past a "continue" then we need to run the
2186   // commands synchronously. Make sure you reset this value anywhere you return
2187   // from the function.
2188 
2189   bool old_async_execution = m_debugger.GetAsyncExecution();
2190 
2191   // If we've been given an execution context, set it at the start, but don't
2192   // keep resetting it or we will cause series of commands that change the
2193   // context, then do an operation that relies on that context to fail.
2194 
2195   if (override_context != nullptr)
2196     UpdateExecutionContext(override_context);
2197 
2198   if (!options.GetStopOnContinue()) {
2199     m_debugger.SetAsyncExecution(false);
2200   }
2201 
2202   for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
2203     const char *cmd = commands.GetStringAtIndex(idx);
2204     if (cmd[0] == '\0')
2205       continue;
2206 
2207     if (options.GetEchoCommands()) {
2208       // TODO: Add Stream support.
2209       result.AppendMessageWithFormat("%s %s\n",
2210                                      m_debugger.GetPrompt().str().c_str(), cmd);
2211     }
2212 
2213     CommandReturnObject tmp_result;
2214     // If override_context is not NULL, pass no_context_switching = true for
2215     // HandleCommand() since we updated our context already.
2216 
2217     // We might call into a regex or alias command, in which case the
2218     // add_to_history will get lost.  This m_command_source_depth dingus is the
2219     // way we turn off adding to the history in that case, so set it up here.
2220     if (!options.GetAddToHistory())
2221       m_command_source_depth++;
2222     bool success =
2223         HandleCommand(cmd, options.m_add_to_history, tmp_result,
2224                       nullptr, /* override_context */
2225                       true,    /* repeat_on_empty_command */
2226                       override_context != nullptr /* no_context_switching */);
2227     if (!options.GetAddToHistory())
2228       m_command_source_depth--;
2229 
2230     if (options.GetPrintResults()) {
2231       if (tmp_result.Succeeded())
2232         result.AppendMessage(tmp_result.GetOutputData());
2233     }
2234 
2235     if (!success || !tmp_result.Succeeded()) {
2236       llvm::StringRef error_msg = tmp_result.GetErrorData();
2237       if (error_msg.empty())
2238         error_msg = "<unknown error>.\n";
2239       if (options.GetStopOnError()) {
2240         result.AppendErrorWithFormat(
2241             "Aborting reading of commands after command #%" PRIu64
2242             ": '%s' failed with %s",
2243             (uint64_t)idx, cmd, error_msg.str().c_str());
2244         result.SetStatus(eReturnStatusFailed);
2245         m_debugger.SetAsyncExecution(old_async_execution);
2246         return;
2247       } else if (options.GetPrintResults()) {
2248         result.AppendMessageWithFormat(
2249             "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2250             error_msg.str().c_str());
2251       }
2252     }
2253 
2254     if (result.GetImmediateOutputStream())
2255       result.GetImmediateOutputStream()->Flush();
2256 
2257     if (result.GetImmediateErrorStream())
2258       result.GetImmediateErrorStream()->Flush();
2259 
2260     // N.B. Can't depend on DidChangeProcessState, because the state coming
2261     // into the command execution could be running (for instance in Breakpoint
2262     // Commands. So we check the return value to see if it is has running in
2263     // it.
2264     if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2265         (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2266       if (options.GetStopOnContinue()) {
2267         // If we caused the target to proceed, and we're going to stop in that
2268         // case, set the status in our real result before returning.  This is
2269         // an error if the continue was not the last command in the set of
2270         // commands to be run.
2271         if (idx != num_lines - 1)
2272           result.AppendErrorWithFormat(
2273               "Aborting reading of commands after command #%" PRIu64
2274               ": '%s' continued the target.\n",
2275               (uint64_t)idx + 1, cmd);
2276         else
2277           result.AppendMessageWithFormat("Command #%" PRIu64
2278                                          " '%s' continued the target.\n",
2279                                          (uint64_t)idx + 1, cmd);
2280 
2281         result.SetStatus(tmp_result.GetStatus());
2282         m_debugger.SetAsyncExecution(old_async_execution);
2283 
2284         return;
2285       }
2286     }
2287 
2288     // Also check for "stop on crash here:
2289     bool should_stop = false;
2290     if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2291       TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2292       if (target_sp) {
2293         ProcessSP process_sp(target_sp->GetProcessSP());
2294         if (process_sp) {
2295           for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2296             StopReason reason = thread_sp->GetStopReason();
2297             if (reason == eStopReasonSignal || reason == eStopReasonException ||
2298                 reason == eStopReasonInstrumentation) {
2299               should_stop = true;
2300               break;
2301             }
2302           }
2303         }
2304       }
2305       if (should_stop) {
2306         if (idx != num_lines - 1)
2307           result.AppendErrorWithFormat(
2308               "Aborting reading of commands after command #%" PRIu64
2309               ": '%s' stopped with a signal or exception.\n",
2310               (uint64_t)idx + 1, cmd);
2311         else
2312           result.AppendMessageWithFormat(
2313               "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2314               (uint64_t)idx + 1, cmd);
2315 
2316         result.SetStatus(tmp_result.GetStatus());
2317         m_debugger.SetAsyncExecution(old_async_execution);
2318 
2319         return;
2320       }
2321     }
2322   }
2323 
2324   result.SetStatus(eReturnStatusSuccessFinishResult);
2325   m_debugger.SetAsyncExecution(old_async_execution);
2326 
2327   return;
2328 }
2329 
2330 // Make flags that we can pass into the IOHandler so our delegates can do the
2331 // right thing
2332 enum {
2333   eHandleCommandFlagStopOnContinue = (1u << 0),
2334   eHandleCommandFlagStopOnError = (1u << 1),
2335   eHandleCommandFlagEchoCommand = (1u << 2),
2336   eHandleCommandFlagPrintResult = (1u << 3),
2337   eHandleCommandFlagStopOnCrash = (1u << 4)
2338 };
2339 
2340 void CommandInterpreter::HandleCommandsFromFile(
2341     FileSpec &cmd_file, ExecutionContext *context,
2342     CommandInterpreterRunOptions &options, CommandReturnObject &result) {
2343   if (cmd_file.Exists()) {
2344     StreamFileSP input_file_sp(new StreamFile());
2345 
2346     std::string cmd_file_path = cmd_file.GetPath();
2347     Status error = input_file_sp->GetFile().Open(cmd_file_path.c_str(),
2348                                                  File::eOpenOptionRead);
2349 
2350     if (error.Success()) {
2351       Debugger &debugger = GetDebugger();
2352 
2353       uint32_t flags = 0;
2354 
2355       if (options.m_stop_on_continue == eLazyBoolCalculate) {
2356         if (m_command_source_flags.empty()) {
2357           // Stop on continue by default
2358           flags |= eHandleCommandFlagStopOnContinue;
2359         } else if (m_command_source_flags.back() &
2360                    eHandleCommandFlagStopOnContinue) {
2361           flags |= eHandleCommandFlagStopOnContinue;
2362         }
2363       } else if (options.m_stop_on_continue == eLazyBoolYes) {
2364         flags |= eHandleCommandFlagStopOnContinue;
2365       }
2366 
2367       if (options.m_stop_on_error == eLazyBoolCalculate) {
2368         if (m_command_source_flags.empty()) {
2369           if (GetStopCmdSourceOnError())
2370             flags |= eHandleCommandFlagStopOnError;
2371         } else if (m_command_source_flags.back() &
2372                    eHandleCommandFlagStopOnError) {
2373           flags |= eHandleCommandFlagStopOnError;
2374         }
2375       } else if (options.m_stop_on_error == eLazyBoolYes) {
2376         flags |= eHandleCommandFlagStopOnError;
2377       }
2378 
2379       if (options.GetStopOnCrash()) {
2380         if (m_command_source_flags.empty()) {
2381           // Echo command by default
2382           flags |= eHandleCommandFlagStopOnCrash;
2383         } else if (m_command_source_flags.back() &
2384                    eHandleCommandFlagStopOnCrash) {
2385           flags |= eHandleCommandFlagStopOnCrash;
2386         }
2387       }
2388 
2389       if (options.m_echo_commands == eLazyBoolCalculate) {
2390         if (m_command_source_flags.empty()) {
2391           // Echo command by default
2392           flags |= eHandleCommandFlagEchoCommand;
2393         } else if (m_command_source_flags.back() &
2394                    eHandleCommandFlagEchoCommand) {
2395           flags |= eHandleCommandFlagEchoCommand;
2396         }
2397       } else if (options.m_echo_commands == eLazyBoolYes) {
2398         flags |= eHandleCommandFlagEchoCommand;
2399       }
2400 
2401       if (options.m_print_results == eLazyBoolCalculate) {
2402         if (m_command_source_flags.empty()) {
2403           // Print output by default
2404           flags |= eHandleCommandFlagPrintResult;
2405         } else if (m_command_source_flags.back() &
2406                    eHandleCommandFlagPrintResult) {
2407           flags |= eHandleCommandFlagPrintResult;
2408         }
2409       } else if (options.m_print_results == eLazyBoolYes) {
2410         flags |= eHandleCommandFlagPrintResult;
2411       }
2412 
2413       if (flags & eHandleCommandFlagPrintResult) {
2414         debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2415                                          cmd_file_path.c_str());
2416       }
2417 
2418       // Used for inheriting the right settings when "command source" might
2419       // have nested "command source" commands
2420       lldb::StreamFileSP empty_stream_sp;
2421       m_command_source_flags.push_back(flags);
2422       IOHandlerSP io_handler_sp(new IOHandlerEditline(
2423           debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2424           empty_stream_sp, // Pass in an empty stream so we inherit the top
2425                            // input reader output stream
2426           empty_stream_sp, // Pass in an empty stream so we inherit the top
2427                            // input reader error stream
2428           flags,
2429           nullptr, // Pass in NULL for "editline_name" so no history is saved,
2430                    // or written
2431           debugger.GetPrompt(), llvm::StringRef(),
2432           false, // Not multi-line
2433           debugger.GetUseColor(), 0, *this));
2434       const bool old_async_execution = debugger.GetAsyncExecution();
2435 
2436       // Set synchronous execution if we are not stopping on continue
2437       if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2438         debugger.SetAsyncExecution(false);
2439 
2440       m_command_source_depth++;
2441 
2442       debugger.RunIOHandler(io_handler_sp);
2443       if (!m_command_source_flags.empty())
2444         m_command_source_flags.pop_back();
2445       m_command_source_depth--;
2446       result.SetStatus(eReturnStatusSuccessFinishNoResult);
2447       debugger.SetAsyncExecution(old_async_execution);
2448     } else {
2449       result.AppendErrorWithFormat(
2450           "error: an error occurred read file '%s': %s\n",
2451           cmd_file_path.c_str(), error.AsCString());
2452       result.SetStatus(eReturnStatusFailed);
2453     }
2454 
2455   } else {
2456     result.AppendErrorWithFormat(
2457         "Error reading commands from file %s - file not found.\n",
2458         cmd_file.GetFilename().AsCString("<Unknown>"));
2459     result.SetStatus(eReturnStatusFailed);
2460     return;
2461   }
2462 }
2463 
2464 ScriptInterpreter *CommandInterpreter::GetScriptInterpreter(bool can_create) {
2465   std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
2466   if (!m_script_interpreter_sp) {
2467     if (!can_create)
2468       return nullptr;
2469     lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2470     m_script_interpreter_sp =
2471         PluginManager::GetScriptInterpreterForLanguage(script_lang, *this);
2472   }
2473   return m_script_interpreter_sp.get();
2474 }
2475 
2476 bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2477 
2478 void CommandInterpreter::SetSynchronous(bool value) {
2479   m_synchronous_execution = value;
2480 }
2481 
2482 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2483                                                  llvm::StringRef prefix,
2484                                                  llvm::StringRef help_text) {
2485   const uint32_t max_columns = m_debugger.GetTerminalWidth();
2486 
2487   size_t line_width_max = max_columns - prefix.size();
2488   if (line_width_max < 16)
2489     line_width_max = help_text.size() + prefix.size();
2490 
2491   strm.IndentMore(prefix.size());
2492   bool prefixed_yet = false;
2493   while (!help_text.empty()) {
2494     // Prefix the first line, indent subsequent lines to line up
2495     if (!prefixed_yet) {
2496       strm << prefix;
2497       prefixed_yet = true;
2498     } else
2499       strm.Indent();
2500 
2501     // Never print more than the maximum on one line.
2502     llvm::StringRef this_line = help_text.substr(0, line_width_max);
2503 
2504     // Always break on an explicit newline.
2505     std::size_t first_newline = this_line.find_first_of("\n");
2506 
2507     // Don't break on space/tab unless the text is too long to fit on one line.
2508     std::size_t last_space = llvm::StringRef::npos;
2509     if (this_line.size() != help_text.size())
2510       last_space = this_line.find_last_of(" \t");
2511 
2512     // Break at whichever condition triggered first.
2513     this_line = this_line.substr(0, std::min(first_newline, last_space));
2514     strm.PutCString(this_line);
2515     strm.EOL();
2516 
2517     // Remove whitespace / newlines after breaking.
2518     help_text = help_text.drop_front(this_line.size()).ltrim();
2519   }
2520   strm.IndentLess(prefix.size());
2521 }
2522 
2523 void CommandInterpreter::OutputFormattedHelpText(Stream &strm,
2524                                                  llvm::StringRef word_text,
2525                                                  llvm::StringRef separator,
2526                                                  llvm::StringRef help_text,
2527                                                  size_t max_word_len) {
2528   StreamString prefix_stream;
2529   prefix_stream.Printf("  %-*s %*s ", (int)max_word_len, word_text.data(),
2530                        (int)separator.size(), separator.data());
2531   OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2532 }
2533 
2534 void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2535                                         llvm::StringRef separator,
2536                                         llvm::StringRef help_text,
2537                                         uint32_t max_word_len) {
2538   int indent_size = max_word_len + separator.size() + 2;
2539 
2540   strm.IndentMore(indent_size);
2541 
2542   StreamString text_strm;
2543   text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2544   text_strm << separator << " " << help_text;
2545 
2546   const uint32_t max_columns = m_debugger.GetTerminalWidth();
2547 
2548   llvm::StringRef text = text_strm.GetString();
2549 
2550   uint32_t chars_left = max_columns;
2551 
2552   auto nextWordLength = [](llvm::StringRef S) {
2553     size_t pos = S.find_first_of(' ');
2554     return pos == llvm::StringRef::npos ? S.size() : pos;
2555   };
2556 
2557   while (!text.empty()) {
2558     if (text.front() == '\n' ||
2559         (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
2560       strm.EOL();
2561       strm.Indent();
2562       chars_left = max_columns - indent_size;
2563       if (text.front() == '\n')
2564         text = text.drop_front();
2565       else
2566         text = text.ltrim(' ');
2567     } else {
2568       strm.PutChar(text.front());
2569       --chars_left;
2570       text = text.drop_front();
2571     }
2572   }
2573 
2574   strm.EOL();
2575   strm.IndentLess(indent_size);
2576 }
2577 
2578 void CommandInterpreter::FindCommandsForApropos(
2579     llvm::StringRef search_word, StringList &commands_found,
2580     StringList &commands_help, CommandObject::CommandMap &command_map) {
2581   CommandObject::CommandMap::const_iterator pos;
2582 
2583   for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
2584     llvm::StringRef command_name = pos->first;
2585     CommandObject *cmd_obj = pos->second.get();
2586 
2587     const bool search_short_help = true;
2588     const bool search_long_help = false;
2589     const bool search_syntax = false;
2590     const bool search_options = false;
2591     if (command_name.contains_lower(search_word) ||
2592         cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2593                                       search_long_help, search_syntax,
2594                                       search_options)) {
2595       commands_found.AppendString(cmd_obj->GetCommandName());
2596       commands_help.AppendString(cmd_obj->GetHelp());
2597     }
2598 
2599     if (cmd_obj->IsMultiwordObject()) {
2600       CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2601       FindCommandsForApropos(search_word, commands_found, commands_help,
2602                              cmd_multiword->GetSubcommandDictionary());
2603     }
2604   }
2605 }
2606 
2607 void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
2608                                                 StringList &commands_found,
2609                                                 StringList &commands_help,
2610                                                 bool search_builtin_commands,
2611                                                 bool search_user_commands,
2612                                                 bool search_alias_commands) {
2613   CommandObject::CommandMap::const_iterator pos;
2614 
2615   if (search_builtin_commands)
2616     FindCommandsForApropos(search_word, commands_found, commands_help,
2617                            m_command_dict);
2618 
2619   if (search_user_commands)
2620     FindCommandsForApropos(search_word, commands_found, commands_help,
2621                            m_user_dict);
2622 
2623   if (search_alias_commands)
2624     FindCommandsForApropos(search_word, commands_found, commands_help,
2625                            m_alias_dict);
2626 }
2627 
2628 void CommandInterpreter::UpdateExecutionContext(
2629     ExecutionContext *override_context) {
2630   if (override_context != nullptr) {
2631     m_exe_ctx_ref = *override_context;
2632   } else {
2633     const bool adopt_selected = true;
2634     m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2635                                adopt_selected);
2636   }
2637 }
2638 
2639 size_t CommandInterpreter::GetProcessOutput() {
2640   //  The process has stuff waiting for stderr; get it and write it out to the
2641   //  appropriate place.
2642   char stdio_buffer[1024];
2643   size_t len;
2644   size_t total_bytes = 0;
2645   Status error;
2646   TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2647   if (target_sp) {
2648     ProcessSP process_sp(target_sp->GetProcessSP());
2649     if (process_sp) {
2650       while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2651                                           error)) > 0) {
2652         size_t bytes_written = len;
2653         m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2654         total_bytes += len;
2655       }
2656       while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2657                                           error)) > 0) {
2658         size_t bytes_written = len;
2659         m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2660         total_bytes += len;
2661       }
2662     }
2663   }
2664   return total_bytes;
2665 }
2666 
2667 void CommandInterpreter::StartHandlingCommand() {
2668   auto idle_state = CommandHandlingState::eIdle;
2669   if (m_command_state.compare_exchange_strong(
2670           idle_state, CommandHandlingState::eInProgress))
2671     lldbassert(m_iohandler_nesting_level == 0);
2672   else
2673     lldbassert(m_iohandler_nesting_level > 0);
2674   ++m_iohandler_nesting_level;
2675 }
2676 
2677 void CommandInterpreter::FinishHandlingCommand() {
2678   lldbassert(m_iohandler_nesting_level > 0);
2679   if (--m_iohandler_nesting_level == 0) {
2680     auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2681     lldbassert(prev_state != CommandHandlingState::eIdle);
2682   }
2683 }
2684 
2685 bool CommandInterpreter::InterruptCommand() {
2686   auto in_progress = CommandHandlingState::eInProgress;
2687   return m_command_state.compare_exchange_strong(
2688       in_progress, CommandHandlingState::eInterrupted);
2689 }
2690 
2691 bool CommandInterpreter::WasInterrupted() const {
2692   bool was_interrupted =
2693       (m_command_state == CommandHandlingState::eInterrupted);
2694   lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2695   return was_interrupted;
2696 }
2697 
2698 void CommandInterpreter::PrintCommandOutput(Stream &stream,
2699                                             llvm::StringRef str) {
2700   // Split the output into lines and poll for interrupt requests
2701   const char *data = str.data();
2702   size_t size = str.size();
2703   while (size > 0 && !WasInterrupted()) {
2704     size_t chunk_size = 0;
2705     for (; chunk_size < size; ++chunk_size) {
2706       lldbassert(data[chunk_size] != '\0');
2707       if (data[chunk_size] == '\n') {
2708         ++chunk_size;
2709         break;
2710       }
2711     }
2712     chunk_size = stream.Write(data, chunk_size);
2713     lldbassert(size >= chunk_size);
2714     data += chunk_size;
2715     size -= chunk_size;
2716   }
2717   if (size > 0) {
2718     stream.Printf("\n... Interrupted.\n");
2719   }
2720 }
2721 
2722 void CommandInterpreter::IOHandlerInputComplete(IOHandler &io_handler,
2723                                                 std::string &line) {
2724     // If we were interrupted, bail out...
2725     if (WasInterrupted())
2726       return;
2727 
2728   const bool is_interactive = io_handler.GetIsInteractive();
2729   if (is_interactive == false) {
2730     // When we are not interactive, don't execute blank lines. This will happen
2731     // sourcing a commands file. We don't want blank lines to repeat the
2732     // previous command and cause any errors to occur (like redefining an
2733     // alias, get an error and stop parsing the commands file).
2734     if (line.empty())
2735       return;
2736 
2737     // When using a non-interactive file handle (like when sourcing commands
2738     // from a file) we need to echo the command out so we don't just see the
2739     // command output and no command...
2740     if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2741       io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2742                                                line.c_str());
2743   }
2744 
2745   StartHandlingCommand();
2746 
2747   lldb_private::CommandReturnObject result;
2748   HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2749 
2750   // Now emit the command output text from the command we just executed
2751   if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2752     // Display any STDOUT/STDERR _prior_ to emitting the command result text
2753     GetProcessOutput();
2754 
2755     if (!result.GetImmediateOutputStream()) {
2756       llvm::StringRef output = result.GetOutputData();
2757       PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
2758     }
2759 
2760     // Now emit the command error text from the command we just executed
2761     if (!result.GetImmediateErrorStream()) {
2762       llvm::StringRef error = result.GetErrorData();
2763       PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
2764     }
2765   }
2766 
2767   FinishHandlingCommand();
2768 
2769   switch (result.GetStatus()) {
2770   case eReturnStatusInvalid:
2771   case eReturnStatusSuccessFinishNoResult:
2772   case eReturnStatusSuccessFinishResult:
2773   case eReturnStatusStarted:
2774     break;
2775 
2776   case eReturnStatusSuccessContinuingNoResult:
2777   case eReturnStatusSuccessContinuingResult:
2778     if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
2779       io_handler.SetIsDone(true);
2780     break;
2781 
2782   case eReturnStatusFailed:
2783     m_num_errors++;
2784     if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2785       io_handler.SetIsDone(true);
2786     break;
2787 
2788   case eReturnStatusQuit:
2789     m_quit_requested = true;
2790     io_handler.SetIsDone(true);
2791     break;
2792   }
2793 
2794   // Finally, if we're going to stop on crash, check that here:
2795   if (!m_quit_requested && result.GetDidChangeProcessState() &&
2796       io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) {
2797     bool should_stop = false;
2798     TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2799     if (target_sp) {
2800       ProcessSP process_sp(target_sp->GetProcessSP());
2801       if (process_sp) {
2802         for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2803           StopReason reason = thread_sp->GetStopReason();
2804           if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2805                reason == eStopReasonInstrumentation) &&
2806               !result.GetAbnormalStopWasExpected()) {
2807             should_stop = true;
2808             break;
2809           }
2810         }
2811       }
2812     }
2813     if (should_stop) {
2814       io_handler.SetIsDone(true);
2815       m_stopped_for_crash = true;
2816     }
2817   }
2818 }
2819 
2820 bool CommandInterpreter::IOHandlerInterrupt(IOHandler &io_handler) {
2821   ExecutionContext exe_ctx(GetExecutionContext());
2822   Process *process = exe_ctx.GetProcessPtr();
2823 
2824   if (InterruptCommand())
2825     return true;
2826 
2827   if (process) {
2828     StateType state = process->GetState();
2829     if (StateIsRunningState(state)) {
2830       process->Halt();
2831       return true; // Don't do any updating when we are running
2832     }
2833   }
2834 
2835   ScriptInterpreter *script_interpreter = GetScriptInterpreter(false);
2836   if (script_interpreter) {
2837     if (script_interpreter->Interrupt())
2838       return true;
2839   }
2840   return false;
2841 }
2842 
2843 void CommandInterpreter::GetLLDBCommandsFromIOHandler(
2844     const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2845     void *baton) {
2846   Debugger &debugger = GetDebugger();
2847   IOHandlerSP io_handler_sp(
2848       new IOHandlerEditline(debugger, IOHandler::Type::CommandList,
2849                             "lldb", // Name of input reader for history
2850                             llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2851                             llvm::StringRef(), // Continuation prompt
2852                             true,              // Get multiple lines
2853                             debugger.GetUseColor(),
2854                             0,          // Don't show line numbers
2855                             delegate)); // IOHandlerDelegate
2856 
2857   if (io_handler_sp) {
2858     io_handler_sp->SetUserData(baton);
2859     if (asynchronously)
2860       debugger.PushIOHandler(io_handler_sp);
2861     else
2862       debugger.RunIOHandler(io_handler_sp);
2863   }
2864 }
2865 
2866 void CommandInterpreter::GetPythonCommandsFromIOHandler(
2867     const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2868     void *baton) {
2869   Debugger &debugger = GetDebugger();
2870   IOHandlerSP io_handler_sp(
2871       new IOHandlerEditline(debugger, IOHandler::Type::PythonCode,
2872                             "lldb-python", // Name of input reader for history
2873                             llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2874                             llvm::StringRef(), // Continuation prompt
2875                             true,              // Get multiple lines
2876                             debugger.GetUseColor(),
2877                             0,          // Don't show line numbers
2878                             delegate)); // IOHandlerDelegate
2879 
2880   if (io_handler_sp) {
2881     io_handler_sp->SetUserData(baton);
2882     if (asynchronously)
2883       debugger.PushIOHandler(io_handler_sp);
2884     else
2885       debugger.RunIOHandler(io_handler_sp);
2886   }
2887 }
2888 
2889 bool CommandInterpreter::IsActive() {
2890   return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2891 }
2892 
2893 lldb::IOHandlerSP
2894 CommandInterpreter::GetIOHandler(bool force_create,
2895                                  CommandInterpreterRunOptions *options) {
2896   // Always re-create the IOHandlerEditline in case the input changed. The old
2897   // instance might have had a non-interactive input and now it does or vice
2898   // versa.
2899   if (force_create || !m_command_io_handler_sp) {
2900     // Always re-create the IOHandlerEditline in case the input changed. The
2901     // old instance might have had a non-interactive input and now it does or
2902     // vice versa.
2903     uint32_t flags = 0;
2904 
2905     if (options) {
2906       if (options->m_stop_on_continue == eLazyBoolYes)
2907         flags |= eHandleCommandFlagStopOnContinue;
2908       if (options->m_stop_on_error == eLazyBoolYes)
2909         flags |= eHandleCommandFlagStopOnError;
2910       if (options->m_stop_on_crash == eLazyBoolYes)
2911         flags |= eHandleCommandFlagStopOnCrash;
2912       if (options->m_echo_commands != eLazyBoolNo)
2913         flags |= eHandleCommandFlagEchoCommand;
2914       if (options->m_print_results != eLazyBoolNo)
2915         flags |= eHandleCommandFlagPrintResult;
2916     } else {
2917       flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
2918     }
2919 
2920     m_command_io_handler_sp.reset(new IOHandlerEditline(
2921         m_debugger, IOHandler::Type::CommandInterpreter,
2922         m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2923         m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
2924         llvm::StringRef(), // Continuation prompt
2925         false, // Don't enable multiple line input, just single line commands
2926         m_debugger.GetUseColor(),
2927         0, // Don't show line numbers
2928         *this));
2929   }
2930   return m_command_io_handler_sp;
2931 }
2932 
2933 void CommandInterpreter::RunCommandInterpreter(
2934     bool auto_handle_events, bool spawn_thread,
2935     CommandInterpreterRunOptions &options) {
2936   // Always re-create the command interpreter when we run it in case any file
2937   // handles have changed.
2938   bool force_create = true;
2939   m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2940   m_stopped_for_crash = false;
2941 
2942   if (auto_handle_events)
2943     m_debugger.StartEventHandlerThread();
2944 
2945   if (spawn_thread) {
2946     m_debugger.StartIOHandlerThread();
2947   } else {
2948     m_debugger.ExecuteIOHandlers();
2949 
2950     if (auto_handle_events)
2951       m_debugger.StopEventHandlerThread();
2952   }
2953 }
2954 
2955 CommandObject *
2956 CommandInterpreter::ResolveCommandImpl(std::string &command_line,
2957                                        CommandReturnObject &result) {
2958   std::string scratch_command(command_line); // working copy so we don't modify
2959                                              // command_line unless we succeed
2960   CommandObject *cmd_obj = nullptr;
2961   StreamString revised_command_line;
2962   bool wants_raw_input = false;
2963   size_t actual_cmd_name_len = 0;
2964   std::string next_word;
2965   StringList matches;
2966   bool done = false;
2967   while (!done) {
2968     char quote_char = '\0';
2969     std::string suffix;
2970     ExtractCommand(scratch_command, next_word, suffix, quote_char);
2971     if (cmd_obj == nullptr) {
2972       std::string full_name;
2973       bool is_alias = GetAliasFullName(next_word, full_name);
2974       cmd_obj = GetCommandObject(next_word, &matches);
2975       bool is_real_command =
2976           (is_alias == false) ||
2977           (cmd_obj != nullptr && cmd_obj->IsAlias() == false);
2978       if (!is_real_command) {
2979         matches.Clear();
2980         std::string alias_result;
2981         cmd_obj =
2982             BuildAliasResult(full_name, scratch_command, alias_result, result);
2983         revised_command_line.Printf("%s", alias_result.c_str());
2984         if (cmd_obj) {
2985           wants_raw_input = cmd_obj->WantsRawCommandString();
2986           actual_cmd_name_len = cmd_obj->GetCommandName().size();
2987         }
2988       } else {
2989         if (!cmd_obj)
2990           cmd_obj = GetCommandObject(next_word, &matches);
2991         if (cmd_obj) {
2992           llvm::StringRef cmd_name = cmd_obj->GetCommandName();
2993           actual_cmd_name_len += cmd_name.size();
2994           revised_command_line.Printf("%s", cmd_name.str().c_str());
2995           wants_raw_input = cmd_obj->WantsRawCommandString();
2996         } else {
2997           revised_command_line.Printf("%s", next_word.c_str());
2998         }
2999       }
3000     } else {
3001       if (cmd_obj->IsMultiwordObject()) {
3002         CommandObject *sub_cmd_obj =
3003             cmd_obj->GetSubcommandObject(next_word.c_str());
3004         if (sub_cmd_obj) {
3005           // The subcommand's name includes the parent command's name, so
3006           // restart rather than append to the revised_command_line.
3007           llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3008           actual_cmd_name_len = sub_cmd_name.size() + 1;
3009           revised_command_line.Clear();
3010           revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
3011           cmd_obj = sub_cmd_obj;
3012           wants_raw_input = cmd_obj->WantsRawCommandString();
3013         } else {
3014           if (quote_char)
3015             revised_command_line.Printf(" %c%s%s%c", quote_char,
3016                                         next_word.c_str(), suffix.c_str(),
3017                                         quote_char);
3018           else
3019             revised_command_line.Printf(" %s%s", next_word.c_str(),
3020                                         suffix.c_str());
3021           done = true;
3022         }
3023       } else {
3024         if (quote_char)
3025           revised_command_line.Printf(" %c%s%s%c", quote_char,
3026                                       next_word.c_str(), suffix.c_str(),
3027                                       quote_char);
3028         else
3029           revised_command_line.Printf(" %s%s", next_word.c_str(),
3030                                       suffix.c_str());
3031         done = true;
3032       }
3033     }
3034 
3035     if (cmd_obj == nullptr) {
3036       const size_t num_matches = matches.GetSize();
3037       if (matches.GetSize() > 1) {
3038         StreamString error_msg;
3039         error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3040                          next_word.c_str());
3041 
3042         for (uint32_t i = 0; i < num_matches; ++i) {
3043           error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3044         }
3045         result.AppendRawError(error_msg.GetString());
3046       } else {
3047         // We didn't have only one match, otherwise we wouldn't get here.
3048         lldbassert(num_matches == 0);
3049         result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3050                                      next_word.c_str());
3051       }
3052       result.SetStatus(eReturnStatusFailed);
3053       return nullptr;
3054     }
3055 
3056     if (cmd_obj->IsMultiwordObject()) {
3057       if (!suffix.empty()) {
3058         result.AppendErrorWithFormat(
3059             "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3060             "might be invalid).\n",
3061             cmd_obj->GetCommandName().str().c_str(),
3062             next_word.empty() ? "" : next_word.c_str(),
3063             next_word.empty() ? " -- " : " ", suffix.c_str());
3064         result.SetStatus(eReturnStatusFailed);
3065         return nullptr;
3066       }
3067     } else {
3068       // If we found a normal command, we are done
3069       done = true;
3070       if (!suffix.empty()) {
3071         switch (suffix[0]) {
3072         case '/':
3073           // GDB format suffixes
3074           {
3075             Options *command_options = cmd_obj->GetOptions();
3076             if (command_options &&
3077                 command_options->SupportsLongOption("gdb-format")) {
3078               std::string gdb_format_option("--gdb-format=");
3079               gdb_format_option += (suffix.c_str() + 1);
3080 
3081               std::string cmd = revised_command_line.GetString();
3082               size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3083               if (arg_terminator_idx != std::string::npos) {
3084                 // Insert the gdb format option before the "--" that terminates
3085                 // options
3086                 gdb_format_option.append(1, ' ');
3087                 cmd.insert(arg_terminator_idx, gdb_format_option);
3088                 revised_command_line.Clear();
3089                 revised_command_line.PutCString(cmd);
3090               } else
3091                 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3092 
3093               if (wants_raw_input &&
3094                   FindArgumentTerminator(cmd) == std::string::npos)
3095                 revised_command_line.PutCString(" --");
3096             } else {
3097               result.AppendErrorWithFormat(
3098                   "the '%s' command doesn't support the --gdb-format option\n",
3099                   cmd_obj->GetCommandName().str().c_str());
3100               result.SetStatus(eReturnStatusFailed);
3101               return nullptr;
3102             }
3103           }
3104           break;
3105 
3106         default:
3107           result.AppendErrorWithFormat(
3108               "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3109           result.SetStatus(eReturnStatusFailed);
3110           return nullptr;
3111         }
3112       }
3113     }
3114     if (scratch_command.empty())
3115       done = true;
3116   }
3117 
3118   if (!scratch_command.empty())
3119     revised_command_line.Printf(" %s", scratch_command.c_str());
3120 
3121   if (cmd_obj != NULL)
3122     command_line = revised_command_line.GetString();
3123 
3124   return cmd_obj;
3125 }
3126