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