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