1 //===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/lldb-python.h"
16 #include "CommandObjectScript.h"
17 #include "lldb/Interpreter/CommandObjectRegexCommand.h"
19 #include "../Commands/CommandObjectApropos.h"
20 #include "../Commands/CommandObjectArgs.h"
21 #include "../Commands/CommandObjectBreakpoint.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/CommandObjectLog.h"
28 #include "../Commands/CommandObjectMemory.h"
29 #include "../Commands/CommandObjectPlatform.h"
30 #include "../Commands/CommandObjectPlugin.h"
31 #include "../Commands/CommandObjectProcess.h"
32 #include "../Commands/CommandObjectQuit.h"
33 #include "../Commands/CommandObjectRegister.h"
34 #include "../Commands/CommandObjectSettings.h"
35 #include "../Commands/CommandObjectSource.h"
36 #include "../Commands/CommandObjectCommands.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"
45 #include "lldb/Core/Debugger.h"
46 #include "lldb/Core/Log.h"
47 #include "lldb/Core/State.h"
48 #include "lldb/Core/Stream.h"
49 #include "lldb/Core/StreamFile.h"
50 #include "lldb/Core/Timer.h"
52 #include "lldb/Host/Editline.h"
53 #include "lldb/Host/Host.h"
54 #include "lldb/Host/HostInfo.h"
56 #include "lldb/Interpreter/Args.h"
57 #include "lldb/Interpreter/CommandCompletions.h"
58 #include "lldb/Interpreter/CommandInterpreter.h"
59 #include "lldb/Interpreter/CommandReturnObject.h"
60 #include "lldb/Interpreter/Options.h"
61 #include "lldb/Interpreter/ScriptInterpreterNone.h"
62 #include "lldb/Interpreter/ScriptInterpreterPython.h"
65 #include "lldb/Target/Process.h"
66 #include "lldb/Target/Thread.h"
67 #include "lldb/Target/TargetList.h"
69 #include "lldb/Utility/CleanUp.h"
71 #include "llvm/ADT/SmallString.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/Support/Path.h"
76 using namespace lldb_private;
79 static PropertyDefinition
82 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, regular expression alias commands will show the expanded command that will be executed. This can be used to debug new regular expression alias commands." },
83 { "prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will prompt you before quitting if there are any live processes being debugged. If false, LLDB will quit without asking in any case." },
84 { "stop-command-source-on-error", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will stop running a 'command source' script upon encountering an error." },
85 { nullptr , OptionValue::eTypeInvalid, true, 0 , nullptr, nullptr, nullptr }
90 ePropertyExpandRegexAliases = 0,
91 ePropertyPromptOnQuit = 1,
92 ePropertyStopCmdSourceOnError = 2
96 CommandInterpreter::GetStaticBroadcasterClass ()
98 static ConstString class_name ("lldb.commandInterpreter");
102 CommandInterpreter::CommandInterpreter
105 ScriptLanguage script_language,
106 bool synchronous_execution
108 Broadcaster (&debugger, "lldb.command-interpreter"),
109 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
110 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand),
111 m_debugger (debugger),
112 m_synchronous_execution (synchronous_execution),
113 m_skip_lldbinit_files (false),
114 m_skip_app_init_files (false),
115 m_script_interpreter_ap (),
116 m_command_io_handler_sp (),
117 m_comment_char ('#'),
118 m_batch_command_mode (false),
119 m_truncation_warning(eNoTruncation),
120 m_command_source_depth (0)
122 debugger.SetScriptLanguage (script_language);
123 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
124 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
125 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
126 CheckInWithManager ();
127 m_collection_sp->Initialize (g_properties);
131 CommandInterpreter::GetExpandRegexAliases () const
133 const uint32_t idx = ePropertyExpandRegexAliases;
134 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
138 CommandInterpreter::GetPromptOnQuit () const
140 const uint32_t idx = ePropertyPromptOnQuit;
141 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
145 CommandInterpreter::GetStopCmdSourceOnError () const
147 const uint32_t idx = ePropertyStopCmdSourceOnError;
148 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
152 CommandInterpreter::Initialize ()
154 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
156 CommandReturnObject result;
158 LoadCommandDictionary ();
160 // Set up some initial aliases.
161 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
164 AddAlias ("q", cmd_obj_sp);
165 AddAlias ("exit", cmd_obj_sp);
168 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
171 AddAlias ("attach", cmd_obj_sp);
174 cmd_obj_sp = GetCommandSPExact ("process detach",false);
177 AddAlias ("detach", cmd_obj_sp);
180 cmd_obj_sp = GetCommandSPExact ("process continue", false);
183 AddAlias ("c", cmd_obj_sp);
184 AddAlias ("continue", cmd_obj_sp);
187 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
189 AddAlias ("b", cmd_obj_sp);
191 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
193 AddAlias ("tbreak", cmd_obj_sp);
195 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
198 AddAlias ("stepi", cmd_obj_sp);
199 AddAlias ("si", cmd_obj_sp);
202 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
205 AddAlias ("nexti", cmd_obj_sp);
206 AddAlias ("ni", cmd_obj_sp);
209 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
212 AddAlias ("s", cmd_obj_sp);
213 AddAlias ("step", cmd_obj_sp);
216 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
219 AddAlias ("n", cmd_obj_sp);
220 AddAlias ("next", cmd_obj_sp);
223 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
226 AddAlias ("finish", cmd_obj_sp);
229 cmd_obj_sp = GetCommandSPExact ("frame select", false);
232 AddAlias ("f", cmd_obj_sp);
235 cmd_obj_sp = GetCommandSPExact ("thread select", false);
238 AddAlias ("t", cmd_obj_sp);
241 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
244 AddAlias ("j", cmd_obj_sp);
245 AddAlias ("jump", cmd_obj_sp);
248 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
251 AddAlias ("l", cmd_obj_sp);
252 AddAlias ("list", cmd_obj_sp);
255 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
258 AddAlias ("env", cmd_obj_sp);
261 cmd_obj_sp = GetCommandSPExact ("memory read", false);
263 AddAlias ("x", cmd_obj_sp);
265 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
267 AddAlias ("up", cmd_obj_sp);
269 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
271 AddAlias ("down", cmd_obj_sp);
273 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
275 AddAlias ("display", cmd_obj_sp);
277 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
279 AddAlias ("dis", cmd_obj_sp);
281 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
283 AddAlias ("di", cmd_obj_sp);
287 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
289 AddAlias ("undisplay", cmd_obj_sp);
291 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
293 AddAlias ("bt", cmd_obj_sp);
295 cmd_obj_sp = GetCommandSPExact ("target create", false);
297 AddAlias ("file", cmd_obj_sp);
299 cmd_obj_sp = GetCommandSPExact ("target modules", false);
301 AddAlias ("image", cmd_obj_sp);
304 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
306 cmd_obj_sp = GetCommandSPExact ("expression", false);
309 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
310 AddAlias ("p", cmd_obj_sp);
311 AddAlias ("print", cmd_obj_sp);
312 AddAlias ("call", cmd_obj_sp);
313 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
314 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
315 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
317 alias_arguments_vector_sp.reset (new OptionArgVector);
318 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
319 AddAlias ("po", cmd_obj_sp);
320 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
323 cmd_obj_sp = GetCommandSPExact ("process kill", false);
326 AddAlias ("kill", cmd_obj_sp);
329 cmd_obj_sp = GetCommandSPExact ("process launch", false);
332 alias_arguments_vector_sp.reset (new OptionArgVector);
333 #if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
334 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
336 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=" LLDB_DEFAULT_SHELL " --", alias_arguments_vector_sp);
338 AddAlias ("r", cmd_obj_sp);
339 AddAlias ("run", cmd_obj_sp);
340 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
341 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
344 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
347 AddAlias ("add-dsym", cmd_obj_sp);
350 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
353 alias_arguments_vector_sp.reset (new OptionArgVector);
354 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
355 AddAlias ("rbreak", cmd_obj_sp);
356 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
361 CommandInterpreter::Clear()
363 m_command_io_handler_sp.reset();
365 if (m_script_interpreter_ap)
366 m_script_interpreter_ap->Clear();
370 CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
372 // This function has not yet been implemented.
374 // Look for any embedded script command
376 // get interpreter object from the command dictionary,
377 // call execute_one_command on it,
378 // get the results as a string,
379 // substitute that string for current stuff.
386 CommandInterpreter::LoadCommandDictionary ()
388 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
390 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
392 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
393 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
394 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
395 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
396 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
397 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
398 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
399 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
400 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
401 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
402 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
403 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
404 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
405 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
406 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
407 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
408 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
409 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
410 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
411 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
412 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
413 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
414 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
416 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
417 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
418 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
419 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
420 {"^(-.*)$", "breakpoint set %1"},
421 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
422 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
423 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}};
425 size_t num_regexes = llvm::array_lengthof(break_regexes);
427 std::unique_ptr<CommandObjectRegexCommand>
428 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
430 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
431 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
433 CommandCompletions::eSymbolCompletion |
434 CommandCompletions::eSourceFileCompletion));
436 if (break_regex_cmd_ap.get())
439 for (size_t i = 0; i < num_regexes; i++)
441 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
445 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
449 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
450 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
454 std::unique_ptr<CommandObjectRegexCommand>
455 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
457 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
458 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
460 CommandCompletions::eSymbolCompletion |
461 CommandCompletions::eSourceFileCompletion));
463 if (tbreak_regex_cmd_ap.get())
466 for (size_t i = 0; i < num_regexes; i++)
468 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
470 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
471 assert (num_printed < 1024);
472 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
476 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
480 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
481 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
485 std::unique_ptr<CommandObjectRegexCommand>
486 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
488 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
489 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
491 if (attach_regex_cmd_ap.get())
493 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
494 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
495 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
496 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
498 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
499 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
503 std::unique_ptr<CommandObjectRegexCommand>
504 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
506 "Go down \"n\" frames in the stack (1 frame by default).",
507 "_regexp-down [n]", 2));
508 if (down_regex_cmd_ap.get())
510 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
511 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
513 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
514 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
518 std::unique_ptr<CommandObjectRegexCommand>
519 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
521 "Go up \"n\" frames in the stack (1 frame by default).",
522 "_regexp-up [n]", 2));
523 if (up_regex_cmd_ap.get())
525 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
526 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
528 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
529 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
533 std::unique_ptr<CommandObjectRegexCommand>
534 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
536 "Add an expression evaluation stop-hook.",
537 "_regexp-display expression", 2));
538 if (display_regex_cmd_ap.get())
540 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
542 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
543 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
547 std::unique_ptr<CommandObjectRegexCommand>
548 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
550 "Remove an expression evaluation stop-hook.",
551 "_regexp-undisplay stop-hook-number", 2));
552 if (undisplay_regex_cmd_ap.get())
554 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
556 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
557 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
561 std::unique_ptr<CommandObjectRegexCommand>
562 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
564 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
565 "gdb-remote [<hostname>:]<portnum>", 2));
566 if (connect_gdb_remote_cmd_ap.get())
568 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
569 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
571 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
572 m_command_dict[command_sp->GetCommandName ()] = command_sp;
576 std::unique_ptr<CommandObjectRegexCommand>
577 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
579 "Connect to a remote KDP server. udp port 41139 is the default port number.",
580 "kdp-remote <hostname>[:<portnum>]", 2));
581 if (connect_kdp_remote_cmd_ap.get())
583 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
584 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
586 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
587 m_command_dict[command_sp->GetCommandName ()] = command_sp;
591 std::unique_ptr<CommandObjectRegexCommand>
592 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
594 "Show a backtrace. An optional argument is accepted; if that argument is a number, it specifies the number of frames to display. If that argument is 'all', full backtraces of all threads are displayed.",
595 "bt [<digit>|all]", 2));
596 if (bt_regex_cmd_ap.get())
598 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
599 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
600 // so now "bt 3" is the preferred form, in line with gdb.
601 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
602 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
603 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
604 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
606 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
607 m_command_dict[command_sp->GetCommandName ()] = command_sp;
611 std::unique_ptr<CommandObjectRegexCommand>
612 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
614 "Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the appropriate 'source list' commands.",
615 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
617 CommandCompletions::eSourceFileCompletion));
618 if (list_regex_cmd_ap.get())
620 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
621 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
622 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
623 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
624 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
625 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
626 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
628 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
629 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
633 std::unique_ptr<CommandObjectRegexCommand>
634 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
636 "Implements a shortcut to viewing and setting environment variables.",
637 "_regexp-env\n_regexp-env FOO=BAR", 2));
638 if (env_regex_cmd_ap.get())
640 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
641 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
643 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
644 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
648 std::unique_ptr<CommandObjectRegexCommand>
649 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
651 "Sets the program counter to a new address.",
652 "_regexp-jump [<line>]\n"
653 "_regexp-jump [<+-lineoffset>]\n"
654 "_regexp-jump [<file>:<line>]\n"
655 "_regexp-jump [*<addr>]\n", 2));
656 if (jump_regex_cmd_ap.get())
658 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
659 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
660 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
661 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
663 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
664 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
671 CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
674 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
678 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
681 return matches.GetSize();
685 CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
687 CommandObject::CommandMap::iterator pos;
688 CommandObjectSP command_sp;
690 std::string cmd(cmd_cstr);
694 pos = m_command_dict.find(cmd);
695 if (pos != m_command_dict.end())
696 command_sp = pos->second;
699 if (include_aliases && HasAliases())
701 pos = m_alias_dict.find(cmd);
702 if (pos != m_alias_dict.end())
703 command_sp = pos->second;
706 if (HasUserCommands())
708 pos = m_user_dict.find(cmd);
709 if (pos != m_user_dict.end())
710 command_sp = pos->second;
713 if (!exact && !command_sp)
715 // We will only get into here if we didn't find any exact matches.
717 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
719 StringList local_matches;
720 if (matches == nullptr)
721 matches = &local_matches;
723 unsigned int num_cmd_matches = 0;
724 unsigned int num_alias_matches = 0;
725 unsigned int num_user_matches = 0;
727 // Look through the command dictionaries one by one, and if we get only one match from any of
728 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
732 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
735 if (num_cmd_matches == 1)
737 cmd.assign(matches->GetStringAtIndex(0));
738 pos = m_command_dict.find(cmd);
739 if (pos != m_command_dict.end())
740 real_match_sp = pos->second;
743 if (include_aliases && HasAliases())
745 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
749 if (num_alias_matches == 1)
751 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
752 pos = m_alias_dict.find(cmd);
753 if (pos != m_alias_dict.end())
754 alias_match_sp = pos->second;
757 if (HasUserCommands())
759 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
762 if (num_user_matches == 1)
764 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
766 pos = m_user_dict.find (cmd);
767 if (pos != m_user_dict.end())
768 user_match_sp = pos->second;
771 // If we got exactly one match, return that, otherwise return the match list.
773 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
776 return real_match_sp;
777 else if (num_alias_matches)
778 return alias_match_sp;
780 return user_match_sp;
783 else if (matches && command_sp)
785 matches->AppendString (cmd_cstr);
793 CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
797 std::string name_sstr(name);
798 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
799 if (found && !can_replace)
801 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
803 m_command_dict[name_sstr] = cmd_sp;
810 CommandInterpreter::AddUserCommand (std::string name,
811 const lldb::CommandObjectSP &cmd_sp,
817 const char* name_cstr = name.c_str();
819 // do not allow replacement of internal commands
820 if (CommandExists(name_cstr))
822 if (can_replace == false)
824 if (m_command_dict[name]->IsRemovable() == false)
828 if (UserCommandExists(name_cstr))
830 if (can_replace == false)
832 if (m_user_dict[name]->IsRemovable() == false)
836 m_user_dict[name] = cmd_sp;
843 CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
845 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
846 CommandObjectSP ret_val; // Possibly empty return value.
848 if (cmd_cstr == nullptr)
851 if (cmd_words.GetArgumentCount() == 1)
852 return GetCommandSP(cmd_cstr, include_aliases, true, nullptr);
855 // We have a multi-word command (seemingly), so we need to do more work.
856 // First, get the cmd_obj_sp for the first word in the command.
857 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr);
858 if (cmd_obj_sp.get() != nullptr)
860 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
861 // command name), and find the appropriate sub-command SP for each command word....
862 size_t end = cmd_words.GetArgumentCount();
863 for (size_t j= 1; j < end; ++j)
865 if (cmd_obj_sp->IsMultiwordObject())
867 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
868 if (cmd_obj_sp.get() == nullptr)
869 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
873 // We have more words in the command name, but we don't have a multiword object. Fail and return
877 // We successfully looped through all the command words and got valid command objects for them. Assign the
878 // last object retrieved to 'ret_val'.
879 ret_val = cmd_obj_sp;
886 CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
888 return GetCommandSPExact (cmd_cstr, include_aliases).get();
892 CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
894 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
896 // If we didn't find an exact match to the command string in the commands, look in
902 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
907 // If there wasn't an exact match then look for an inexact one in just the commands
908 command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get();
910 // Finally, if there wasn't an inexact match among the commands, look for an inexact
911 // match in both the commands and aliases.
916 matches->AppendString(command_obj->GetCommandName());
920 return GetCommandSP(cmd_cstr, true, false, matches).get();
924 CommandInterpreter::CommandExists (const char *cmd)
926 return m_command_dict.find(cmd) != m_command_dict.end();
930 CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
931 const char *options_args,
932 OptionArgVectorSP &option_arg_vector_sp)
935 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
937 if (!options_args || (strlen (options_args) < 1))
940 std::string options_string (options_args);
941 Args args (options_args);
942 CommandReturnObject result;
943 // Check to see if the command being aliased can take any command options.
944 Options *options = cmd_obj_sp->GetOptions ();
947 // See if any options were specified as part of the alias; if so, handle them appropriately.
948 options->NotifyOptionParsingStarting ();
949 args.Unshift ("dummy_arg");
950 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
952 if (result.Succeeded())
953 options->VerifyPartialOptions (result);
954 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
956 result.AppendError ("Unable to create requested alias.\n");
961 if (!options_string.empty())
963 if (cmd_obj_sp->WantsRawCommandString ())
964 option_arg_vector->push_back (OptionArgPair ("<argument>",
969 const size_t argc = args.GetArgumentCount();
970 for (size_t i = 0; i < argc; ++i)
971 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
972 option_arg_vector->push_back
973 (OptionArgPair ("<argument>",
975 std::string (args.GetArgumentAtIndex (i)))));
983 CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
985 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
988 full_name.assign(cmd);
994 size_t num_alias_matches;
995 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
996 if (num_alias_matches == 1)
998 // Make sure this isn't shadowing a command in the regular command space:
999 StringList regular_matches;
1000 const bool include_aliases = false;
1001 const bool exact = false;
1002 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, ®ular_matches));
1003 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1007 full_name.assign (matches.GetStringAtIndex(0));
1017 CommandInterpreter::AliasExists (const char *cmd)
1019 return m_alias_dict.find(cmd) != m_alias_dict.end();
1023 CommandInterpreter::UserCommandExists (const char *cmd)
1025 return m_user_dict.find(cmd) != m_user_dict.end();
1029 CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1031 command_obj_sp->SetIsAlias (true);
1032 m_alias_dict[alias_name] = command_obj_sp;
1036 CommandInterpreter::RemoveAlias (const char *alias_name)
1038 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1039 if (pos != m_alias_dict.end())
1041 m_alias_dict.erase(pos);
1047 CommandInterpreter::RemoveUser (const char *alias_name)
1049 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1050 if (pos != m_user_dict.end())
1052 m_user_dict.erase(pos);
1059 CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1061 help_string.Printf ("'%s", command_name);
1062 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1064 if (option_arg_vector_sp)
1066 OptionArgVector *options = option_arg_vector_sp.get();
1067 for (size_t i = 0; i < options->size(); ++i)
1069 OptionArgPair cur_option = (*options)[i];
1070 std::string opt = cur_option.first;
1071 OptionArgValue value_pair = cur_option.second;
1072 std::string value = value_pair.second;
1073 if (opt.compare("<argument>") == 0)
1075 help_string.Printf (" %s", value.c_str());
1079 help_string.Printf (" %s", opt.c_str());
1080 if ((value.compare ("<no-argument>") != 0)
1081 && (value.compare ("<need-argument") != 0))
1083 help_string.Printf (" %s", value.c_str());
1089 help_string.Printf ("'");
1093 CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1095 CommandObject::CommandMap::const_iterator pos;
1096 CommandObject::CommandMap::const_iterator end = dict.end();
1099 for (pos = dict.begin(); pos != end; ++pos)
1101 size_t len = pos->first.size();
1109 CommandInterpreter::GetHelp (CommandReturnObject &result,
1112 CommandObject::CommandMap::const_iterator pos;
1113 size_t max_len = FindLongestCommandWord (m_command_dict);
1115 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
1118 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
1119 result.AppendMessage("");
1121 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1123 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1126 result.AppendMessage("");
1130 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
1132 result.AppendMessage("The following is a list of your current command abbreviations "
1133 "(see 'help command alias' for more info):");
1134 result.AppendMessage("");
1135 max_len = FindLongestCommandWord (m_alias_dict);
1137 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1140 StreamString translation_and_help;
1141 std::string entry_name = pos->first;
1142 std::string second_entry = pos->second.get()->GetCommandName();
1143 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1145 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1146 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1147 translation_and_help.GetData(), max_len);
1149 result.AppendMessage("");
1152 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
1154 result.AppendMessage ("The following is a list of your current user-defined commands:");
1155 result.AppendMessage("");
1156 max_len = FindLongestCommandWord (m_user_dict);
1157 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1159 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1162 result.AppendMessage("");
1165 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1169 CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
1171 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1172 // eventually be invoked by the given command line.
1174 CommandObject *cmd_obj = nullptr;
1175 std::string white_space (" \t\v");
1176 size_t start = command_string.find_first_not_of (white_space);
1181 if (start != std::string::npos)
1183 // Get the next word from command_string.
1184 end = command_string.find_first_of (white_space, start);
1185 if (end == std::string::npos)
1186 end = command_string.size();
1187 std::string cmd_word = command_string.substr (start, end - start);
1189 if (cmd_obj == nullptr)
1190 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1191 // command or alias.
1192 cmd_obj = GetCommandObject (cmd_word.c_str());
1193 else if (cmd_obj->IsMultiwordObject ())
1195 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
1196 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
1198 cmd_obj = sub_cmd_obj;
1199 else // cmd_word was not a valid sub-command word, so we are donee
1203 // We have a cmd_obj and it is not a multi-word object, so we are done.
1206 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1207 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1210 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1213 start = command_string.find_first_not_of (white_space, end);
1216 // Unable to find any more words.
1220 if (end == command_string.size())
1221 command_string.clear();
1223 command_string = command_string.substr(end);
1228 static const char *k_white_space = " \t\v";
1229 static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1231 StripLeadingSpaces (std::string &s)
1235 size_t pos = s.find_first_not_of (k_white_space);
1236 if (pos == std::string::npos)
1245 FindArgumentTerminator (const std::string &s)
1247 const size_t s_len = s.size();
1249 while (offset < s_len)
1251 size_t pos = s.find ("--", offset);
1252 if (pos == std::string::npos)
1256 if (isspace(s[pos-1]))
1258 // Check if the string ends "\s--" (where \s is a space character)
1259 // or if we have "\s--\s".
1260 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1268 return std::string::npos;
1272 ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char "e_char)
1276 StripLeadingSpaces (command_string);
1278 bool result = false;
1281 if (!command_string.empty())
1283 const char first_char = command_string[0];
1284 if (first_char == '\'' || first_char == '"')
1286 quote_char = first_char;
1287 const size_t end_quote_pos = command_string.find (quote_char, 1);
1288 if (end_quote_pos == std::string::npos)
1290 command.swap (command_string);
1291 command_string.erase ();
1295 command.assign (command_string, 1, end_quote_pos - 1);
1296 if (end_quote_pos + 1 < command_string.size())
1297 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1299 command_string.erase ();
1304 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1305 if (first_space_pos == std::string::npos)
1307 command.swap (command_string);
1308 command_string.erase();
1312 command.assign (command_string, 0, first_space_pos);
1313 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
1320 if (!command.empty())
1322 // actual commands can't start with '-' or '_'
1323 if (command[0] != '-' && command[0] != '_')
1325 size_t pos = command.find_first_not_of(k_valid_command_chars);
1326 if (pos > 0 && pos != std::string::npos)
1328 suffix.assign (command.begin() + pos, command.end());
1329 command.erase (pos);
1338 CommandInterpreter::BuildAliasResult (const char *alias_name,
1339 std::string &raw_input_string,
1340 std::string &alias_result,
1341 CommandReturnObject &result)
1343 CommandObject *alias_cmd_obj = nullptr;
1344 Args cmd_args (raw_input_string.c_str());
1345 alias_cmd_obj = GetCommandObject (alias_name);
1346 StreamString result_str;
1350 std::string alias_name_str = alias_name;
1351 if ((cmd_args.GetArgumentCount() == 0)
1352 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1353 cmd_args.Unshift (alias_name);
1355 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1356 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1358 if (option_arg_vector_sp.get())
1360 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1362 for (size_t i = 0; i < option_arg_vector->size(); ++i)
1364 OptionArgPair option_pair = (*option_arg_vector)[i];
1365 OptionArgValue value_pair = option_pair.second;
1366 int value_type = value_pair.first;
1367 std::string option = option_pair.first;
1368 std::string value = value_pair.second;
1369 if (option.compare ("<argument>") == 0)
1370 result_str.Printf (" %s", value.c_str());
1373 result_str.Printf (" %s", option.c_str());
1374 if (value_type != OptionParser::eOptionalArgument)
1375 result_str.Printf (" ");
1376 if (value.compare ("<OptionParser::eNoArgument>") != 0)
1378 int index = GetOptionArgumentPosition (value.c_str());
1380 result_str.Printf ("%s", value.c_str());
1381 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
1384 result.AppendErrorWithFormat
1385 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1387 result.SetStatus (eReturnStatusFailed);
1388 return alias_cmd_obj;
1392 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1393 if (strpos != std::string::npos)
1394 raw_input_string = raw_input_string.erase (strpos,
1395 strlen (cmd_args.GetArgumentAtIndex (index)));
1396 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1403 alias_result = result_str.GetData();
1405 return alias_cmd_obj;
1409 CommandInterpreter::PreprocessCommand (std::string &command)
1411 // The command preprocessor needs to do things to the command
1412 // line before any parsing of arguments or anything else is done.
1413 // The only current stuff that gets proprocessed is anyting enclosed
1414 // in backtick ('`') characters is evaluated as an expression and
1415 // the result of the expression must be a scalar that can be substituted
1416 // into the command. An example would be:
1417 // (lldb) memory read `$rsp + 20`
1418 Error error; // Error for any expressions that might not evaluate
1419 size_t start_backtick;
1421 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1423 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1425 // The backtick was preceeded by a '\' character, remove the slash
1426 // and don't treat the backtick as the start of an expression
1427 command.erase(start_backtick-1, 1);
1428 // No need to add one to start_backtick since we just deleted a char
1429 pos = start_backtick;
1433 const size_t expr_content_start = start_backtick + 1;
1434 const size_t end_backtick = command.find ('`', expr_content_start);
1435 if (end_backtick == std::string::npos)
1437 else if (end_backtick == expr_content_start)
1439 // Empty expression (two backticks in a row)
1440 command.erase (start_backtick, 2);
1444 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1446 ExecutionContext exe_ctx(GetExecutionContext());
1447 Target *target = exe_ctx.GetTargetPtr();
1448 // Get a dummy target to allow for calculator mode while processing backticks.
1449 // This also helps break the infinite loop caused when target is null.
1451 target = Host::GetDummyTarget(GetDebugger()).get();
1454 ValueObjectSP expr_result_valobj_sp;
1456 EvaluateExpressionOptions options;
1457 options.SetCoerceToId(false);
1458 options.SetUnwindOnError(true);
1459 options.SetIgnoreBreakpoints(true);
1460 options.SetKeepInMemory(false);
1461 options.SetTryAllThreads(true);
1462 options.SetTimeoutUsec(0);
1464 ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1465 exe_ctx.GetFramePtr(),
1466 expr_result_valobj_sp,
1469 if (expr_result == eExpressionCompleted)
1472 if (expr_result_valobj_sp->ResolveValue (scalar))
1474 command.erase (start_backtick, end_backtick - start_backtick + 1);
1475 StreamString value_strm;
1476 const bool show_type = false;
1477 scalar.GetValue (&value_strm, show_type);
1478 size_t value_string_size = value_strm.GetSize();
1479 if (value_string_size)
1481 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1482 pos = start_backtick + value_string_size;
1487 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1492 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1497 if (expr_result_valobj_sp)
1498 error = expr_result_valobj_sp->GetError();
1499 if (error.Success())
1502 switch (expr_result)
1504 case eExpressionSetupError:
1505 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1507 case eExpressionParseError:
1508 error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str());
1510 case eExpressionResultUnavailable:
1511 error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str());
1512 case eExpressionCompleted:
1514 case eExpressionDiscarded:
1515 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1517 case eExpressionInterrupted:
1518 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1520 case eExpressionHitBreakpoint:
1521 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1523 case eExpressionTimedOut:
1524 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1526 case eExpressionStoppedForDebug:
1527 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1543 CommandInterpreter::HandleCommand (const char *command_line,
1544 LazyBool lazy_add_to_history,
1545 CommandReturnObject &result,
1546 ExecutionContext *override_context,
1547 bool repeat_on_empty_command,
1548 bool no_context_switching)
1553 CommandObject *cmd_obj = nullptr;
1554 bool wants_raw_input = false;
1555 std::string command_string (command_line);
1556 std::string original_command_string (command_line);
1558 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
1559 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1561 // Make a scoped cleanup object that will clear the crash description string
1562 // on exit of this function.
1563 lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription);
1566 log->Printf ("Processing command: %s", command_line);
1568 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1570 if (!no_context_switching)
1571 UpdateExecutionContext (override_context);
1573 bool add_to_history;
1574 if (lazy_add_to_history == eLazyBoolCalculate)
1575 add_to_history = (m_command_source_depth == 0);
1577 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1579 bool empty_command = false;
1580 bool comment_command = false;
1581 if (command_string.empty())
1582 empty_command = true;
1585 const char *k_space_characters = "\t\n\v\f\r ";
1587 size_t non_space = command_string.find_first_not_of (k_space_characters);
1588 // Check for empty line or comment line (lines whose first
1589 // non-space character is the comment character for this interpreter)
1590 if (non_space == std::string::npos)
1591 empty_command = true;
1592 else if (command_string[non_space] == m_comment_char)
1593 comment_command = true;
1594 else if (command_string[non_space] == CommandHistory::g_repeat_char)
1596 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
1597 if (history_string == nullptr)
1599 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1600 result.SetStatus(eReturnStatusFailed);
1603 add_to_history = false;
1604 command_string = history_string;
1605 original_command_string = history_string;
1611 if (repeat_on_empty_command)
1613 if (m_command_history.IsEmpty())
1615 result.AppendError ("empty command");
1616 result.SetStatus(eReturnStatusFailed);
1621 command_line = m_repeat_command.c_str();
1622 command_string = command_line;
1623 original_command_string = command_line;
1624 if (m_repeat_command.empty())
1626 result.AppendErrorWithFormat("No auto repeat.\n");
1627 result.SetStatus (eReturnStatusFailed);
1631 add_to_history = false;
1635 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1639 else if (comment_command)
1641 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1646 Error error (PreprocessCommand (command_string));
1650 result.AppendError (error.AsCString());
1651 result.SetStatus(eReturnStatusFailed);
1656 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1657 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1658 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1659 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1660 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
1661 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
1662 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
1664 StreamString revised_command_line;
1665 size_t actual_cmd_name_len = 0;
1666 std::string next_word;
1670 char quote_char = '\0';
1672 ExtractCommand (command_string, next_word, suffix, quote_char);
1673 if (cmd_obj == nullptr)
1675 std::string full_name;
1676 if (GetAliasFullName(next_word.c_str(), full_name))
1678 std::string alias_result;
1679 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
1680 revised_command_line.Printf ("%s", alias_result.c_str());
1683 wants_raw_input = cmd_obj->WantsRawCommandString ();
1684 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1689 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
1692 actual_cmd_name_len += next_word.length();
1693 revised_command_line.Printf ("%s", next_word.c_str());
1694 wants_raw_input = cmd_obj->WantsRawCommandString ();
1698 revised_command_line.Printf ("%s", next_word.c_str());
1704 if (cmd_obj->IsMultiwordObject ())
1706 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
1709 actual_cmd_name_len += next_word.length() + 1;
1710 revised_command_line.Printf (" %s", next_word.c_str());
1711 cmd_obj = sub_cmd_obj;
1712 wants_raw_input = cmd_obj->WantsRawCommandString ();
1717 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1719 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1726 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1728 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1733 if (cmd_obj == nullptr)
1735 const size_t num_matches = matches.GetSize();
1736 if (matches.GetSize() > 1) {
1737 StreamString error_msg;
1738 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
1740 for (uint32_t i = 0; i < num_matches; ++i) {
1741 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
1743 result.AppendRawError (error_msg.GetString().c_str());
1745 // We didn't have only one match, otherwise we wouldn't get here.
1746 assert(num_matches == 0);
1747 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1749 result.SetStatus (eReturnStatusFailed);
1753 if (cmd_obj->IsMultiwordObject ())
1755 if (!suffix.empty())
1758 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1759 cmd_obj->GetCommandName(),
1760 next_word.empty() ? "" : next_word.c_str(),
1761 next_word.empty() ? " -- " : " ",
1763 result.SetStatus (eReturnStatusFailed);
1769 // If we found a normal command, we are done
1771 if (!suffix.empty())
1776 // GDB format suffixes
1778 Options *command_options = cmd_obj->GetOptions();
1779 if (command_options && command_options->SupportsLongOption("gdb-format"))
1781 std::string gdb_format_option ("--gdb-format=");
1782 gdb_format_option += (suffix.c_str() + 1);
1784 bool inserted = false;
1785 std::string &cmd = revised_command_line.GetString();
1786 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1787 if (arg_terminator_idx != std::string::npos)
1789 // Insert the gdb format option before the "--" that terminates options
1790 gdb_format_option.append(1,' ');
1791 cmd.insert(arg_terminator_idx, gdb_format_option);
1796 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1798 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1799 revised_command_line.PutCString (" --");
1803 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1804 cmd_obj->GetCommandName());
1805 result.SetStatus (eReturnStatusFailed);
1812 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1814 result.SetStatus (eReturnStatusFailed);
1820 if (command_string.length() == 0)
1825 if (!command_string.empty())
1826 revised_command_line.Printf (" %s", command_string.c_str());
1829 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1830 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1831 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1832 // wants_raw_input specifies whether the Execute method expects raw input or not.
1837 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1838 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1839 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1843 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1844 // CommandObject, with the appropriate arguments.
1846 if (cmd_obj != nullptr)
1850 Args command_args (revised_command_line.GetData());
1851 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1852 if (repeat_command != nullptr)
1853 m_repeat_command.assign(repeat_command);
1855 m_repeat_command.assign(original_command_string.c_str());
1857 m_command_history.AppendString (original_command_string);
1860 command_string = revised_command_line.GetData();
1861 std::string command_name (cmd_obj->GetCommandName());
1862 std::string remainder;
1863 if (actual_cmd_name_len < command_string.length())
1864 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1865 // than cmd_obj->GetCommandName(), because name completion
1866 // allows users to enter short versions of the names,
1867 // e.g. 'br s' for 'breakpoint set'.
1869 // Remove any initial spaces
1870 std::string white_space (" \t\v");
1871 size_t pos = remainder.find_first_not_of (white_space);
1872 if (pos != 0 && pos != std::string::npos)
1873 remainder.erase(0, pos);
1876 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
1878 cmd_obj->Execute (remainder.c_str(), result);
1882 // We didn't find the first command object, so complete the first argument.
1883 Args command_args (revised_command_line.GetData());
1886 int cursor_index = 0;
1887 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1889 num_matches = HandleCompletionMatches (command_args,
1891 cursor_char_position,
1897 if (num_matches > 0)
1899 std::string error_msg;
1900 error_msg.assign ("ambiguous command '");
1901 error_msg.append(command_args.GetArgumentAtIndex(0));
1902 error_msg.append ("'.");
1904 error_msg.append (" Possible completions:");
1905 for (int i = 0; i < num_matches; i++)
1907 error_msg.append ("\n\t");
1908 error_msg.append (matches.GetStringAtIndex (i));
1910 error_msg.append ("\n");
1911 result.AppendRawError (error_msg.c_str());
1914 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1916 result.SetStatus (eReturnStatusFailed);
1920 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1922 return result.Succeeded();
1926 CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1928 int &cursor_char_position,
1929 int match_start_point,
1930 int max_return_elements,
1931 bool &word_complete,
1932 StringList &matches)
1934 int num_command_matches = 0;
1935 bool look_for_subcommand = false;
1937 // For any of the command completions a unique match will be a complete word.
1938 word_complete = true;
1940 if (cursor_index == -1)
1942 // We got nothing on the command line, so return the list of commands
1943 bool include_aliases = true;
1944 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1946 else if (cursor_index == 0)
1948 // The cursor is in the first argument, so just do a lookup in the dictionary.
1949 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
1950 num_command_matches = matches.GetSize();
1952 if (num_command_matches == 1
1953 && cmd_obj && cmd_obj->IsMultiwordObject()
1954 && matches.GetStringAtIndex(0) != nullptr
1955 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1957 if (parsed_line.GetArgumentCount() == 1)
1959 word_complete = true;
1963 look_for_subcommand = true;
1964 num_command_matches = 0;
1965 matches.DeleteStringAtIndex(0);
1966 parsed_line.AppendArgument ("");
1968 cursor_char_position = 0;
1973 if (cursor_index > 0 || look_for_subcommand)
1975 // We are completing further on into a commands arguments, so find the command and tell it
1976 // to complete the command.
1977 // First see if there is a matching initial command:
1978 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
1979 if (command_object == nullptr)
1985 parsed_line.Shift();
1987 num_command_matches = command_object->HandleCompletion (parsed_line,
1989 cursor_char_position,
1991 max_return_elements,
1997 return num_command_matches;
2002 CommandInterpreter::HandleCompletion (const char *current_line,
2004 const char *last_char,
2005 int match_start_point,
2006 int max_return_elements,
2007 StringList &matches)
2009 // We parse the argument up to the cursor, so the last argument in parsed_line is
2010 // the one containing the cursor, and the cursor is after the last character.
2012 Args parsed_line(current_line, last_char - current_line);
2013 Args partial_parsed_line(current_line, cursor - current_line);
2015 // Don't complete comments, and if the line we are completing is just the history repeat character,
2016 // substitute the appropriate history line.
2017 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
2020 if (first_arg[0] == m_comment_char)
2022 else if (first_arg[0] == CommandHistory::g_repeat_char)
2024 const char *history_string = m_command_history.FindString (first_arg);
2025 if (history_string != nullptr)
2028 matches.InsertStringAtIndex(0, history_string);
2038 int num_args = partial_parsed_line.GetArgumentCount();
2039 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2040 int cursor_char_position;
2042 if (cursor_index == -1)
2043 cursor_char_position = 0;
2045 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
2047 if (cursor > current_line && cursor[-1] == ' ')
2049 // We are just after a space. If we are in an argument, then we will continue
2050 // parsing, but if we are between arguments, then we have to complete whatever the next
2051 // element would be.
2052 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2053 // protected by a quote) then the space will also be in the parsed argument...
2055 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2056 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2058 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
2060 cursor_char_position = 0;
2064 int num_command_matches;
2068 // Only max_return_elements == -1 is supported at present:
2069 assert (max_return_elements == -1);
2071 num_command_matches = HandleCompletionMatches (parsed_line,
2073 cursor_char_position,
2075 max_return_elements,
2079 if (num_command_matches <= 0)
2080 return num_command_matches;
2084 // If we got an empty string, insert nothing.
2085 matches.InsertStringAtIndex(0, "");
2089 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2090 // put an empty string in element 0.
2091 std::string command_partial_str;
2092 if (cursor_index >= 0)
2093 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2094 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
2096 std::string common_prefix;
2097 matches.LongestCommonPrefix (common_prefix);
2098 const size_t partial_name_len = command_partial_str.size();
2100 // If we matched a unique single command, add a space...
2101 // Only do this if the completer told us this was a complete word, however...
2102 if (num_command_matches == 1 && word_complete)
2104 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2105 if (quote_char != '\0')
2106 common_prefix.push_back(quote_char);
2108 common_prefix.push_back(' ');
2110 common_prefix.erase (0, partial_name_len);
2111 matches.InsertStringAtIndex(0, common_prefix.c_str());
2113 return num_command_matches;
2117 CommandInterpreter::~CommandInterpreter ()
2122 CommandInterpreter::UpdatePrompt (const char *new_prompt)
2124 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2125 BroadcastEvent (prompt_change_event_sp);
2126 if (m_command_io_handler_sp)
2127 m_command_io_handler_sp->SetPrompt(new_prompt);
2132 CommandInterpreter::Confirm (const char *message, bool default_answer)
2134 // Check AutoConfirm first:
2135 if (m_debugger.GetAutoConfirm())
2136 return default_answer;
2138 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2141 IOHandlerSP io_handler_sp (confirm);
2142 m_debugger.RunIOHandler (io_handler_sp);
2143 return confirm->GetResponse();
2147 CommandInterpreter::GetAliasOptions (const char *alias_name)
2149 OptionArgMap::iterator pos;
2150 OptionArgVectorSP ret_val;
2152 std::string alias (alias_name);
2154 if (HasAliasOptions())
2156 pos = m_alias_options.find (alias);
2157 if (pos != m_alias_options.end())
2158 ret_val = pos->second;
2165 CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2167 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2168 if (pos != m_alias_options.end())
2170 m_alias_options.erase (pos);
2175 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2177 m_alias_options[alias_name] = option_arg_vector_sp;
2181 CommandInterpreter::HasCommands ()
2183 return (!m_command_dict.empty());
2187 CommandInterpreter::HasAliases ()
2189 return (!m_alias_dict.empty());
2193 CommandInterpreter::HasUserCommands ()
2195 return (!m_user_dict.empty());
2199 CommandInterpreter::HasAliasOptions ()
2201 return (!m_alias_options.empty());
2205 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2206 const char *alias_name,
2208 std::string &raw_input_string,
2209 CommandReturnObject &result)
2211 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
2213 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
2215 // Make sure that the alias name is the 0th element in cmd_args
2216 std::string alias_name_str = alias_name;
2217 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2218 cmd_args.Unshift (alias_name);
2220 Args new_args (alias_cmd_obj->GetCommandName());
2221 if (new_args.GetArgumentCount() == 2)
2224 if (option_arg_vector_sp.get())
2226 if (wants_raw_input)
2228 // We have a command that both has command options and takes raw input. Make *sure* it has a
2229 // " -- " in the right place in the raw_input_string.
2230 size_t pos = raw_input_string.find(" -- ");
2231 if (pos == std::string::npos)
2233 // None found; assume it goes at the beginning of the raw input string
2234 raw_input_string.insert (0, " -- ");
2238 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2239 const size_t old_size = cmd_args.GetArgumentCount();
2240 std::vector<bool> used (old_size + 1, false);
2244 for (size_t i = 0; i < option_arg_vector->size(); ++i)
2246 OptionArgPair option_pair = (*option_arg_vector)[i];
2247 OptionArgValue value_pair = option_pair.second;
2248 int value_type = value_pair.first;
2249 std::string option = option_pair.first;
2250 std::string value = value_pair.second;
2251 if (option.compare ("<argument>") == 0)
2253 if (!wants_raw_input
2254 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2255 new_args.AppendArgument (value.c_str());
2259 if (value_type != OptionParser::eOptionalArgument)
2260 new_args.AppendArgument (option.c_str());
2261 if (value.compare ("<no-argument>") != 0)
2263 int index = GetOptionArgumentPosition (value.c_str());
2266 // value was NOT a positional argument; must be a real value
2267 if (value_type != OptionParser::eOptionalArgument)
2268 new_args.AppendArgument (value.c_str());
2272 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2273 new_args.AppendArgument (buffer);
2277 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
2279 result.AppendErrorWithFormat
2280 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2282 result.SetStatus (eReturnStatusFailed);
2287 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2288 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2289 if (strpos != std::string::npos)
2291 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2294 if (value_type != OptionParser::eOptionalArgument)
2295 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2299 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2300 cmd_args.GetArgumentAtIndex (index));
2301 new_args.AppendArgument (buffer);
2309 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
2311 if (!used[j] && !wants_raw_input)
2312 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2316 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2320 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2321 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2322 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2324 if (wants_raw_input)
2327 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2332 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2338 CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2340 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2343 char *cptr = (char *) in_string;
2345 // Does it start with '%'
2350 // Is the rest of it entirely digits?
2351 if (isdigit (cptr[0]))
2353 const char *start = cptr;
2354 while (isdigit (cptr[0]))
2357 // We've gotten to the end of the digits; are we at the end of the string?
2358 if (cptr[0] == '\0')
2359 position = atoi (start);
2367 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2372 // In the current working directory we don't load any program specific
2373 // .lldbinit files, we only look for a "./.lldbinit" file.
2374 if (m_skip_lldbinit_files)
2377 init_file.SetFile ("./.lldbinit", true);
2381 // If we aren't looking in the current working directory we are looking
2382 // in the home directory. We will first see if there is an application
2383 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2384 // "-" and the name of the program. If this file doesn't exist, we fall
2385 // back to just the "~/.lldbinit" file. We also obey any requests to not
2386 // load the init files.
2387 llvm::SmallString<64> home_dir_path;
2388 llvm::sys::path::home_directory(home_dir_path);
2389 FileSpec profilePath(home_dir_path.c_str(), false);
2390 profilePath.AppendPathComponent(".lldbinit");
2391 std::string init_file_path = profilePath.GetPath();
2393 if (m_skip_app_init_files == false)
2395 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2396 const char *program_name = program_file_spec.GetFilename().AsCString();
2400 char program_init_file_name[PATH_MAX];
2401 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path.c_str(), program_name);
2402 init_file.SetFile (program_init_file_name, true);
2403 if (!init_file.Exists())
2408 if (!init_file && !m_skip_lldbinit_files)
2409 init_file.SetFile (init_file_path.c_str(), false);
2412 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2413 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2415 if (init_file.Exists())
2417 const bool saved_batch = SetBatchCommandMode (true);
2418 HandleCommandsFromFile (init_file,
2419 nullptr, // Execution context
2420 eLazyBoolYes, // Stop on continue
2421 eLazyBoolNo, // Stop on error
2422 eLazyBoolNo, // Don't echo commands
2423 eLazyBoolNo, // Don't print command output
2424 eLazyBoolNo, // Don't add the commands that are sourced into the history buffer
2426 SetBatchCommandMode (saved_batch);
2430 // nothing to be done if the file doesn't exist
2431 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2436 CommandInterpreter::GetPlatform (bool prefer_target_platform)
2438 PlatformSP platform_sp;
2439 if (prefer_target_platform)
2441 ExecutionContext exe_ctx(GetExecutionContext());
2442 Target *target = exe_ctx.GetTargetPtr();
2444 platform_sp = target->GetPlatform();
2448 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2453 CommandInterpreter::HandleCommands (const StringList &commands,
2454 ExecutionContext *override_context,
2455 bool stop_on_continue,
2459 LazyBool add_to_history,
2460 CommandReturnObject &result)
2462 size_t num_lines = commands.GetSize();
2464 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2465 // Make sure you reset this value anywhere you return from the function.
2467 bool old_async_execution = m_debugger.GetAsyncExecution();
2469 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2470 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2472 if (override_context != nullptr)
2473 UpdateExecutionContext (override_context);
2475 if (!stop_on_continue)
2477 m_debugger.SetAsyncExecution (false);
2480 for (size_t idx = 0; idx < num_lines; idx++)
2482 const char *cmd = commands.GetStringAtIndex(idx);
2488 result.AppendMessageWithFormat ("%s %s\n",
2489 m_debugger.GetPrompt(),
2493 CommandReturnObject tmp_result;
2494 // If override_context is not NULL, pass no_context_switching = true for
2495 // HandleCommand() since we updated our context already.
2497 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2498 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here.
2499 if (!add_to_history)
2500 m_command_source_depth++;
2501 bool success = HandleCommand(cmd, add_to_history, tmp_result,
2502 nullptr, /* override_context */
2503 true, /* repeat_on_empty_command */
2504 override_context != nullptr /* no_context_switching */);
2505 if (!add_to_history)
2506 m_command_source_depth--;
2510 if (tmp_result.Succeeded())
2511 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
2514 if (!success || !tmp_result.Succeeded())
2516 const char *error_msg = tmp_result.GetErrorData();
2517 if (error_msg == nullptr || error_msg[0] == '\0')
2518 error_msg = "<unknown error>.\n";
2521 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s",
2522 (uint64_t)idx, cmd, error_msg);
2523 result.SetStatus (eReturnStatusFailed);
2524 m_debugger.SetAsyncExecution (old_async_execution);
2527 else if (print_results)
2529 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s",
2536 if (result.GetImmediateOutputStream())
2537 result.GetImmediateOutputStream()->Flush();
2539 if (result.GetImmediateErrorStream())
2540 result.GetImmediateErrorStream()->Flush();
2542 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2543 // could be running (for instance in Breakpoint Commands.
2544 // So we check the return value to see if it is has running in it.
2545 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2546 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2548 if (stop_on_continue)
2550 // If we caused the target to proceed, and we're going to stop in that case, set the
2551 // status in our real result before returning. This is an error if the continue was not the
2552 // last command in the set of commands to be run.
2553 if (idx != num_lines - 1)
2554 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n",
2555 (uint64_t)idx + 1, cmd);
2557 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd);
2559 result.SetStatus(tmp_result.GetStatus());
2560 m_debugger.SetAsyncExecution (old_async_execution);
2568 result.SetStatus (eReturnStatusSuccessFinishResult);
2569 m_debugger.SetAsyncExecution (old_async_execution);
2574 // Make flags that we can pass into the IOHandler so our delegates can do the right thing
2576 eHandleCommandFlagStopOnContinue = (1u << 0),
2577 eHandleCommandFlagStopOnError = (1u << 1),
2578 eHandleCommandFlagEchoCommand = (1u << 2),
2579 eHandleCommandFlagPrintResult = (1u << 3)
2583 CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2584 ExecutionContext *context,
2585 LazyBool stop_on_continue,
2586 LazyBool stop_on_error,
2587 LazyBool echo_command,
2588 LazyBool print_result,
2589 LazyBool add_to_history,
2590 CommandReturnObject &result)
2592 if (cmd_file.Exists())
2594 StreamFileSP input_file_sp (new StreamFile());
2596 std::string cmd_file_path = cmd_file.GetPath();
2597 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2599 if (error.Success())
2601 Debugger &debugger = GetDebugger();
2605 if (stop_on_continue == eLazyBoolCalculate)
2607 if (m_command_source_flags.empty())
2609 // Stop on continue by default
2610 flags |= eHandleCommandFlagStopOnContinue;
2612 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2614 flags |= eHandleCommandFlagStopOnContinue;
2617 else if (stop_on_continue == eLazyBoolYes)
2619 flags |= eHandleCommandFlagStopOnContinue;
2622 if (stop_on_error == eLazyBoolCalculate)
2624 if (m_command_source_flags.empty())
2626 if (GetStopCmdSourceOnError())
2627 flags |= eHandleCommandFlagStopOnError;
2629 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2631 flags |= eHandleCommandFlagStopOnError;
2634 else if (stop_on_error == eLazyBoolYes)
2636 flags |= eHandleCommandFlagStopOnError;
2639 if (echo_command == eLazyBoolCalculate)
2641 if (m_command_source_flags.empty())
2643 // Echo command by default
2644 flags |= eHandleCommandFlagEchoCommand;
2646 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2648 flags |= eHandleCommandFlagEchoCommand;
2651 else if (echo_command == eLazyBoolYes)
2653 flags |= eHandleCommandFlagEchoCommand;
2656 if (print_result == eLazyBoolCalculate)
2658 if (m_command_source_flags.empty())
2660 // Print output by default
2661 flags |= eHandleCommandFlagPrintResult;
2663 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
2665 flags |= eHandleCommandFlagPrintResult;
2668 else if (print_result == eLazyBoolYes)
2670 flags |= eHandleCommandFlagPrintResult;
2673 if (flags & eHandleCommandFlagPrintResult)
2675 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
2678 // Used for inheriting the right settings when "command source" might have
2679 // nested "command source" commands
2680 lldb::StreamFileSP empty_stream_sp;
2681 m_command_source_flags.push_back(flags);
2682 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
2684 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2685 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
2687 nullptr, // Pass in NULL for "editline_name" so no history is saved, or written
2688 debugger.GetPrompt(),
2689 false, // Not multi-line
2692 const bool old_async_execution = debugger.GetAsyncExecution();
2694 // Set synchronous execution if we not stopping when we continue
2695 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2696 debugger.SetAsyncExecution (false);
2698 m_command_source_depth++;
2700 debugger.RunIOHandler(io_handler_sp);
2701 if (!m_command_source_flags.empty())
2702 m_command_source_flags.pop_back();
2703 m_command_source_depth--;
2704 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2705 debugger.SetAsyncExecution (old_async_execution);
2709 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2710 result.SetStatus (eReturnStatusFailed);
2717 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2718 cmd_file.GetFilename().AsCString());
2719 result.SetStatus (eReturnStatusFailed);
2725 CommandInterpreter::GetScriptInterpreter (bool can_create)
2727 if (m_script_interpreter_ap.get() != nullptr)
2728 return m_script_interpreter_ap.get();
2733 // <rdar://problem/11751427>
2734 // we need to protect the initialization of the script interpreter
2735 // otherwise we could end up with two threads both trying to create
2736 // their instance of it, and for some languages (e.g. Python)
2737 // this is a bulletproof recipe for disaster!
2738 // this needs to be a function-level static because multiple Debugger instances living in the same process
2739 // still need to be isolated and not try to initialize Python concurrently
2740 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2741 Mutex::Locker interpreter_lock(g_interpreter_mutex);
2743 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
2745 log->Printf("Initializing the ScriptInterpreter now\n");
2747 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2748 switch (script_lang)
2750 case eScriptLanguagePython:
2751 #ifndef LLDB_DISABLE_PYTHON
2752 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2755 // Fall through to the None case when python is disabled
2757 case eScriptLanguageNone:
2758 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2762 return m_script_interpreter_ap.get();
2768 CommandInterpreter::GetSynchronous ()
2770 return m_synchronous_execution;
2774 CommandInterpreter::SetSynchronous (bool value)
2776 m_synchronous_execution = value;
2780 CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2781 const char *word_text,
2782 const char *separator,
2783 const char *help_text,
2784 size_t max_word_len)
2786 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2788 int indent_size = max_word_len + strlen (separator) + 2;
2790 strm.IndentMore (indent_size);
2792 StreamString text_strm;
2793 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text);
2795 size_t len = text_strm.GetSize();
2796 const char *text = text_strm.GetData();
2797 if (text[len - 1] == '\n')
2800 len = text_strm.GetSize();
2803 if (len < max_columns)
2805 // Output it as a single line.
2806 strm.Printf ("%s", text);
2810 // We need to break it up into multiple lines.
2811 bool first_line = true;
2815 const size_t final_end = strlen (text);
2817 while (end < final_end)
2820 text_width = max_columns - 1;
2822 text_width = max_columns - indent_size - 1;
2824 // Don't start the 'text' on a space, since we're already outputting the indentation.
2827 while ((start < final_end) && (text[start] == ' '))
2831 end = start + text_width;
2832 if (end > final_end)
2836 // If we're not at the end of the text, make sure we break the line on white space.
2838 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2843 const size_t sub_len = end - start;
2850 assert (start <= final_end);
2851 assert (start + sub_len <= final_end);
2853 strm.Write (text + start, sub_len);
2858 strm.IndentLess(indent_size);
2862 CommandInterpreter::OutputHelpText (Stream &strm,
2863 const char *word_text,
2864 const char *separator,
2865 const char *help_text,
2866 uint32_t max_word_len)
2868 int indent_size = max_word_len + strlen (separator) + 2;
2870 strm.IndentMore (indent_size);
2872 StreamString text_strm;
2873 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2875 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2877 size_t len = text_strm.GetSize();
2878 const char *text = text_strm.GetData();
2880 uint32_t chars_left = max_columns;
2882 for (uint32_t i = 0; i < len; i++)
2884 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2886 chars_left = max_columns - indent_size;
2892 strm.PutChar(text[i]);
2899 strm.IndentLess(indent_size);
2903 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2904 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
2906 CommandObject::CommandMap::const_iterator pos;
2908 if (search_builtin_commands)
2910 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2912 const char *command_name = pos->first.c_str();
2913 CommandObject *cmd_obj = pos->second.get();
2915 if (cmd_obj->HelpTextContainsWord (search_word))
2917 commands_found.AppendString (command_name);
2918 commands_help.AppendString (cmd_obj->GetHelp());
2921 if (cmd_obj->IsMultiwordObject())
2922 cmd_obj->AproposAllSubCommands (command_name,
2930 if (search_user_commands)
2932 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
2934 const char *command_name = pos->first.c_str();
2935 CommandObject *cmd_obj = pos->second.get();
2937 if (cmd_obj->HelpTextContainsWord (search_word))
2939 commands_found.AppendString (command_name);
2940 commands_help.AppendString (cmd_obj->GetHelp());
2943 if (cmd_obj->IsMultiwordObject())
2944 cmd_obj->AproposAllSubCommands (command_name,
2954 CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2956 if (override_context != nullptr)
2958 m_exe_ctx_ref = *override_context;
2962 const bool adopt_selected = true;
2963 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
2969 CommandInterpreter::GetProcessOutput ()
2971 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2972 char stdio_buffer[1024];
2974 size_t total_bytes = 0;
2976 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2979 ProcessSP process_sp (target_sp->GetProcessSP());
2982 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2984 size_t bytes_written = len;
2985 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
2988 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2990 size_t bytes_written = len;
2991 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
3000 CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
3002 const bool is_interactive = io_handler.GetIsInteractive();
3003 if (is_interactive == false)
3005 // When we are not interactive, don't execute blank lines. This will happen
3006 // sourcing a commands file. We don't want blank lines to repeat the previous
3007 // command and cause any errors to occur (like redefining an alias, get an error
3008 // and stop parsing the commands file).
3012 // When using a non-interactive file handle (like when sourcing commands from a file)
3013 // we need to echo the command out so we don't just see the command output and no
3015 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
3016 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
3019 lldb_private::CommandReturnObject result;
3020 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
3022 // Now emit the command output text from the command we just executed
3023 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
3025 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3026 GetProcessOutput ();
3028 if (!result.GetImmediateOutputStream())
3030 const char *output = result.GetOutputData();
3031 if (output && output[0])
3032 io_handler.GetOutputStreamFile()->PutCString(output);
3035 // Now emit the command error text from the command we just executed
3036 if (!result.GetImmediateErrorStream())
3038 const char *error = result.GetErrorData();
3039 if (error && error[0])
3040 io_handler.GetErrorStreamFile()->PutCString(error);
3044 switch (result.GetStatus())
3046 case eReturnStatusInvalid:
3047 case eReturnStatusSuccessFinishNoResult:
3048 case eReturnStatusSuccessFinishResult:
3049 case eReturnStatusStarted:
3052 case eReturnStatusSuccessContinuingNoResult:
3053 case eReturnStatusSuccessContinuingResult:
3054 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3055 io_handler.SetIsDone(true);
3058 case eReturnStatusFailed:
3059 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3060 io_handler.SetIsDone(true);
3063 case eReturnStatusQuit:
3064 io_handler.SetIsDone(true);
3070 CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler)
3072 ExecutionContext exe_ctx (GetExecutionContext());
3073 Process *process = exe_ctx.GetProcessPtr();
3077 StateType state = process->GetState();
3078 if (StateIsRunningState(state))
3081 return true; // Don't do any updating when we are running
3088 CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3089 IOHandlerDelegate &delegate,
3090 bool asynchronously,
3093 Debugger &debugger = GetDebugger();
3094 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3095 "lldb", // Name of input reader for history
3097 true, // Get multiple lines
3098 0, // Don't show line numbers
3099 delegate)); // IOHandlerDelegate
3103 io_handler_sp->SetUserData (baton);
3105 debugger.PushIOHandler(io_handler_sp);
3107 debugger.RunIOHandler(io_handler_sp);
3114 CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3115 IOHandlerDelegate &delegate,
3116 bool asynchronously,
3119 Debugger &debugger = GetDebugger();
3120 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3121 "lldb-python", // Name of input reader for history
3123 true, // Get multiple lines
3124 0, // Don't show line numbers
3125 delegate)); // IOHandlerDelegate
3129 io_handler_sp->SetUserData (baton);
3131 debugger.PushIOHandler(io_handler_sp);
3133 debugger.RunIOHandler(io_handler_sp);
3139 CommandInterpreter::IsActive ()
3141 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3145 CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
3148 // Only get one line at a time
3149 const bool multiple_lines = false;
3151 // Always re-create the IOHandlerEditline in case the input
3152 // changed. The old instance might have had a non-interactive
3153 // input and now it does or vice versa.
3154 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3155 m_debugger.GetInputFile(),
3156 m_debugger.GetOutputFile(),
3157 m_debugger.GetErrorFile(),
3158 eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult,
3160 m_debugger.GetPrompt(),
3162 0, // Don't show line numbers
3165 m_debugger.PushIOHandler(m_command_io_handler_sp);
3167 if (auto_handle_events)
3168 m_debugger.StartEventHandlerThread();
3172 m_debugger.StartIOHandlerThread();
3176 m_debugger.ExecuteIOHanders();
3178 if (auto_handle_events)
3179 m_debugger.StopEventHandlerThread();