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/Stream.h"
48 #include "lldb/Core/StreamFile.h"
49 #include "lldb/Core/Timer.h"
51 #include "lldb/Host/Editline.h"
52 #include "lldb/Host/Host.h"
54 #include "lldb/Interpreter/Args.h"
55 #include "lldb/Interpreter/CommandCompletions.h"
56 #include "lldb/Interpreter/CommandInterpreter.h"
57 #include "lldb/Interpreter/CommandReturnObject.h"
58 #include "lldb/Interpreter/Options.h"
59 #include "lldb/Interpreter/ScriptInterpreterNone.h"
60 #include "lldb/Interpreter/ScriptInterpreterPython.h"
63 #include "lldb/Target/Process.h"
64 #include "lldb/Target/Thread.h"
65 #include "lldb/Target/TargetList.h"
67 #include "lldb/Utility/CleanUp.h"
70 using namespace lldb_private;
73 static PropertyDefinition
76 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, NULL, NULL, "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." },
77 { "prompt-on-quit", OptionValue::eTypeBoolean, true, true, NULL, NULL, "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." },
78 { "stop-command-source-on-error", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, LLDB will stop running a 'command source' script upon encountering an error." },
79 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
84 ePropertyExpandRegexAliases = 0,
85 ePropertyPromptOnQuit = 1,
86 ePropertyStopCmdSourceOnError = 2
90 CommandInterpreter::GetStaticBroadcasterClass ()
92 static ConstString class_name ("lldb.commandInterpreter");
96 CommandInterpreter::CommandInterpreter
99 ScriptLanguage script_language,
100 bool synchronous_execution
102 Broadcaster (&debugger, "lldb.command-interpreter"),
103 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
104 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand),
105 m_debugger (debugger),
106 m_synchronous_execution (synchronous_execution),
107 m_skip_lldbinit_files (false),
108 m_skip_app_init_files (false),
109 m_script_interpreter_ap (),
110 m_command_io_handler_sp (),
111 m_comment_char ('#'),
112 m_batch_command_mode (false),
113 m_truncation_warning(eNoTruncation),
114 m_command_source_depth (0)
116 debugger.SetScriptLanguage (script_language);
117 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
118 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
119 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
120 CheckInWithManager ();
121 m_collection_sp->Initialize (g_properties);
125 CommandInterpreter::GetExpandRegexAliases () const
127 const uint32_t idx = ePropertyExpandRegexAliases;
128 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
132 CommandInterpreter::GetPromptOnQuit () const
134 const uint32_t idx = ePropertyPromptOnQuit;
135 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
139 CommandInterpreter::GetStopCmdSourceOnError () const
141 const uint32_t idx = ePropertyStopCmdSourceOnError;
142 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
146 CommandInterpreter::Initialize ()
148 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
150 CommandReturnObject result;
152 LoadCommandDictionary ();
154 // Set up some initial aliases.
155 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
158 AddAlias ("q", cmd_obj_sp);
159 AddAlias ("exit", cmd_obj_sp);
162 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
165 AddAlias ("attach", cmd_obj_sp);
168 cmd_obj_sp = GetCommandSPExact ("process detach",false);
171 AddAlias ("detach", cmd_obj_sp);
174 cmd_obj_sp = GetCommandSPExact ("process continue", false);
177 AddAlias ("c", cmd_obj_sp);
178 AddAlias ("continue", cmd_obj_sp);
181 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
183 AddAlias ("b", cmd_obj_sp);
185 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
187 AddAlias ("tbreak", cmd_obj_sp);
189 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
192 AddAlias ("stepi", cmd_obj_sp);
193 AddAlias ("si", cmd_obj_sp);
196 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
199 AddAlias ("nexti", cmd_obj_sp);
200 AddAlias ("ni", cmd_obj_sp);
203 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
206 AddAlias ("s", cmd_obj_sp);
207 AddAlias ("step", cmd_obj_sp);
210 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
213 AddAlias ("n", cmd_obj_sp);
214 AddAlias ("next", cmd_obj_sp);
217 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
220 AddAlias ("finish", cmd_obj_sp);
223 cmd_obj_sp = GetCommandSPExact ("frame select", false);
226 AddAlias ("f", cmd_obj_sp);
229 cmd_obj_sp = GetCommandSPExact ("thread select", false);
232 AddAlias ("t", cmd_obj_sp);
235 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
238 AddAlias ("j", cmd_obj_sp);
239 AddAlias ("jump", cmd_obj_sp);
242 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
245 AddAlias ("l", cmd_obj_sp);
246 AddAlias ("list", cmd_obj_sp);
249 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
252 AddAlias ("env", cmd_obj_sp);
255 cmd_obj_sp = GetCommandSPExact ("memory read", false);
257 AddAlias ("x", cmd_obj_sp);
259 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
261 AddAlias ("up", cmd_obj_sp);
263 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
265 AddAlias ("down", cmd_obj_sp);
267 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
269 AddAlias ("display", cmd_obj_sp);
271 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
273 AddAlias ("dis", cmd_obj_sp);
275 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
277 AddAlias ("di", cmd_obj_sp);
281 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
283 AddAlias ("undisplay", cmd_obj_sp);
285 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
287 AddAlias ("bt", cmd_obj_sp);
289 cmd_obj_sp = GetCommandSPExact ("target create", false);
291 AddAlias ("file", cmd_obj_sp);
293 cmd_obj_sp = GetCommandSPExact ("target modules", false);
295 AddAlias ("image", cmd_obj_sp);
298 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
300 cmd_obj_sp = GetCommandSPExact ("expression", false);
303 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
304 AddAlias ("p", cmd_obj_sp);
305 AddAlias ("print", cmd_obj_sp);
306 AddAlias ("call", cmd_obj_sp);
307 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
308 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
309 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
311 alias_arguments_vector_sp.reset (new OptionArgVector);
312 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
313 AddAlias ("po", cmd_obj_sp);
314 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
317 cmd_obj_sp = GetCommandSPExact ("process kill", false);
320 AddAlias ("kill", cmd_obj_sp);
323 cmd_obj_sp = GetCommandSPExact ("process launch", false);
326 alias_arguments_vector_sp.reset (new OptionArgVector);
327 #if defined (__arm__)
328 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
330 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=" LLDB_DEFAULT_SHELL " --", alias_arguments_vector_sp);
332 AddAlias ("r", cmd_obj_sp);
333 AddAlias ("run", cmd_obj_sp);
334 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
335 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
338 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
341 AddAlias ("add-dsym", cmd_obj_sp);
344 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
347 alias_arguments_vector_sp.reset (new OptionArgVector);
348 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
349 AddAlias ("rbreak", cmd_obj_sp);
350 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
355 CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
357 // This function has not yet been implemented.
359 // Look for any embedded script command
361 // get interpreter object from the command dictionary,
362 // call execute_one_command on it,
363 // get the results as a string,
364 // substitute that string for current stuff.
371 CommandInterpreter::LoadCommandDictionary ()
373 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
375 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
377 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
378 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
379 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
380 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
381 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
382 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
383 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
384 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
385 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
386 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
387 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
388 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
389 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
390 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
391 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
392 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
393 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
394 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
395 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
396 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
397 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
398 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
399 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
401 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
402 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
403 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
404 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
405 {"^(-.*)$", "breakpoint set %1"},
406 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
407 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
408 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
410 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
412 std::unique_ptr<CommandObjectRegexCommand>
413 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
415 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
416 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
418 CommandCompletions::eSymbolCompletion |
419 CommandCompletions::eSourceFileCompletion));
421 if (break_regex_cmd_ap.get())
424 for (size_t i = 0; i < num_regexes; i++)
426 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
430 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
434 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
435 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
439 std::unique_ptr<CommandObjectRegexCommand>
440 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
442 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
443 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
445 CommandCompletions::eSymbolCompletion |
446 CommandCompletions::eSourceFileCompletion));
448 if (tbreak_regex_cmd_ap.get())
451 for (size_t i = 0; i < num_regexes; i++)
453 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
455 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
456 assert (num_printed < 1024);
457 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
461 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
465 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
466 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
470 std::unique_ptr<CommandObjectRegexCommand>
471 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
473 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
474 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
476 if (attach_regex_cmd_ap.get())
478 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
479 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
480 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
481 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
483 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
484 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
488 std::unique_ptr<CommandObjectRegexCommand>
489 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
491 "Go down \"n\" frames in the stack (1 frame by default).",
492 "_regexp-down [n]", 2));
493 if (down_regex_cmd_ap.get())
495 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
496 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
498 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
499 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
503 std::unique_ptr<CommandObjectRegexCommand>
504 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
506 "Go up \"n\" frames in the stack (1 frame by default).",
507 "_regexp-up [n]", 2));
508 if (up_regex_cmd_ap.get())
510 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
511 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
513 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
514 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
518 std::unique_ptr<CommandObjectRegexCommand>
519 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
521 "Add an expression evaluation stop-hook.",
522 "_regexp-display expression", 2));
523 if (display_regex_cmd_ap.get())
525 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
527 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
528 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
532 std::unique_ptr<CommandObjectRegexCommand>
533 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
535 "Remove an expression evaluation stop-hook.",
536 "_regexp-undisplay stop-hook-number", 2));
537 if (undisplay_regex_cmd_ap.get())
539 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
541 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
542 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
546 std::unique_ptr<CommandObjectRegexCommand>
547 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
549 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
550 "gdb-remote [<hostname>:]<portnum>", 2));
551 if (connect_gdb_remote_cmd_ap.get())
553 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
554 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
556 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
557 m_command_dict[command_sp->GetCommandName ()] = command_sp;
561 std::unique_ptr<CommandObjectRegexCommand>
562 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
564 "Connect to a remote KDP server. udp port 41139 is the default port number.",
565 "kdp-remote <hostname>[:<portnum>]", 2));
566 if (connect_kdp_remote_cmd_ap.get())
568 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
569 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
571 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
572 m_command_dict[command_sp->GetCommandName ()] = command_sp;
576 std::unique_ptr<CommandObjectRegexCommand>
577 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
579 "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.",
580 "bt [<digit>|all]", 2));
581 if (bt_regex_cmd_ap.get())
583 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
584 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
585 // so now "bt 3" is the preferred form, in line with gdb.
586 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
587 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
588 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
589 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
591 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
592 m_command_dict[command_sp->GetCommandName ()] = command_sp;
596 std::unique_ptr<CommandObjectRegexCommand>
597 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
599 "Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the appropriate 'source list' commands.",
600 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
602 CommandCompletions::eSourceFileCompletion));
603 if (list_regex_cmd_ap.get())
605 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
606 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
607 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
608 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
609 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
610 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
611 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
613 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
614 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
618 std::unique_ptr<CommandObjectRegexCommand>
619 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
621 "Implements a shortcut to viewing and setting environment variables.",
622 "_regexp-env\n_regexp-env FOO=BAR", 2));
623 if (env_regex_cmd_ap.get())
625 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
626 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
628 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
629 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
633 std::unique_ptr<CommandObjectRegexCommand>
634 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
636 "Sets the program counter to a new address.",
637 "_regexp-jump [<line>]\n"
638 "_regexp-jump [<+-lineoffset>]\n"
639 "_regexp-jump [<file>:<line>]\n"
640 "_regexp-jump [*<addr>]\n", 2));
641 if (jump_regex_cmd_ap.get())
643 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
644 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
645 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
646 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
648 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
649 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
656 CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
659 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
663 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
666 return matches.GetSize();
670 CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
672 CommandObject::CommandMap::iterator pos;
673 CommandObjectSP command_sp;
675 std::string cmd(cmd_cstr);
679 pos = m_command_dict.find(cmd);
680 if (pos != m_command_dict.end())
681 command_sp = pos->second;
684 if (include_aliases && HasAliases())
686 pos = m_alias_dict.find(cmd);
687 if (pos != m_alias_dict.end())
688 command_sp = pos->second;
691 if (HasUserCommands())
693 pos = m_user_dict.find(cmd);
694 if (pos != m_user_dict.end())
695 command_sp = pos->second;
698 if (!exact && !command_sp)
700 // We will only get into here if we didn't find any exact matches.
702 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
704 StringList local_matches;
706 matches = &local_matches;
708 unsigned int num_cmd_matches = 0;
709 unsigned int num_alias_matches = 0;
710 unsigned int num_user_matches = 0;
712 // Look through the command dictionaries one by one, and if we get only one match from any of
713 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
717 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
720 if (num_cmd_matches == 1)
722 cmd.assign(matches->GetStringAtIndex(0));
723 pos = m_command_dict.find(cmd);
724 if (pos != m_command_dict.end())
725 real_match_sp = pos->second;
728 if (include_aliases && HasAliases())
730 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
734 if (num_alias_matches == 1)
736 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
737 pos = m_alias_dict.find(cmd);
738 if (pos != m_alias_dict.end())
739 alias_match_sp = pos->second;
742 if (HasUserCommands())
744 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
747 if (num_user_matches == 1)
749 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
751 pos = m_user_dict.find (cmd);
752 if (pos != m_user_dict.end())
753 user_match_sp = pos->second;
756 // If we got exactly one match, return that, otherwise return the match list.
758 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
761 return real_match_sp;
762 else if (num_alias_matches)
763 return alias_match_sp;
765 return user_match_sp;
768 else if (matches && command_sp)
770 matches->AppendString (cmd_cstr);
778 CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
782 std::string name_sstr(name);
783 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
784 if (found && !can_replace)
786 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
788 m_command_dict[name_sstr] = cmd_sp;
795 CommandInterpreter::AddUserCommand (std::string name,
796 const lldb::CommandObjectSP &cmd_sp,
802 const char* name_cstr = name.c_str();
804 // do not allow replacement of internal commands
805 if (CommandExists(name_cstr))
807 if (can_replace == false)
809 if (m_command_dict[name]->IsRemovable() == false)
813 if (UserCommandExists(name_cstr))
815 if (can_replace == false)
817 if (m_user_dict[name]->IsRemovable() == false)
821 m_user_dict[name] = cmd_sp;
828 CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
830 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
831 CommandObjectSP ret_val; // Possibly empty return value.
833 if (cmd_cstr == NULL)
836 if (cmd_words.GetArgumentCount() == 1)
837 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
840 // We have a multi-word command (seemingly), so we need to do more work.
841 // First, get the cmd_obj_sp for the first word in the command.
842 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
843 if (cmd_obj_sp.get() != NULL)
845 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
846 // command name), and find the appropriate sub-command SP for each command word....
847 size_t end = cmd_words.GetArgumentCount();
848 for (size_t j= 1; j < end; ++j)
850 if (cmd_obj_sp->IsMultiwordObject())
852 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
853 if (cmd_obj_sp.get() == NULL)
854 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
858 // We have more words in the command name, but we don't have a multiword object. Fail and return
862 // We successfully looped through all the command words and got valid command objects for them. Assign the
863 // last object retrieved to 'ret_val'.
864 ret_val = cmd_obj_sp;
871 CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
873 return GetCommandSPExact (cmd_cstr, include_aliases).get();
877 CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
879 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
881 // If we didn't find an exact match to the command string in the commands, look in
887 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
892 // If there wasn't an exact match then look for an inexact one in just the commands
893 command_obj = GetCommandSP(cmd_cstr, false, false, NULL).get();
895 // Finally, if there wasn't an inexact match among the commands, look for an inexact
896 // match in both the commands and aliases.
901 matches->AppendString(command_obj->GetCommandName());
905 return GetCommandSP(cmd_cstr, true, false, matches).get();
909 CommandInterpreter::CommandExists (const char *cmd)
911 return m_command_dict.find(cmd) != m_command_dict.end();
915 CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
916 const char *options_args,
917 OptionArgVectorSP &option_arg_vector_sp)
920 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
922 if (!options_args || (strlen (options_args) < 1))
925 std::string options_string (options_args);
926 Args args (options_args);
927 CommandReturnObject result;
928 // Check to see if the command being aliased can take any command options.
929 Options *options = cmd_obj_sp->GetOptions ();
932 // See if any options were specified as part of the alias; if so, handle them appropriately.
933 options->NotifyOptionParsingStarting ();
934 args.Unshift ("dummy_arg");
935 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
937 if (result.Succeeded())
938 options->VerifyPartialOptions (result);
939 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
941 result.AppendError ("Unable to create requested alias.\n");
946 if (!options_string.empty())
948 if (cmd_obj_sp->WantsRawCommandString ())
949 option_arg_vector->push_back (OptionArgPair ("<argument>",
954 const size_t argc = args.GetArgumentCount();
955 for (size_t i = 0; i < argc; ++i)
956 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
957 option_arg_vector->push_back
958 (OptionArgPair ("<argument>",
960 std::string (args.GetArgumentAtIndex (i)))));
968 CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
970 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
973 full_name.assign(cmd);
979 size_t num_alias_matches;
980 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
981 if (num_alias_matches == 1)
983 // Make sure this isn't shadowing a command in the regular command space:
984 StringList regular_matches;
985 const bool include_aliases = false;
986 const bool exact = false;
987 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, ®ular_matches));
988 if (cmd_obj_sp || regular_matches.GetSize() > 0)
992 full_name.assign (matches.GetStringAtIndex(0));
1002 CommandInterpreter::AliasExists (const char *cmd)
1004 return m_alias_dict.find(cmd) != m_alias_dict.end();
1008 CommandInterpreter::UserCommandExists (const char *cmd)
1010 return m_user_dict.find(cmd) != m_user_dict.end();
1014 CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1016 command_obj_sp->SetIsAlias (true);
1017 m_alias_dict[alias_name] = command_obj_sp;
1021 CommandInterpreter::RemoveAlias (const char *alias_name)
1023 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1024 if (pos != m_alias_dict.end())
1026 m_alias_dict.erase(pos);
1032 CommandInterpreter::RemoveUser (const char *alias_name)
1034 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1035 if (pos != m_user_dict.end())
1037 m_user_dict.erase(pos);
1044 CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1046 help_string.Printf ("'%s", command_name);
1047 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1049 if (option_arg_vector_sp)
1051 OptionArgVector *options = option_arg_vector_sp.get();
1052 for (size_t i = 0; i < options->size(); ++i)
1054 OptionArgPair cur_option = (*options)[i];
1055 std::string opt = cur_option.first;
1056 OptionArgValue value_pair = cur_option.second;
1057 std::string value = value_pair.second;
1058 if (opt.compare("<argument>") == 0)
1060 help_string.Printf (" %s", value.c_str());
1064 help_string.Printf (" %s", opt.c_str());
1065 if ((value.compare ("<no-argument>") != 0)
1066 && (value.compare ("<need-argument") != 0))
1068 help_string.Printf (" %s", value.c_str());
1074 help_string.Printf ("'");
1078 CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1080 CommandObject::CommandMap::const_iterator pos;
1081 CommandObject::CommandMap::const_iterator end = dict.end();
1084 for (pos = dict.begin(); pos != end; ++pos)
1086 size_t len = pos->first.size();
1094 CommandInterpreter::GetHelp (CommandReturnObject &result,
1097 CommandObject::CommandMap::const_iterator pos;
1098 size_t max_len = FindLongestCommandWord (m_command_dict);
1100 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
1103 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
1104 result.AppendMessage("");
1106 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1108 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1111 result.AppendMessage("");
1115 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
1117 result.AppendMessage("The following is a list of your current command abbreviations "
1118 "(see 'help command alias' for more info):");
1119 result.AppendMessage("");
1120 max_len = FindLongestCommandWord (m_alias_dict);
1122 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1125 StreamString translation_and_help;
1126 std::string entry_name = pos->first;
1127 std::string second_entry = pos->second.get()->GetCommandName();
1128 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1130 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1131 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1132 translation_and_help.GetData(), max_len);
1134 result.AppendMessage("");
1137 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
1139 result.AppendMessage ("The following is a list of your current user-defined commands:");
1140 result.AppendMessage("");
1141 max_len = FindLongestCommandWord (m_user_dict);
1142 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1144 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1147 result.AppendMessage("");
1150 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1154 CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
1156 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1157 // eventually be invoked by the given command line.
1159 CommandObject *cmd_obj = NULL;
1160 std::string white_space (" \t\v");
1161 size_t start = command_string.find_first_not_of (white_space);
1166 if (start != std::string::npos)
1168 // Get the next word from command_string.
1169 end = command_string.find_first_of (white_space, start);
1170 if (end == std::string::npos)
1171 end = command_string.size();
1172 std::string cmd_word = command_string.substr (start, end - start);
1174 if (cmd_obj == NULL)
1175 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1176 // command or alias.
1177 cmd_obj = GetCommandObject (cmd_word.c_str());
1178 else if (cmd_obj->IsMultiwordObject ())
1180 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
1181 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
1183 cmd_obj = sub_cmd_obj;
1184 else // cmd_word was not a valid sub-command word, so we are donee
1188 // We have a cmd_obj and it is not a multi-word object, so we are done.
1191 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1192 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1195 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1198 start = command_string.find_first_not_of (white_space, end);
1201 // Unable to find any more words.
1205 if (end == command_string.size())
1206 command_string.clear();
1208 command_string = command_string.substr(end);
1213 static const char *k_white_space = " \t\v";
1214 static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1216 StripLeadingSpaces (std::string &s)
1220 size_t pos = s.find_first_not_of (k_white_space);
1221 if (pos == std::string::npos)
1230 FindArgumentTerminator (const std::string &s)
1232 const size_t s_len = s.size();
1234 while (offset < s_len)
1236 size_t pos = s.find ("--", offset);
1237 if (pos == std::string::npos)
1241 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]))
1253 return std::string::npos;
1257 ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char "e_char)
1261 StripLeadingSpaces (command_string);
1263 bool result = false;
1266 if (!command_string.empty())
1268 const char first_char = command_string[0];
1269 if (first_char == '\'' || first_char == '"')
1271 quote_char = first_char;
1272 const size_t end_quote_pos = command_string.find (quote_char, 1);
1273 if (end_quote_pos == std::string::npos)
1275 command.swap (command_string);
1276 command_string.erase ();
1280 command.assign (command_string, 1, end_quote_pos - 1);
1281 if (end_quote_pos + 1 < command_string.size())
1282 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1284 command_string.erase ();
1289 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1290 if (first_space_pos == std::string::npos)
1292 command.swap (command_string);
1293 command_string.erase();
1297 command.assign (command_string, 0, first_space_pos);
1298 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
1305 if (!command.empty())
1307 // actual commands can't start with '-' or '_'
1308 if (command[0] != '-' && command[0] != '_')
1310 size_t pos = command.find_first_not_of(k_valid_command_chars);
1311 if (pos > 0 && pos != std::string::npos)
1313 suffix.assign (command.begin() + pos, command.end());
1314 command.erase (pos);
1323 CommandInterpreter::BuildAliasResult (const char *alias_name,
1324 std::string &raw_input_string,
1325 std::string &alias_result,
1326 CommandReturnObject &result)
1328 CommandObject *alias_cmd_obj = NULL;
1329 Args cmd_args (raw_input_string.c_str());
1330 alias_cmd_obj = GetCommandObject (alias_name);
1331 StreamString result_str;
1335 std::string alias_name_str = alias_name;
1336 if ((cmd_args.GetArgumentCount() == 0)
1337 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1338 cmd_args.Unshift (alias_name);
1340 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1341 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1343 if (option_arg_vector_sp.get())
1345 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1347 for (size_t i = 0; i < option_arg_vector->size(); ++i)
1349 OptionArgPair option_pair = (*option_arg_vector)[i];
1350 OptionArgValue value_pair = option_pair.second;
1351 int value_type = value_pair.first;
1352 std::string option = option_pair.first;
1353 std::string value = value_pair.second;
1354 if (option.compare ("<argument>") == 0)
1355 result_str.Printf (" %s", value.c_str());
1358 result_str.Printf (" %s", option.c_str());
1359 if (value_type != OptionParser::eOptionalArgument)
1360 result_str.Printf (" ");
1361 if (value.compare ("<OptionParser::eNoArgument>") != 0)
1363 int index = GetOptionArgumentPosition (value.c_str());
1365 result_str.Printf ("%s", value.c_str());
1366 else if (index >= cmd_args.GetArgumentCount())
1369 result.AppendErrorWithFormat
1370 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1372 result.SetStatus (eReturnStatusFailed);
1373 return alias_cmd_obj;
1377 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1378 if (strpos != std::string::npos)
1379 raw_input_string = raw_input_string.erase (strpos,
1380 strlen (cmd_args.GetArgumentAtIndex (index)));
1381 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1388 alias_result = result_str.GetData();
1390 return alias_cmd_obj;
1394 CommandInterpreter::PreprocessCommand (std::string &command)
1396 // The command preprocessor needs to do things to the command
1397 // line before any parsing of arguments or anything else is done.
1398 // The only current stuff that gets proprocessed is anyting enclosed
1399 // in backtick ('`') characters is evaluated as an expression and
1400 // the result of the expression must be a scalar that can be substituted
1401 // into the command. An example would be:
1402 // (lldb) memory read `$rsp + 20`
1403 Error error; // Error for any expressions that might not evaluate
1404 size_t start_backtick;
1406 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1408 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1410 // The backtick was preceeded by a '\' character, remove the slash
1411 // and don't treat the backtick as the start of an expression
1412 command.erase(start_backtick-1, 1);
1413 // No need to add one to start_backtick since we just deleted a char
1414 pos = start_backtick;
1418 const size_t expr_content_start = start_backtick + 1;
1419 const size_t end_backtick = command.find ('`', expr_content_start);
1420 if (end_backtick == std::string::npos)
1422 else if (end_backtick == expr_content_start)
1424 // Empty expression (two backticks in a row)
1425 command.erase (start_backtick, 2);
1429 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1431 ExecutionContext exe_ctx(GetExecutionContext());
1432 Target *target = exe_ctx.GetTargetPtr();
1433 // Get a dummy target to allow for calculator mode while processing backticks.
1434 // This also helps break the infinite loop caused when target is null.
1436 target = Host::GetDummyTarget(GetDebugger()).get();
1439 ValueObjectSP expr_result_valobj_sp;
1441 EvaluateExpressionOptions options;
1442 options.SetCoerceToId(false);
1443 options.SetUnwindOnError(true);
1444 options.SetIgnoreBreakpoints(true);
1445 options.SetKeepInMemory(false);
1446 options.SetTryAllThreads(true);
1447 options.SetTimeoutUsec(0);
1449 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1450 exe_ctx.GetFramePtr(),
1451 expr_result_valobj_sp,
1454 if (expr_result == eExecutionCompleted)
1457 if (expr_result_valobj_sp->ResolveValue (scalar))
1459 command.erase (start_backtick, end_backtick - start_backtick + 1);
1460 StreamString value_strm;
1461 const bool show_type = false;
1462 scalar.GetValue (&value_strm, show_type);
1463 size_t value_string_size = value_strm.GetSize();
1464 if (value_string_size)
1466 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1467 pos = start_backtick + value_string_size;
1472 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1477 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1482 if (expr_result_valobj_sp)
1483 error = expr_result_valobj_sp->GetError();
1484 if (error.Success())
1487 switch (expr_result)
1489 case eExecutionSetupError:
1490 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1492 case eExecutionCompleted:
1494 case eExecutionDiscarded:
1495 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1497 case eExecutionInterrupted:
1498 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1500 case eExecutionHitBreakpoint:
1501 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1503 case eExecutionTimedOut:
1504 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1506 case eExecutionStoppedForDebug:
1507 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1523 CommandInterpreter::HandleCommand (const char *command_line,
1524 LazyBool lazy_add_to_history,
1525 CommandReturnObject &result,
1526 ExecutionContext *override_context,
1527 bool repeat_on_empty_command,
1528 bool no_context_switching)
1533 CommandObject *cmd_obj = NULL;
1534 bool wants_raw_input = false;
1535 std::string command_string (command_line);
1536 std::string original_command_string (command_line);
1538 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
1539 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1541 // Make a scoped cleanup object that will clear the crash description string
1542 // on exit of this function.
1543 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
1546 log->Printf ("Processing command: %s", command_line);
1548 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1550 if (!no_context_switching)
1551 UpdateExecutionContext (override_context);
1553 bool add_to_history;
1554 if (lazy_add_to_history == eLazyBoolCalculate)
1555 add_to_history = (m_command_source_depth == 0);
1557 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1559 bool empty_command = false;
1560 bool comment_command = false;
1561 if (command_string.empty())
1562 empty_command = true;
1565 const char *k_space_characters = "\t\n\v\f\r ";
1567 size_t non_space = command_string.find_first_not_of (k_space_characters);
1568 // Check for empty line or comment line (lines whose first
1569 // non-space character is the comment character for this interpreter)
1570 if (non_space == std::string::npos)
1571 empty_command = true;
1572 else if (command_string[non_space] == m_comment_char)
1573 comment_command = true;
1574 else if (command_string[non_space] == CommandHistory::g_repeat_char)
1576 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
1577 if (history_string == NULL)
1579 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1580 result.SetStatus(eReturnStatusFailed);
1583 add_to_history = false;
1584 command_string = history_string;
1585 original_command_string = history_string;
1591 if (repeat_on_empty_command)
1593 if (m_command_history.IsEmpty())
1595 result.AppendError ("empty command");
1596 result.SetStatus(eReturnStatusFailed);
1601 command_line = m_repeat_command.c_str();
1602 command_string = command_line;
1603 original_command_string = command_line;
1604 if (m_repeat_command.empty())
1606 result.AppendErrorWithFormat("No auto repeat.\n");
1607 result.SetStatus (eReturnStatusFailed);
1611 add_to_history = false;
1615 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1619 else if (comment_command)
1621 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1626 Error error (PreprocessCommand (command_string));
1630 result.AppendError (error.AsCString());
1631 result.SetStatus(eReturnStatusFailed);
1636 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1637 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1638 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1639 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1640 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
1641 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
1642 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
1644 StreamString revised_command_line;
1645 size_t actual_cmd_name_len = 0;
1646 std::string next_word;
1650 char quote_char = '\0';
1652 ExtractCommand (command_string, next_word, suffix, quote_char);
1653 if (cmd_obj == NULL)
1655 std::string full_name;
1656 if (GetAliasFullName(next_word.c_str(), full_name))
1658 std::string alias_result;
1659 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
1660 revised_command_line.Printf ("%s", alias_result.c_str());
1663 wants_raw_input = cmd_obj->WantsRawCommandString ();
1664 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1669 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
1672 actual_cmd_name_len += next_word.length();
1673 revised_command_line.Printf ("%s", next_word.c_str());
1674 wants_raw_input = cmd_obj->WantsRawCommandString ();
1678 revised_command_line.Printf ("%s", next_word.c_str());
1684 if (cmd_obj->IsMultiwordObject ())
1686 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
1689 actual_cmd_name_len += next_word.length() + 1;
1690 revised_command_line.Printf (" %s", next_word.c_str());
1691 cmd_obj = sub_cmd_obj;
1692 wants_raw_input = cmd_obj->WantsRawCommandString ();
1697 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1699 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1706 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1708 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1713 if (cmd_obj == NULL)
1715 const size_t num_matches = matches.GetSize();
1716 if (matches.GetSize() > 1) {
1717 StreamString error_msg;
1718 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
1720 for (uint32_t i = 0; i < num_matches; ++i) {
1721 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
1723 result.AppendRawError (error_msg.GetString().c_str());
1725 // We didn't have only one match, otherwise we wouldn't get here.
1726 assert(num_matches == 0);
1727 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1729 result.SetStatus (eReturnStatusFailed);
1733 if (cmd_obj->IsMultiwordObject ())
1735 if (!suffix.empty())
1738 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1739 cmd_obj->GetCommandName(),
1740 next_word.empty() ? "" : next_word.c_str(),
1741 next_word.empty() ? " -- " : " ",
1743 result.SetStatus (eReturnStatusFailed);
1749 // If we found a normal command, we are done
1751 if (!suffix.empty())
1756 // GDB format suffixes
1758 Options *command_options = cmd_obj->GetOptions();
1759 if (command_options && command_options->SupportsLongOption("gdb-format"))
1761 std::string gdb_format_option ("--gdb-format=");
1762 gdb_format_option += (suffix.c_str() + 1);
1764 bool inserted = false;
1765 std::string &cmd = revised_command_line.GetString();
1766 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1767 if (arg_terminator_idx != std::string::npos)
1769 // Insert the gdb format option before the "--" that terminates options
1770 gdb_format_option.append(1,' ');
1771 cmd.insert(arg_terminator_idx, gdb_format_option);
1776 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1778 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1779 revised_command_line.PutCString (" --");
1783 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1784 cmd_obj->GetCommandName());
1785 result.SetStatus (eReturnStatusFailed);
1792 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1794 result.SetStatus (eReturnStatusFailed);
1800 if (command_string.length() == 0)
1805 if (!command_string.empty())
1806 revised_command_line.Printf (" %s", command_string.c_str());
1809 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1810 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1811 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1812 // wants_raw_input specifies whether the Execute method expects raw input or not.
1817 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1818 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1819 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1823 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1824 // CommandObject, with the appropriate arguments.
1826 if (cmd_obj != NULL)
1830 Args command_args (revised_command_line.GetData());
1831 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1832 if (repeat_command != NULL)
1833 m_repeat_command.assign(repeat_command);
1835 m_repeat_command.assign(original_command_string.c_str());
1837 m_command_history.AppendString (original_command_string);
1840 command_string = revised_command_line.GetData();
1841 std::string command_name (cmd_obj->GetCommandName());
1842 std::string remainder;
1843 if (actual_cmd_name_len < command_string.length())
1844 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1845 // than cmd_obj->GetCommandName(), because name completion
1846 // allows users to enter short versions of the names,
1847 // e.g. 'br s' for 'breakpoint set'.
1849 // Remove any initial spaces
1850 std::string white_space (" \t\v");
1851 size_t pos = remainder.find_first_not_of (white_space);
1852 if (pos != 0 && pos != std::string::npos)
1853 remainder.erase(0, pos);
1856 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
1858 cmd_obj->Execute (remainder.c_str(), result);
1862 // We didn't find the first command object, so complete the first argument.
1863 Args command_args (revised_command_line.GetData());
1866 int cursor_index = 0;
1867 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1869 num_matches = HandleCompletionMatches (command_args,
1871 cursor_char_position,
1877 if (num_matches > 0)
1879 std::string error_msg;
1880 error_msg.assign ("ambiguous command '");
1881 error_msg.append(command_args.GetArgumentAtIndex(0));
1882 error_msg.append ("'.");
1884 error_msg.append (" Possible completions:");
1885 for (int i = 0; i < num_matches; i++)
1887 error_msg.append ("\n\t");
1888 error_msg.append (matches.GetStringAtIndex (i));
1890 error_msg.append ("\n");
1891 result.AppendRawError (error_msg.c_str());
1894 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1896 result.SetStatus (eReturnStatusFailed);
1900 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1902 return result.Succeeded();
1906 CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1908 int &cursor_char_position,
1909 int match_start_point,
1910 int max_return_elements,
1911 bool &word_complete,
1912 StringList &matches)
1914 int num_command_matches = 0;
1915 bool look_for_subcommand = false;
1917 // For any of the command completions a unique match will be a complete word.
1918 word_complete = true;
1920 if (cursor_index == -1)
1922 // We got nothing on the command line, so return the list of commands
1923 bool include_aliases = true;
1924 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1926 else if (cursor_index == 0)
1928 // The cursor is in the first argument, so just do a lookup in the dictionary.
1929 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
1930 num_command_matches = matches.GetSize();
1932 if (num_command_matches == 1
1933 && cmd_obj && cmd_obj->IsMultiwordObject()
1934 && matches.GetStringAtIndex(0) != NULL
1935 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1937 if (parsed_line.GetArgumentCount() == 1)
1939 word_complete = true;
1943 look_for_subcommand = true;
1944 num_command_matches = 0;
1945 matches.DeleteStringAtIndex(0);
1946 parsed_line.AppendArgument ("");
1948 cursor_char_position = 0;
1953 if (cursor_index > 0 || look_for_subcommand)
1955 // We are completing further on into a commands arguments, so find the command and tell it
1956 // to complete the command.
1957 // First see if there is a matching initial command:
1958 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
1959 if (command_object == NULL)
1965 parsed_line.Shift();
1967 num_command_matches = command_object->HandleCompletion (parsed_line,
1969 cursor_char_position,
1971 max_return_elements,
1977 return num_command_matches;
1982 CommandInterpreter::HandleCompletion (const char *current_line,
1984 const char *last_char,
1985 int match_start_point,
1986 int max_return_elements,
1987 StringList &matches)
1989 // We parse the argument up to the cursor, so the last argument in parsed_line is
1990 // the one containing the cursor, and the cursor is after the last character.
1992 Args parsed_line(current_line, last_char - current_line);
1993 Args partial_parsed_line(current_line, cursor - current_line);
1995 // Don't complete comments, and if the line we are completing is just the history repeat character,
1996 // substitute the appropriate history line.
1997 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
2000 if (first_arg[0] == m_comment_char)
2002 else if (first_arg[0] == CommandHistory::g_repeat_char)
2004 const char *history_string = m_command_history.FindString (first_arg);
2005 if (history_string != NULL)
2008 matches.InsertStringAtIndex(0, history_string);
2018 int num_args = partial_parsed_line.GetArgumentCount();
2019 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2020 int cursor_char_position;
2022 if (cursor_index == -1)
2023 cursor_char_position = 0;
2025 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
2027 if (cursor > current_line && cursor[-1] == ' ')
2029 // We are just after a space. If we are in an argument, then we will continue
2030 // parsing, but if we are between arguments, then we have to complete whatever the next
2031 // element would be.
2032 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2033 // protected by a quote) then the space will also be in the parsed argument...
2035 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2036 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2038 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
2040 cursor_char_position = 0;
2044 int num_command_matches;
2048 // Only max_return_elements == -1 is supported at present:
2049 assert (max_return_elements == -1);
2051 num_command_matches = HandleCompletionMatches (parsed_line,
2053 cursor_char_position,
2055 max_return_elements,
2059 if (num_command_matches <= 0)
2060 return num_command_matches;
2064 // If we got an empty string, insert nothing.
2065 matches.InsertStringAtIndex(0, "");
2069 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2070 // put an empty string in element 0.
2071 std::string command_partial_str;
2072 if (cursor_index >= 0)
2073 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2074 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
2076 std::string common_prefix;
2077 matches.LongestCommonPrefix (common_prefix);
2078 const size_t partial_name_len = command_partial_str.size();
2080 // If we matched a unique single command, add a space...
2081 // Only do this if the completer told us this was a complete word, however...
2082 if (num_command_matches == 1 && word_complete)
2084 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2085 if (quote_char != '\0')
2086 common_prefix.push_back(quote_char);
2088 common_prefix.push_back(' ');
2090 common_prefix.erase (0, partial_name_len);
2091 matches.InsertStringAtIndex(0, common_prefix.c_str());
2093 return num_command_matches;
2097 CommandInterpreter::~CommandInterpreter ()
2102 CommandInterpreter::UpdatePrompt (const char *new_prompt)
2104 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2105 BroadcastEvent (prompt_change_event_sp);
2106 if (m_command_io_handler_sp)
2107 m_command_io_handler_sp->SetPrompt(new_prompt);
2112 CommandInterpreter::Confirm (const char *message, bool default_answer)
2114 // Check AutoConfirm first:
2115 if (m_debugger.GetAutoConfirm())
2116 return default_answer;
2118 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2121 IOHandlerSP io_handler_sp (confirm);
2122 m_debugger.RunIOHandler (io_handler_sp);
2123 return confirm->GetResponse();
2127 CommandInterpreter::GetAliasOptions (const char *alias_name)
2129 OptionArgMap::iterator pos;
2130 OptionArgVectorSP ret_val;
2132 std::string alias (alias_name);
2134 if (HasAliasOptions())
2136 pos = m_alias_options.find (alias);
2137 if (pos != m_alias_options.end())
2138 ret_val = pos->second;
2145 CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2147 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2148 if (pos != m_alias_options.end())
2150 m_alias_options.erase (pos);
2155 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2157 m_alias_options[alias_name] = option_arg_vector_sp;
2161 CommandInterpreter::HasCommands ()
2163 return (!m_command_dict.empty());
2167 CommandInterpreter::HasAliases ()
2169 return (!m_alias_dict.empty());
2173 CommandInterpreter::HasUserCommands ()
2175 return (!m_user_dict.empty());
2179 CommandInterpreter::HasAliasOptions ()
2181 return (!m_alias_options.empty());
2185 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2186 const char *alias_name,
2188 std::string &raw_input_string,
2189 CommandReturnObject &result)
2191 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
2193 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
2195 // Make sure that the alias name is the 0th element in cmd_args
2196 std::string alias_name_str = alias_name;
2197 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2198 cmd_args.Unshift (alias_name);
2200 Args new_args (alias_cmd_obj->GetCommandName());
2201 if (new_args.GetArgumentCount() == 2)
2204 if (option_arg_vector_sp.get())
2206 if (wants_raw_input)
2208 // We have a command that both has command options and takes raw input. Make *sure* it has a
2209 // " -- " in the right place in the raw_input_string.
2210 size_t pos = raw_input_string.find(" -- ");
2211 if (pos == std::string::npos)
2213 // None found; assume it goes at the beginning of the raw input string
2214 raw_input_string.insert (0, " -- ");
2218 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2219 const size_t old_size = cmd_args.GetArgumentCount();
2220 std::vector<bool> used (old_size + 1, false);
2224 for (size_t i = 0; i < option_arg_vector->size(); ++i)
2226 OptionArgPair option_pair = (*option_arg_vector)[i];
2227 OptionArgValue value_pair = option_pair.second;
2228 int value_type = value_pair.first;
2229 std::string option = option_pair.first;
2230 std::string value = value_pair.second;
2231 if (option.compare ("<argument>") == 0)
2233 if (!wants_raw_input
2234 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2235 new_args.AppendArgument (value.c_str());
2239 if (value_type != OptionParser::eOptionalArgument)
2240 new_args.AppendArgument (option.c_str());
2241 if (value.compare ("<no-argument>") != 0)
2243 int index = GetOptionArgumentPosition (value.c_str());
2246 // value was NOT a positional argument; must be a real value
2247 if (value_type != OptionParser::eOptionalArgument)
2248 new_args.AppendArgument (value.c_str());
2252 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2253 new_args.AppendArgument (buffer);
2257 else if (index >= cmd_args.GetArgumentCount())
2259 result.AppendErrorWithFormat
2260 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2262 result.SetStatus (eReturnStatusFailed);
2267 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2268 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2269 if (strpos != std::string::npos)
2271 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2274 if (value_type != OptionParser::eOptionalArgument)
2275 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2279 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2280 cmd_args.GetArgumentAtIndex (index));
2281 new_args.AppendArgument (buffer);
2289 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
2291 if (!used[j] && !wants_raw_input)
2292 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2296 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2300 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2301 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2302 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2304 if (wants_raw_input)
2307 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2312 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2318 CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2320 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2323 char *cptr = (char *) in_string;
2325 // Does it start with '%'
2330 // Is the rest of it entirely digits?
2331 if (isdigit (cptr[0]))
2333 const char *start = cptr;
2334 while (isdigit (cptr[0]))
2337 // We've gotten to the end of the digits; are we at the end of the string?
2338 if (cptr[0] == '\0')
2339 position = atoi (start);
2347 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2352 // In the current working directory we don't load any program specific
2353 // .lldbinit files, we only look for a "./.lldbinit" file.
2354 if (m_skip_lldbinit_files)
2357 init_file.SetFile ("./.lldbinit", true);
2361 // If we aren't looking in the current working directory we are looking
2362 // in the home directory. We will first see if there is an application
2363 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2364 // "-" and the name of the program. If this file doesn't exist, we fall
2365 // back to just the "~/.lldbinit" file. We also obey any requests to not
2366 // load the init files.
2367 const char *init_file_path = "~/.lldbinit";
2369 if (m_skip_app_init_files == false)
2371 FileSpec program_file_spec (Host::GetProgramFileSpec());
2372 const char *program_name = program_file_spec.GetFilename().AsCString();
2376 char program_init_file_name[PATH_MAX];
2377 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2378 init_file.SetFile (program_init_file_name, true);
2379 if (!init_file.Exists())
2384 if (!init_file && !m_skip_lldbinit_files)
2385 init_file.SetFile (init_file_path, true);
2388 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2389 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2391 if (init_file.Exists())
2393 const bool saved_batch = SetBatchCommandMode (true);
2394 HandleCommandsFromFile (init_file,
2395 NULL, // Execution context
2396 eLazyBoolYes, // Stop on continue
2397 eLazyBoolNo, // Stop on error
2398 eLazyBoolNo, // Don't echo commands
2399 eLazyBoolNo, // Don't print command output
2400 eLazyBoolNo, // Don't add the commands that are sourced into the history buffer
2402 SetBatchCommandMode (saved_batch);
2406 // nothing to be done if the file doesn't exist
2407 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2412 CommandInterpreter::GetPlatform (bool prefer_target_platform)
2414 PlatformSP platform_sp;
2415 if (prefer_target_platform)
2417 ExecutionContext exe_ctx(GetExecutionContext());
2418 Target *target = exe_ctx.GetTargetPtr();
2420 platform_sp = target->GetPlatform();
2424 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2429 CommandInterpreter::HandleCommands (const StringList &commands,
2430 ExecutionContext *override_context,
2431 bool stop_on_continue,
2435 LazyBool add_to_history,
2436 CommandReturnObject &result)
2438 size_t num_lines = commands.GetSize();
2440 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2441 // Make sure you reset this value anywhere you return from the function.
2443 bool old_async_execution = m_debugger.GetAsyncExecution();
2445 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2446 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2448 if (override_context != NULL)
2449 UpdateExecutionContext (override_context);
2451 if (!stop_on_continue)
2453 m_debugger.SetAsyncExecution (false);
2456 for (size_t idx = 0; idx < num_lines; idx++)
2458 const char *cmd = commands.GetStringAtIndex(idx);
2464 result.AppendMessageWithFormat ("%s %s\n",
2465 m_debugger.GetPrompt(),
2469 CommandReturnObject tmp_result;
2470 // If override_context is not NULL, pass no_context_switching = true for
2471 // HandleCommand() since we updated our context already.
2473 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2474 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here.
2475 if (!add_to_history)
2476 m_command_source_depth++;
2477 bool success = HandleCommand(cmd, add_to_history, tmp_result,
2478 NULL, /* override_context */
2479 true, /* repeat_on_empty_command */
2480 override_context != NULL /* no_context_switching */);
2481 if (!add_to_history)
2482 m_command_source_depth--;
2486 if (tmp_result.Succeeded())
2487 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
2490 if (!success || !tmp_result.Succeeded())
2492 const char *error_msg = tmp_result.GetErrorData();
2493 if (error_msg == NULL || error_msg[0] == '\0')
2494 error_msg = "<unknown error>.\n";
2497 result.AppendErrorWithFormat("Aborting reading of commands after command #%zu: '%s' failed with %s",
2498 idx, cmd, error_msg);
2499 result.SetStatus (eReturnStatusFailed);
2500 m_debugger.SetAsyncExecution (old_async_execution);
2503 else if (print_results)
2505 result.AppendMessageWithFormat ("Command #%zu '%s' failed with %s",
2512 if (result.GetImmediateOutputStream())
2513 result.GetImmediateOutputStream()->Flush();
2515 if (result.GetImmediateErrorStream())
2516 result.GetImmediateErrorStream()->Flush();
2518 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2519 // could be running (for instance in Breakpoint Commands.
2520 // So we check the return value to see if it is has running in it.
2521 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2522 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2524 if (stop_on_continue)
2526 // If we caused the target to proceed, and we're going to stop in that case, set the
2527 // status in our real result before returning. This is an error if the continue was not the
2528 // last command in the set of commands to be run.
2529 if (idx != num_lines - 1)
2530 result.AppendErrorWithFormat("Aborting reading of commands after command #%zu: '%s' continued the target.\n",
2533 result.AppendMessageWithFormat ("Command #%zu '%s' continued the target.\n", idx + 1, cmd);
2535 result.SetStatus(tmp_result.GetStatus());
2536 m_debugger.SetAsyncExecution (old_async_execution);
2544 result.SetStatus (eReturnStatusSuccessFinishResult);
2545 m_debugger.SetAsyncExecution (old_async_execution);
2550 // Make flags that we can pass into the IOHandler so our delegates can do the right thing
2552 eHandleCommandFlagStopOnContinue = (1u << 0),
2553 eHandleCommandFlagStopOnError = (1u << 1),
2554 eHandleCommandFlagEchoCommand = (1u << 2),
2555 eHandleCommandFlagPrintResult = (1u << 3)
2559 CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2560 ExecutionContext *context,
2561 LazyBool stop_on_continue,
2562 LazyBool stop_on_error,
2563 LazyBool echo_command,
2564 LazyBool print_result,
2565 LazyBool add_to_history,
2566 CommandReturnObject &result)
2568 if (cmd_file.Exists())
2570 StreamFileSP input_file_sp (new StreamFile());
2572 std::string cmd_file_path = cmd_file.GetPath();
2573 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2575 if (error.Success())
2577 Debugger &debugger = GetDebugger();
2581 if (stop_on_continue == eLazyBoolCalculate)
2583 if (m_command_source_flags.empty())
2585 // Stop on continue by default
2586 flags |= eHandleCommandFlagStopOnContinue;
2588 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2590 flags |= eHandleCommandFlagStopOnContinue;
2593 else if (stop_on_continue == eLazyBoolYes)
2595 flags |= eHandleCommandFlagStopOnContinue;
2598 if (stop_on_error == eLazyBoolCalculate)
2600 if (m_command_source_flags.empty())
2602 if (GetStopCmdSourceOnError())
2603 flags |= eHandleCommandFlagStopOnError;
2605 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2607 flags |= eHandleCommandFlagStopOnError;
2610 else if (stop_on_error == eLazyBoolYes)
2612 flags |= eHandleCommandFlagStopOnError;
2615 if (echo_command == eLazyBoolCalculate)
2617 if (m_command_source_flags.empty())
2619 // Echo command by default
2620 flags |= eHandleCommandFlagEchoCommand;
2622 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2624 flags |= eHandleCommandFlagEchoCommand;
2627 else if (echo_command == eLazyBoolYes)
2629 flags |= eHandleCommandFlagEchoCommand;
2632 if (print_result == eLazyBoolCalculate)
2634 if (m_command_source_flags.empty())
2636 // Print output by default
2637 flags |= eHandleCommandFlagPrintResult;
2639 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
2641 flags |= eHandleCommandFlagPrintResult;
2644 else if (print_result == eLazyBoolYes)
2646 flags |= eHandleCommandFlagPrintResult;
2649 if (flags & eHandleCommandFlagPrintResult)
2651 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
2654 // Used for inheriting the right settings when "command source" might have
2655 // nested "command source" commands
2656 lldb::StreamFileSP empty_stream_sp;
2657 m_command_source_flags.push_back(flags);
2658 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
2660 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2661 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
2663 NULL, // Pass in NULL for "editline_name" so no history is saved, or written
2664 debugger.GetPrompt(),
2665 false, // Not multi-line
2667 const bool old_async_execution = debugger.GetAsyncExecution();
2669 // Set synchronous execution if we not stopping when we continue
2670 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2671 debugger.SetAsyncExecution (false);
2673 m_command_source_depth++;
2675 debugger.RunIOHandler(io_handler_sp);
2676 if (!m_command_source_flags.empty())
2677 m_command_source_flags.pop_back();
2678 m_command_source_depth--;
2679 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2680 debugger.SetAsyncExecution (old_async_execution);
2684 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2685 result.SetStatus (eReturnStatusFailed);
2692 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2693 cmd_file.GetFilename().AsCString());
2694 result.SetStatus (eReturnStatusFailed);
2700 CommandInterpreter::GetScriptInterpreter (bool can_create)
2702 if (m_script_interpreter_ap.get() != NULL)
2703 return m_script_interpreter_ap.get();
2708 // <rdar://problem/11751427>
2709 // we need to protect the initialization of the script interpreter
2710 // otherwise we could end up with two threads both trying to create
2711 // their instance of it, and for some languages (e.g. Python)
2712 // this is a bulletproof recipe for disaster!
2713 // this needs to be a function-level static because multiple Debugger instances living in the same process
2714 // still need to be isolated and not try to initialize Python concurrently
2715 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2716 Mutex::Locker interpreter_lock(g_interpreter_mutex);
2718 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
2720 log->Printf("Initializing the ScriptInterpreter now\n");
2722 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2723 switch (script_lang)
2725 case eScriptLanguagePython:
2726 #ifndef LLDB_DISABLE_PYTHON
2727 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2730 // Fall through to the None case when python is disabled
2732 case eScriptLanguageNone:
2733 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2737 return m_script_interpreter_ap.get();
2743 CommandInterpreter::GetSynchronous ()
2745 return m_synchronous_execution;
2749 CommandInterpreter::SetSynchronous (bool value)
2751 m_synchronous_execution = value;
2755 CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2756 const char *word_text,
2757 const char *separator,
2758 const char *help_text,
2759 size_t max_word_len)
2761 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2763 int indent_size = max_word_len + strlen (separator) + 2;
2765 strm.IndentMore (indent_size);
2767 StreamString text_strm;
2768 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text);
2770 size_t len = text_strm.GetSize();
2771 const char *text = text_strm.GetData();
2772 if (text[len - 1] == '\n')
2775 len = text_strm.GetSize();
2778 if (len < max_columns)
2780 // Output it as a single line.
2781 strm.Printf ("%s", text);
2785 // We need to break it up into multiple lines.
2786 bool first_line = true;
2790 const size_t final_end = strlen (text);
2792 while (end < final_end)
2795 text_width = max_columns - 1;
2797 text_width = max_columns - indent_size - 1;
2799 // Don't start the 'text' on a space, since we're already outputting the indentation.
2802 while ((start < final_end) && (text[start] == ' '))
2806 end = start + text_width;
2807 if (end > final_end)
2811 // If we're not at the end of the text, make sure we break the line on white space.
2813 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2818 const size_t sub_len = end - start;
2825 assert (start <= final_end);
2826 assert (start + sub_len <= final_end);
2828 strm.Write (text + start, sub_len);
2833 strm.IndentLess(indent_size);
2837 CommandInterpreter::OutputHelpText (Stream &strm,
2838 const char *word_text,
2839 const char *separator,
2840 const char *help_text,
2841 uint32_t max_word_len)
2843 int indent_size = max_word_len + strlen (separator) + 2;
2845 strm.IndentMore (indent_size);
2847 StreamString text_strm;
2848 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2850 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2852 size_t len = text_strm.GetSize();
2853 const char *text = text_strm.GetData();
2855 uint32_t chars_left = max_columns;
2857 for (uint32_t i = 0; i < len; i++)
2859 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2861 chars_left = max_columns - indent_size;
2867 strm.PutChar(text[i]);
2874 strm.IndentLess(indent_size);
2878 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2879 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
2881 CommandObject::CommandMap::const_iterator pos;
2883 if (search_builtin_commands)
2885 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2887 const char *command_name = pos->first.c_str();
2888 CommandObject *cmd_obj = pos->second.get();
2890 if (cmd_obj->HelpTextContainsWord (search_word))
2892 commands_found.AppendString (command_name);
2893 commands_help.AppendString (cmd_obj->GetHelp());
2896 if (cmd_obj->IsMultiwordObject())
2897 cmd_obj->AproposAllSubCommands (command_name,
2905 if (search_user_commands)
2907 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
2909 const char *command_name = pos->first.c_str();
2910 CommandObject *cmd_obj = pos->second.get();
2912 if (cmd_obj->HelpTextContainsWord (search_word))
2914 commands_found.AppendString (command_name);
2915 commands_help.AppendString (cmd_obj->GetHelp());
2918 if (cmd_obj->IsMultiwordObject())
2919 cmd_obj->AproposAllSubCommands (command_name,
2929 CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2931 if (override_context != NULL)
2933 m_exe_ctx_ref = *override_context;
2937 const bool adopt_selected = true;
2938 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
2944 CommandInterpreter::GetProcessOutput ()
2946 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2947 char stdio_buffer[1024];
2949 size_t total_bytes = 0;
2951 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2954 ProcessSP process_sp (target_sp->GetProcessSP());
2957 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2959 size_t bytes_written = len;
2960 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
2963 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2965 size_t bytes_written = len;
2966 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
2975 CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
2977 const bool is_interactive = io_handler.GetIsInteractive();
2978 if (is_interactive == false)
2980 // When we are not interactive, don't execute blank lines. This will happen
2981 // sourcing a commands file. We don't want blank lines to repeat the previous
2982 // command and cause any errors to occur (like redefining an alias, get an error
2983 // and stop parsing the commands file).
2987 // When using a non-interactive file handle (like when sourcing commands from a file)
2988 // we need to echo the command out so we don't just see the command output and no
2990 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2991 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
2994 lldb_private::CommandReturnObject result;
2995 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2997 // Now emit the command output text from the command we just executed
2998 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
3000 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3001 GetProcessOutput ();
3003 if (!result.GetImmediateOutputStream())
3005 const char *output = result.GetOutputData();
3006 if (output && output[0])
3007 io_handler.GetOutputStreamFile()->PutCString(output);
3010 // Now emit the command error text from the command we just executed
3011 if (!result.GetImmediateErrorStream())
3013 const char *error = result.GetErrorData();
3014 if (error && error[0])
3015 io_handler.GetErrorStreamFile()->PutCString(error);
3019 switch (result.GetStatus())
3021 case eReturnStatusInvalid:
3022 case eReturnStatusSuccessFinishNoResult:
3023 case eReturnStatusSuccessFinishResult:
3024 case eReturnStatusStarted:
3027 case eReturnStatusSuccessContinuingNoResult:
3028 case eReturnStatusSuccessContinuingResult:
3029 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3030 io_handler.SetIsDone(true);
3033 case eReturnStatusFailed:
3034 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3035 io_handler.SetIsDone(true);
3038 case eReturnStatusQuit:
3039 io_handler.SetIsDone(true);
3045 CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3046 IOHandlerDelegate &delegate,
3047 bool asynchronously,
3050 Debugger &debugger = GetDebugger();
3051 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3052 "lldb", // Name of input reader for history
3054 true, // Get multiple lines
3055 delegate)); // IOHandlerDelegate
3059 io_handler_sp->SetUserData (baton);
3061 debugger.PushIOHandler(io_handler_sp);
3063 debugger.RunIOHandler(io_handler_sp);
3070 CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3071 IOHandlerDelegate &delegate,
3072 bool asynchronously,
3075 Debugger &debugger = GetDebugger();
3076 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3077 "lldb-python", // Name of input reader for history
3079 true, // Get multiple lines
3080 delegate)); // IOHandlerDelegate
3084 io_handler_sp->SetUserData (baton);
3086 debugger.PushIOHandler(io_handler_sp);
3088 debugger.RunIOHandler(io_handler_sp);
3094 CommandInterpreter::IsActive ()
3096 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3100 CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
3103 const bool multiple_lines = false; // Only get one line at a time
3104 if (!m_command_io_handler_sp)
3105 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3106 m_debugger.GetInputFile(),
3107 m_debugger.GetOutputFile(),
3108 m_debugger.GetErrorFile(),
3109 eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult,
3111 m_debugger.GetPrompt(),
3114 m_debugger.PushIOHandler(m_command_io_handler_sp);
3116 if (auto_handle_events)
3117 m_debugger.StartEventHandlerThread();
3121 m_debugger.StartIOHandlerThread();
3125 m_debugger.ExecuteIOHanders();
3127 if (auto_handle_events)
3128 m_debugger.StopEventHandlerThread();