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/CommandObjectHelp.h"
26 #include "../Commands/CommandObjectLog.h"
27 #include "../Commands/CommandObjectMemory.h"
28 #include "../Commands/CommandObjectPlatform.h"
29 #include "../Commands/CommandObjectPlugin.h"
30 #include "../Commands/CommandObjectProcess.h"
31 #include "../Commands/CommandObjectQuit.h"
32 #include "../Commands/CommandObjectRegister.h"
33 #include "../Commands/CommandObjectSettings.h"
34 #include "../Commands/CommandObjectSource.h"
35 #include "../Commands/CommandObjectCommands.h"
36 #include "../Commands/CommandObjectSyntax.h"
37 #include "../Commands/CommandObjectTarget.h"
38 #include "../Commands/CommandObjectThread.h"
39 #include "../Commands/CommandObjectType.h"
40 #include "../Commands/CommandObjectVersion.h"
41 #include "../Commands/CommandObjectWatchpoint.h"
44 #include "lldb/Core/Debugger.h"
45 #include "lldb/Core/InputReader.h"
46 #include "lldb/Core/Log.h"
47 #include "lldb/Core/Stream.h"
48 #include "lldb/Core/Timer.h"
50 #include "lldb/Host/Host.h"
52 #include "lldb/Interpreter/Args.h"
53 #include "lldb/Interpreter/CommandCompletions.h"
54 #include "lldb/Interpreter/CommandInterpreter.h"
55 #include "lldb/Interpreter/CommandReturnObject.h"
56 #include "lldb/Interpreter/Options.h"
57 #include "lldb/Interpreter/ScriptInterpreterNone.h"
58 #include "lldb/Interpreter/ScriptInterpreterPython.h"
61 #include "lldb/Target/Process.h"
62 #include "lldb/Target/Thread.h"
63 #include "lldb/Target/TargetList.h"
65 #include "lldb/Utility/CleanUp.h"
68 using namespace lldb_private;
71 static PropertyDefinition
74 { "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." },
75 { "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." },
76 { "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." },
77 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
82 ePropertyExpandRegexAliases = 0,
83 ePropertyPromptOnQuit = 1,
84 ePropertyStopCmdSourceOnError = 2
88 CommandInterpreter::GetStaticBroadcasterClass ()
90 static ConstString class_name ("lldb.commandInterpreter");
94 CommandInterpreter::CommandInterpreter
97 ScriptLanguage script_language,
98 bool synchronous_execution
100 Broadcaster (&debugger, "lldb.command-interpreter"),
101 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
102 m_debugger (debugger),
103 m_synchronous_execution (synchronous_execution),
104 m_skip_lldbinit_files (false),
105 m_skip_app_init_files (false),
106 m_script_interpreter_ap (),
107 m_comment_char ('#'),
108 m_batch_command_mode (false),
109 m_truncation_warning(eNoTruncation),
110 m_command_source_depth (0)
112 debugger.SetScriptLanguage (script_language);
113 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
114 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
115 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
116 CheckInWithManager ();
117 m_collection_sp->Initialize (g_properties);
121 CommandInterpreter::GetExpandRegexAliases () const
123 const uint32_t idx = ePropertyExpandRegexAliases;
124 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
128 CommandInterpreter::GetPromptOnQuit () const
130 const uint32_t idx = ePropertyPromptOnQuit;
131 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
135 CommandInterpreter::GetStopCmdSourceOnError () const
137 const uint32_t idx = ePropertyStopCmdSourceOnError;
138 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
142 CommandInterpreter::Initialize ()
144 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
146 CommandReturnObject result;
148 LoadCommandDictionary ();
150 // Set up some initial aliases.
151 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
154 AddAlias ("q", cmd_obj_sp);
155 AddAlias ("exit", cmd_obj_sp);
158 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
161 AddAlias ("attach", cmd_obj_sp);
164 cmd_obj_sp = GetCommandSPExact ("process detach",false);
167 AddAlias ("detach", cmd_obj_sp);
170 cmd_obj_sp = GetCommandSPExact ("process continue", false);
173 AddAlias ("c", cmd_obj_sp);
174 AddAlias ("continue", cmd_obj_sp);
177 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
179 AddAlias ("b", cmd_obj_sp);
181 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
183 AddAlias ("tbreak", cmd_obj_sp);
185 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
188 AddAlias ("stepi", cmd_obj_sp);
189 AddAlias ("si", cmd_obj_sp);
192 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
195 AddAlias ("nexti", cmd_obj_sp);
196 AddAlias ("ni", cmd_obj_sp);
199 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
202 AddAlias ("s", cmd_obj_sp);
203 AddAlias ("step", cmd_obj_sp);
206 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
209 AddAlias ("n", cmd_obj_sp);
210 AddAlias ("next", cmd_obj_sp);
213 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
216 AddAlias ("finish", cmd_obj_sp);
219 cmd_obj_sp = GetCommandSPExact ("frame select", false);
222 AddAlias ("f", cmd_obj_sp);
225 cmd_obj_sp = GetCommandSPExact ("thread select", false);
228 AddAlias ("t", cmd_obj_sp);
231 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
234 AddAlias ("j", cmd_obj_sp);
235 AddAlias ("jump", cmd_obj_sp);
238 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
241 AddAlias ("l", cmd_obj_sp);
242 AddAlias ("list", cmd_obj_sp);
245 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
248 AddAlias ("env", cmd_obj_sp);
251 cmd_obj_sp = GetCommandSPExact ("memory read", false);
253 AddAlias ("x", cmd_obj_sp);
255 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
257 AddAlias ("up", cmd_obj_sp);
259 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
261 AddAlias ("down", cmd_obj_sp);
263 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
265 AddAlias ("display", cmd_obj_sp);
267 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
269 AddAlias ("dis", cmd_obj_sp);
271 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
273 AddAlias ("di", cmd_obj_sp);
277 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
279 AddAlias ("undisplay", cmd_obj_sp);
281 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
283 AddAlias ("bt", cmd_obj_sp);
285 cmd_obj_sp = GetCommandSPExact ("target create", false);
287 AddAlias ("file", cmd_obj_sp);
289 cmd_obj_sp = GetCommandSPExact ("target modules", false);
291 AddAlias ("image", cmd_obj_sp);
294 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
296 cmd_obj_sp = GetCommandSPExact ("expression", false);
299 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
300 AddAlias ("p", cmd_obj_sp);
301 AddAlias ("print", cmd_obj_sp);
302 AddAlias ("call", cmd_obj_sp);
303 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
304 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
305 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
307 alias_arguments_vector_sp.reset (new OptionArgVector);
308 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
309 AddAlias ("po", cmd_obj_sp);
310 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
313 cmd_obj_sp = GetCommandSPExact ("process kill", false);
316 AddAlias ("kill", cmd_obj_sp);
319 cmd_obj_sp = GetCommandSPExact ("process launch", false);
322 alias_arguments_vector_sp.reset (new OptionArgVector);
323 #if defined (__arm__)
324 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
326 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=" LLDB_DEFAULT_SHELL " --", alias_arguments_vector_sp);
328 AddAlias ("r", cmd_obj_sp);
329 AddAlias ("run", cmd_obj_sp);
330 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
331 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
334 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
337 AddAlias ("add-dsym", cmd_obj_sp);
340 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
343 alias_arguments_vector_sp.reset (new OptionArgVector);
344 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
345 AddAlias ("rbreak", cmd_obj_sp);
346 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
351 CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
353 // This function has not yet been implemented.
355 // Look for any embedded script command
357 // get interpreter object from the command dictionary,
358 // call execute_one_command on it,
359 // get the results as a string,
360 // substitute that string for current stuff.
367 CommandInterpreter::LoadCommandDictionary ()
369 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
371 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
373 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
374 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
375 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
376 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
377 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
378 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
379 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
380 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
381 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
382 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
383 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
384 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
385 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
386 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
387 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
388 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
389 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
390 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
391 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
392 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
393 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
394 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
396 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
397 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
398 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
399 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
400 {"^(-.*)$", "breakpoint set %1"},
401 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
402 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
403 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
405 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
407 std::unique_ptr<CommandObjectRegexCommand>
408 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
410 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
411 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
413 CommandCompletions::eSymbolCompletion |
414 CommandCompletions::eSourceFileCompletion));
416 if (break_regex_cmd_ap.get())
419 for (size_t i = 0; i < num_regexes; i++)
421 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
425 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
429 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
430 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
434 std::unique_ptr<CommandObjectRegexCommand>
435 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
437 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
438 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
440 CommandCompletions::eSymbolCompletion |
441 CommandCompletions::eSourceFileCompletion));
443 if (tbreak_regex_cmd_ap.get())
446 for (size_t i = 0; i < num_regexes; i++)
448 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
450 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
451 assert (num_printed < 1024);
452 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
456 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
460 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
461 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
465 std::unique_ptr<CommandObjectRegexCommand>
466 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
468 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
469 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
471 if (attach_regex_cmd_ap.get())
473 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
474 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
475 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
476 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
478 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
479 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
483 std::unique_ptr<CommandObjectRegexCommand>
484 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
486 "Go down \"n\" frames in the stack (1 frame by default).",
487 "_regexp-down [n]", 2));
488 if (down_regex_cmd_ap.get())
490 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
491 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
493 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
494 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
498 std::unique_ptr<CommandObjectRegexCommand>
499 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
501 "Go up \"n\" frames in the stack (1 frame by default).",
502 "_regexp-up [n]", 2));
503 if (up_regex_cmd_ap.get())
505 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
506 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
508 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
509 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
513 std::unique_ptr<CommandObjectRegexCommand>
514 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
516 "Add an expression evaluation stop-hook.",
517 "_regexp-display expression", 2));
518 if (display_regex_cmd_ap.get())
520 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
522 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
523 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
527 std::unique_ptr<CommandObjectRegexCommand>
528 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
530 "Remove an expression evaluation stop-hook.",
531 "_regexp-undisplay stop-hook-number", 2));
532 if (undisplay_regex_cmd_ap.get())
534 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
536 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
537 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
541 std::unique_ptr<CommandObjectRegexCommand>
542 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
544 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
545 "gdb-remote [<hostname>:]<portnum>", 2));
546 if (connect_gdb_remote_cmd_ap.get())
548 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
549 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
551 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
552 m_command_dict[command_sp->GetCommandName ()] = command_sp;
556 std::unique_ptr<CommandObjectRegexCommand>
557 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
559 "Connect to a remote KDP server. udp port 41139 is the default port number.",
560 "kdp-remote <hostname>[:<portnum>]", 2));
561 if (connect_kdp_remote_cmd_ap.get())
563 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
564 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
566 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
567 m_command_dict[command_sp->GetCommandName ()] = command_sp;
571 std::unique_ptr<CommandObjectRegexCommand>
572 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
574 "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.",
575 "bt [<digit>|all]", 2));
576 if (bt_regex_cmd_ap.get())
578 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
579 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
580 // so now "bt 3" is the preferred form, in line with gdb.
581 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
582 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
583 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
584 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
586 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
587 m_command_dict[command_sp->GetCommandName ()] = command_sp;
591 std::unique_ptr<CommandObjectRegexCommand>
592 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
594 "Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the appropriate 'source list' commands.",
595 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
597 CommandCompletions::eSourceFileCompletion));
598 if (list_regex_cmd_ap.get())
600 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
601 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
602 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
603 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
604 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
605 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
606 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
608 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
609 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
613 std::unique_ptr<CommandObjectRegexCommand>
614 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
616 "Implements a shortcut to viewing and setting environment variables.",
617 "_regexp-env\n_regexp-env FOO=BAR", 2));
618 if (env_regex_cmd_ap.get())
620 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
621 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
623 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
624 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
628 std::unique_ptr<CommandObjectRegexCommand>
629 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
631 "Sets the program counter to a new address.",
632 "_regexp-jump [<line>]\n"
633 "_regexp-jump [<+-lineoffset>]\n"
634 "_regexp-jump [<file>:<line>]\n"
635 "_regexp-jump [*<addr>]\n", 2));
636 if (jump_regex_cmd_ap.get())
638 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
639 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
640 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
641 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
643 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
644 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
651 CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
654 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
658 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
661 return matches.GetSize();
665 CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
667 CommandObject::CommandMap::iterator pos;
668 CommandObjectSP command_sp;
670 std::string cmd(cmd_cstr);
674 pos = m_command_dict.find(cmd);
675 if (pos != m_command_dict.end())
676 command_sp = pos->second;
679 if (include_aliases && HasAliases())
681 pos = m_alias_dict.find(cmd);
682 if (pos != m_alias_dict.end())
683 command_sp = pos->second;
686 if (HasUserCommands())
688 pos = m_user_dict.find(cmd);
689 if (pos != m_user_dict.end())
690 command_sp = pos->second;
693 if (!exact && !command_sp)
695 // We will only get into here if we didn't find any exact matches.
697 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
699 StringList local_matches;
701 matches = &local_matches;
703 unsigned int num_cmd_matches = 0;
704 unsigned int num_alias_matches = 0;
705 unsigned int num_user_matches = 0;
707 // Look through the command dictionaries one by one, and if we get only one match from any of
708 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
712 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
715 if (num_cmd_matches == 1)
717 cmd.assign(matches->GetStringAtIndex(0));
718 pos = m_command_dict.find(cmd);
719 if (pos != m_command_dict.end())
720 real_match_sp = pos->second;
723 if (include_aliases && HasAliases())
725 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
729 if (num_alias_matches == 1)
731 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
732 pos = m_alias_dict.find(cmd);
733 if (pos != m_alias_dict.end())
734 alias_match_sp = pos->second;
737 if (HasUserCommands())
739 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
742 if (num_user_matches == 1)
744 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
746 pos = m_user_dict.find (cmd);
747 if (pos != m_user_dict.end())
748 user_match_sp = pos->second;
751 // If we got exactly one match, return that, otherwise return the match list.
753 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
756 return real_match_sp;
757 else if (num_alias_matches)
758 return alias_match_sp;
760 return user_match_sp;
763 else if (matches && command_sp)
765 matches->AppendString (cmd_cstr);
773 CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
777 std::string name_sstr(name);
778 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
779 if (found && !can_replace)
781 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
783 m_command_dict[name_sstr] = cmd_sp;
790 CommandInterpreter::AddUserCommand (std::string name,
791 const lldb::CommandObjectSP &cmd_sp,
797 const char* name_cstr = name.c_str();
799 // do not allow replacement of internal commands
800 if (CommandExists(name_cstr))
802 if (can_replace == false)
804 if (m_command_dict[name]->IsRemovable() == false)
808 if (UserCommandExists(name_cstr))
810 if (can_replace == false)
812 if (m_user_dict[name]->IsRemovable() == false)
816 m_user_dict[name] = cmd_sp;
823 CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
825 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
826 CommandObjectSP ret_val; // Possibly empty return value.
828 if (cmd_cstr == NULL)
831 if (cmd_words.GetArgumentCount() == 1)
832 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
835 // We have a multi-word command (seemingly), so we need to do more work.
836 // First, get the cmd_obj_sp for the first word in the command.
837 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
838 if (cmd_obj_sp.get() != NULL)
840 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
841 // command name), and find the appropriate sub-command SP for each command word....
842 size_t end = cmd_words.GetArgumentCount();
843 for (size_t j= 1; j < end; ++j)
845 if (cmd_obj_sp->IsMultiwordObject())
847 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
848 if (cmd_obj_sp.get() == NULL)
849 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
853 // We have more words in the command name, but we don't have a multiword object. Fail and return
857 // We successfully looped through all the command words and got valid command objects for them. Assign the
858 // last object retrieved to 'ret_val'.
859 ret_val = cmd_obj_sp;
866 CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
868 return GetCommandSPExact (cmd_cstr, include_aliases).get();
872 CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
874 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
876 // If we didn't find an exact match to the command string in the commands, look in
882 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
887 // If there wasn't an exact match then look for an inexact one in just the commands
888 command_obj = GetCommandSP(cmd_cstr, false, false, NULL).get();
890 // Finally, if there wasn't an inexact match among the commands, look for an inexact
891 // match in both the commands and aliases.
896 matches->AppendString(command_obj->GetCommandName());
900 return GetCommandSP(cmd_cstr, true, false, matches).get();
904 CommandInterpreter::CommandExists (const char *cmd)
906 return m_command_dict.find(cmd) != m_command_dict.end();
910 CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
911 const char *options_args,
912 OptionArgVectorSP &option_arg_vector_sp)
915 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
917 if (!options_args || (strlen (options_args) < 1))
920 std::string options_string (options_args);
921 Args args (options_args);
922 CommandReturnObject result;
923 // Check to see if the command being aliased can take any command options.
924 Options *options = cmd_obj_sp->GetOptions ();
927 // See if any options were specified as part of the alias; if so, handle them appropriately.
928 options->NotifyOptionParsingStarting ();
929 args.Unshift ("dummy_arg");
930 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
932 if (result.Succeeded())
933 options->VerifyPartialOptions (result);
934 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
936 result.AppendError ("Unable to create requested alias.\n");
941 if (!options_string.empty())
943 if (cmd_obj_sp->WantsRawCommandString ())
944 option_arg_vector->push_back (OptionArgPair ("<argument>",
949 const size_t argc = args.GetArgumentCount();
950 for (size_t i = 0; i < argc; ++i)
951 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
952 option_arg_vector->push_back
953 (OptionArgPair ("<argument>",
955 std::string (args.GetArgumentAtIndex (i)))));
963 CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
965 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
968 full_name.assign(cmd);
974 size_t num_alias_matches;
975 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
976 if (num_alias_matches == 1)
978 // Make sure this isn't shadowing a command in the regular command space:
979 StringList regular_matches;
980 const bool include_aliases = false;
981 const bool exact = false;
982 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, ®ular_matches));
983 if (cmd_obj_sp || regular_matches.GetSize() > 0)
987 full_name.assign (matches.GetStringAtIndex(0));
997 CommandInterpreter::AliasExists (const char *cmd)
999 return m_alias_dict.find(cmd) != m_alias_dict.end();
1003 CommandInterpreter::UserCommandExists (const char *cmd)
1005 return m_user_dict.find(cmd) != m_user_dict.end();
1009 CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1011 command_obj_sp->SetIsAlias (true);
1012 m_alias_dict[alias_name] = command_obj_sp;
1016 CommandInterpreter::RemoveAlias (const char *alias_name)
1018 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1019 if (pos != m_alias_dict.end())
1021 m_alias_dict.erase(pos);
1027 CommandInterpreter::RemoveUser (const char *alias_name)
1029 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1030 if (pos != m_user_dict.end())
1032 m_user_dict.erase(pos);
1039 CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1041 help_string.Printf ("'%s", command_name);
1042 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1044 if (option_arg_vector_sp)
1046 OptionArgVector *options = option_arg_vector_sp.get();
1047 for (size_t i = 0; i < options->size(); ++i)
1049 OptionArgPair cur_option = (*options)[i];
1050 std::string opt = cur_option.first;
1051 OptionArgValue value_pair = cur_option.second;
1052 std::string value = value_pair.second;
1053 if (opt.compare("<argument>") == 0)
1055 help_string.Printf (" %s", value.c_str());
1059 help_string.Printf (" %s", opt.c_str());
1060 if ((value.compare ("<no-argument>") != 0)
1061 && (value.compare ("<need-argument") != 0))
1063 help_string.Printf (" %s", value.c_str());
1069 help_string.Printf ("'");
1073 CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1075 CommandObject::CommandMap::const_iterator pos;
1076 CommandObject::CommandMap::const_iterator end = dict.end();
1079 for (pos = dict.begin(); pos != end; ++pos)
1081 size_t len = pos->first.size();
1089 CommandInterpreter::GetHelp (CommandReturnObject &result,
1092 CommandObject::CommandMap::const_iterator pos;
1093 size_t max_len = FindLongestCommandWord (m_command_dict);
1095 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
1098 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
1099 result.AppendMessage("");
1101 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1103 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1106 result.AppendMessage("");
1110 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
1112 result.AppendMessage("The following is a list of your current command abbreviations "
1113 "(see 'help command alias' for more info):");
1114 result.AppendMessage("");
1115 max_len = FindLongestCommandWord (m_alias_dict);
1117 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1120 StreamString translation_and_help;
1121 std::string entry_name = pos->first;
1122 std::string second_entry = pos->second.get()->GetCommandName();
1123 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1125 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1126 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1127 translation_and_help.GetData(), max_len);
1129 result.AppendMessage("");
1132 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
1134 result.AppendMessage ("The following is a list of your current user-defined commands:");
1135 result.AppendMessage("");
1136 max_len = FindLongestCommandWord (m_user_dict);
1137 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1139 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1142 result.AppendMessage("");
1145 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1149 CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
1151 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1152 // eventually be invoked by the given command line.
1154 CommandObject *cmd_obj = NULL;
1155 std::string white_space (" \t\v");
1156 size_t start = command_string.find_first_not_of (white_space);
1161 if (start != std::string::npos)
1163 // Get the next word from command_string.
1164 end = command_string.find_first_of (white_space, start);
1165 if (end == std::string::npos)
1166 end = command_string.size();
1167 std::string cmd_word = command_string.substr (start, end - start);
1169 if (cmd_obj == NULL)
1170 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1171 // command or alias.
1172 cmd_obj = GetCommandObject (cmd_word.c_str());
1173 else if (cmd_obj->IsMultiwordObject ())
1175 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
1176 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
1178 cmd_obj = sub_cmd_obj;
1179 else // cmd_word was not a valid sub-command word, so we are donee
1183 // We have a cmd_obj and it is not a multi-word object, so we are done.
1186 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1187 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1190 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1193 start = command_string.find_first_not_of (white_space, end);
1196 // Unable to find any more words.
1200 if (end == command_string.size())
1201 command_string.clear();
1203 command_string = command_string.substr(end);
1208 static const char *k_white_space = " \t\v";
1209 static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1211 StripLeadingSpaces (std::string &s)
1215 size_t pos = s.find_first_not_of (k_white_space);
1216 if (pos == std::string::npos)
1225 FindArgumentTerminator (const std::string &s)
1227 const size_t s_len = s.size();
1229 while (offset < s_len)
1231 size_t pos = s.find ("--", offset);
1232 if (pos == std::string::npos)
1236 if (isspace(s[pos-1]))
1238 // Check if the string ends "\s--" (where \s is a space character)
1239 // or if we have "\s--\s".
1240 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1248 return std::string::npos;
1252 ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char "e_char)
1256 StripLeadingSpaces (command_string);
1258 bool result = false;
1261 if (!command_string.empty())
1263 const char first_char = command_string[0];
1264 if (first_char == '\'' || first_char == '"')
1266 quote_char = first_char;
1267 const size_t end_quote_pos = command_string.find (quote_char, 1);
1268 if (end_quote_pos == std::string::npos)
1270 command.swap (command_string);
1271 command_string.erase ();
1275 command.assign (command_string, 1, end_quote_pos - 1);
1276 if (end_quote_pos + 1 < command_string.size())
1277 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1279 command_string.erase ();
1284 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1285 if (first_space_pos == std::string::npos)
1287 command.swap (command_string);
1288 command_string.erase();
1292 command.assign (command_string, 0, first_space_pos);
1293 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
1300 if (!command.empty())
1302 // actual commands can't start with '-' or '_'
1303 if (command[0] != '-' && command[0] != '_')
1305 size_t pos = command.find_first_not_of(k_valid_command_chars);
1306 if (pos > 0 && pos != std::string::npos)
1308 suffix.assign (command.begin() + pos, command.end());
1309 command.erase (pos);
1318 CommandInterpreter::BuildAliasResult (const char *alias_name,
1319 std::string &raw_input_string,
1320 std::string &alias_result,
1321 CommandReturnObject &result)
1323 CommandObject *alias_cmd_obj = NULL;
1324 Args cmd_args (raw_input_string.c_str());
1325 alias_cmd_obj = GetCommandObject (alias_name);
1326 StreamString result_str;
1330 std::string alias_name_str = alias_name;
1331 if ((cmd_args.GetArgumentCount() == 0)
1332 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1333 cmd_args.Unshift (alias_name);
1335 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1336 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1338 if (option_arg_vector_sp.get())
1340 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1342 for (size_t i = 0; i < option_arg_vector->size(); ++i)
1344 OptionArgPair option_pair = (*option_arg_vector)[i];
1345 OptionArgValue value_pair = option_pair.second;
1346 int value_type = value_pair.first;
1347 std::string option = option_pair.first;
1348 std::string value = value_pair.second;
1349 if (option.compare ("<argument>") == 0)
1350 result_str.Printf (" %s", value.c_str());
1353 result_str.Printf (" %s", option.c_str());
1354 if (value_type != OptionParser::eOptionalArgument)
1355 result_str.Printf (" ");
1356 if (value.compare ("<OptionParser::eNoArgument>") != 0)
1358 int index = GetOptionArgumentPosition (value.c_str());
1360 result_str.Printf ("%s", value.c_str());
1361 else if (index >= cmd_args.GetArgumentCount())
1364 result.AppendErrorWithFormat
1365 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1367 result.SetStatus (eReturnStatusFailed);
1368 return alias_cmd_obj;
1372 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1373 if (strpos != std::string::npos)
1374 raw_input_string = raw_input_string.erase (strpos,
1375 strlen (cmd_args.GetArgumentAtIndex (index)));
1376 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1383 alias_result = result_str.GetData();
1385 return alias_cmd_obj;
1389 CommandInterpreter::PreprocessCommand (std::string &command)
1391 // The command preprocessor needs to do things to the command
1392 // line before any parsing of arguments or anything else is done.
1393 // The only current stuff that gets proprocessed is anyting enclosed
1394 // in backtick ('`') characters is evaluated as an expression and
1395 // the result of the expression must be a scalar that can be substituted
1396 // into the command. An example would be:
1397 // (lldb) memory read `$rsp + 20`
1398 Error error; // Error for any expressions that might not evaluate
1399 size_t start_backtick;
1401 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1403 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1405 // The backtick was preceeded by a '\' character, remove the slash
1406 // and don't treat the backtick as the start of an expression
1407 command.erase(start_backtick-1, 1);
1408 // No need to add one to start_backtick since we just deleted a char
1409 pos = start_backtick;
1413 const size_t expr_content_start = start_backtick + 1;
1414 const size_t end_backtick = command.find ('`', expr_content_start);
1415 if (end_backtick == std::string::npos)
1417 else if (end_backtick == expr_content_start)
1419 // Empty expression (two backticks in a row)
1420 command.erase (start_backtick, 2);
1424 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1426 ExecutionContext exe_ctx(GetExecutionContext());
1427 Target *target = exe_ctx.GetTargetPtr();
1428 // Get a dummy target to allow for calculator mode while processing backticks.
1429 // This also helps break the infinite loop caused when target is null.
1431 target = Host::GetDummyTarget(GetDebugger()).get();
1434 ValueObjectSP expr_result_valobj_sp;
1436 EvaluateExpressionOptions options;
1437 options.SetCoerceToId(false);
1438 options.SetUnwindOnError(true);
1439 options.SetIgnoreBreakpoints(true);
1440 options.SetKeepInMemory(false);
1441 options.SetTryAllThreads(true);
1442 options.SetTimeoutUsec(0);
1444 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1445 exe_ctx.GetFramePtr(),
1446 expr_result_valobj_sp,
1449 if (expr_result == eExecutionCompleted)
1452 if (expr_result_valobj_sp->ResolveValue (scalar))
1454 command.erase (start_backtick, end_backtick - start_backtick + 1);
1455 StreamString value_strm;
1456 const bool show_type = false;
1457 scalar.GetValue (&value_strm, show_type);
1458 size_t value_string_size = value_strm.GetSize();
1459 if (value_string_size)
1461 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1462 pos = start_backtick + value_string_size;
1467 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1472 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1477 if (expr_result_valobj_sp)
1478 error = expr_result_valobj_sp->GetError();
1479 if (error.Success())
1482 switch (expr_result)
1484 case eExecutionSetupError:
1485 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1487 case eExecutionCompleted:
1489 case eExecutionDiscarded:
1490 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1492 case eExecutionInterrupted:
1493 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1495 case eExecutionHitBreakpoint:
1496 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1498 case eExecutionTimedOut:
1499 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1501 case eExecutionStoppedForDebug:
1502 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1518 CommandInterpreter::HandleCommand (const char *command_line,
1519 LazyBool lazy_add_to_history,
1520 CommandReturnObject &result,
1521 ExecutionContext *override_context,
1522 bool repeat_on_empty_command,
1523 bool no_context_switching)
1528 CommandObject *cmd_obj = NULL;
1529 bool wants_raw_input = false;
1530 std::string command_string (command_line);
1531 std::string original_command_string (command_line);
1533 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
1534 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1536 // Make a scoped cleanup object that will clear the crash description string
1537 // on exit of this function.
1538 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
1541 log->Printf ("Processing command: %s", command_line);
1543 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1545 if (!no_context_switching)
1546 UpdateExecutionContext (override_context);
1548 bool add_to_history;
1549 if (lazy_add_to_history == eLazyBoolCalculate)
1550 add_to_history = (m_command_source_depth == 0);
1552 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1554 bool empty_command = false;
1555 bool comment_command = false;
1556 if (command_string.empty())
1557 empty_command = true;
1560 const char *k_space_characters = "\t\n\v\f\r ";
1562 size_t non_space = command_string.find_first_not_of (k_space_characters);
1563 // Check for empty line or comment line (lines whose first
1564 // non-space character is the comment character for this interpreter)
1565 if (non_space == std::string::npos)
1566 empty_command = true;
1567 else if (command_string[non_space] == m_comment_char)
1568 comment_command = true;
1569 else if (command_string[non_space] == CommandHistory::g_repeat_char)
1571 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
1572 if (history_string == NULL)
1574 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1575 result.SetStatus(eReturnStatusFailed);
1578 add_to_history = false;
1579 command_string = history_string;
1580 original_command_string = history_string;
1586 if (repeat_on_empty_command)
1588 if (m_command_history.IsEmpty())
1590 result.AppendError ("empty command");
1591 result.SetStatus(eReturnStatusFailed);
1596 command_line = m_repeat_command.c_str();
1597 command_string = command_line;
1598 original_command_string = command_line;
1599 if (m_repeat_command.empty())
1601 result.AppendErrorWithFormat("No auto repeat.\n");
1602 result.SetStatus (eReturnStatusFailed);
1606 add_to_history = false;
1610 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1614 else if (comment_command)
1616 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1621 Error error (PreprocessCommand (command_string));
1625 result.AppendError (error.AsCString());
1626 result.SetStatus(eReturnStatusFailed);
1631 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1632 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1633 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1634 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1635 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
1636 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
1637 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
1639 StreamString revised_command_line;
1640 size_t actual_cmd_name_len = 0;
1641 std::string next_word;
1645 char quote_char = '\0';
1647 ExtractCommand (command_string, next_word, suffix, quote_char);
1648 if (cmd_obj == NULL)
1650 std::string full_name;
1651 if (GetAliasFullName(next_word.c_str(), full_name))
1653 std::string alias_result;
1654 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
1655 revised_command_line.Printf ("%s", alias_result.c_str());
1658 wants_raw_input = cmd_obj->WantsRawCommandString ();
1659 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1664 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
1667 actual_cmd_name_len += next_word.length();
1668 revised_command_line.Printf ("%s", next_word.c_str());
1669 wants_raw_input = cmd_obj->WantsRawCommandString ();
1673 revised_command_line.Printf ("%s", next_word.c_str());
1679 if (cmd_obj->IsMultiwordObject ())
1681 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
1684 actual_cmd_name_len += next_word.length() + 1;
1685 revised_command_line.Printf (" %s", next_word.c_str());
1686 cmd_obj = sub_cmd_obj;
1687 wants_raw_input = cmd_obj->WantsRawCommandString ();
1692 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1694 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1701 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1703 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1708 if (cmd_obj == NULL)
1710 const size_t num_matches = matches.GetSize();
1711 if (matches.GetSize() > 1) {
1712 StreamString error_msg;
1713 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
1715 for (uint32_t i = 0; i < num_matches; ++i) {
1716 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
1718 result.AppendRawError (error_msg.GetString().c_str());
1720 // We didn't have only one match, otherwise we wouldn't get here.
1721 assert(num_matches == 0);
1722 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1724 result.SetStatus (eReturnStatusFailed);
1728 if (cmd_obj->IsMultiwordObject ())
1730 if (!suffix.empty())
1733 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1734 cmd_obj->GetCommandName(),
1735 next_word.empty() ? "" : next_word.c_str(),
1736 next_word.empty() ? " -- " : " ",
1738 result.SetStatus (eReturnStatusFailed);
1744 // If we found a normal command, we are done
1746 if (!suffix.empty())
1751 // GDB format suffixes
1753 Options *command_options = cmd_obj->GetOptions();
1754 if (command_options && command_options->SupportsLongOption("gdb-format"))
1756 std::string gdb_format_option ("--gdb-format=");
1757 gdb_format_option += (suffix.c_str() + 1);
1759 bool inserted = false;
1760 std::string &cmd = revised_command_line.GetString();
1761 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1762 if (arg_terminator_idx != std::string::npos)
1764 // Insert the gdb format option before the "--" that terminates options
1765 gdb_format_option.append(1,' ');
1766 cmd.insert(arg_terminator_idx, gdb_format_option);
1771 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1773 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1774 revised_command_line.PutCString (" --");
1778 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1779 cmd_obj->GetCommandName());
1780 result.SetStatus (eReturnStatusFailed);
1787 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1789 result.SetStatus (eReturnStatusFailed);
1795 if (command_string.length() == 0)
1800 if (!command_string.empty())
1801 revised_command_line.Printf (" %s", command_string.c_str());
1804 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1805 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1806 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1807 // wants_raw_input specifies whether the Execute method expects raw input or not.
1812 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1813 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1814 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1818 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1819 // CommandObject, with the appropriate arguments.
1821 if (cmd_obj != NULL)
1825 Args command_args (revised_command_line.GetData());
1826 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1827 if (repeat_command != NULL)
1828 m_repeat_command.assign(repeat_command);
1830 m_repeat_command.assign(original_command_string.c_str());
1832 m_command_history.AppendString (original_command_string);
1835 command_string = revised_command_line.GetData();
1836 std::string command_name (cmd_obj->GetCommandName());
1837 std::string remainder;
1838 if (actual_cmd_name_len < command_string.length())
1839 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1840 // than cmd_obj->GetCommandName(), because name completion
1841 // allows users to enter short versions of the names,
1842 // e.g. 'br s' for 'breakpoint set'.
1844 // Remove any initial spaces
1845 std::string white_space (" \t\v");
1846 size_t pos = remainder.find_first_not_of (white_space);
1847 if (pos != 0 && pos != std::string::npos)
1848 remainder.erase(0, pos);
1851 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
1853 cmd_obj->Execute (remainder.c_str(), result);
1857 // We didn't find the first command object, so complete the first argument.
1858 Args command_args (revised_command_line.GetData());
1861 int cursor_index = 0;
1862 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1864 num_matches = HandleCompletionMatches (command_args,
1866 cursor_char_position,
1872 if (num_matches > 0)
1874 std::string error_msg;
1875 error_msg.assign ("ambiguous command '");
1876 error_msg.append(command_args.GetArgumentAtIndex(0));
1877 error_msg.append ("'.");
1879 error_msg.append (" Possible completions:");
1880 for (int i = 0; i < num_matches; i++)
1882 error_msg.append ("\n\t");
1883 error_msg.append (matches.GetStringAtIndex (i));
1885 error_msg.append ("\n");
1886 result.AppendRawError (error_msg.c_str());
1889 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1891 result.SetStatus (eReturnStatusFailed);
1895 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1897 return result.Succeeded();
1901 CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1903 int &cursor_char_position,
1904 int match_start_point,
1905 int max_return_elements,
1906 bool &word_complete,
1907 StringList &matches)
1909 int num_command_matches = 0;
1910 bool look_for_subcommand = false;
1912 // For any of the command completions a unique match will be a complete word.
1913 word_complete = true;
1915 if (cursor_index == -1)
1917 // We got nothing on the command line, so return the list of commands
1918 bool include_aliases = true;
1919 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1921 else if (cursor_index == 0)
1923 // The cursor is in the first argument, so just do a lookup in the dictionary.
1924 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
1925 num_command_matches = matches.GetSize();
1927 if (num_command_matches == 1
1928 && cmd_obj && cmd_obj->IsMultiwordObject()
1929 && matches.GetStringAtIndex(0) != NULL
1930 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1932 look_for_subcommand = true;
1933 num_command_matches = 0;
1934 matches.DeleteStringAtIndex(0);
1935 parsed_line.AppendArgument ("");
1937 cursor_char_position = 0;
1941 if (cursor_index > 0 || look_for_subcommand)
1943 // We are completing further on into a commands arguments, so find the command and tell it
1944 // to complete the command.
1945 // First see if there is a matching initial command:
1946 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
1947 if (command_object == NULL)
1953 parsed_line.Shift();
1955 num_command_matches = command_object->HandleCompletion (parsed_line,
1957 cursor_char_position,
1959 max_return_elements,
1965 return num_command_matches;
1970 CommandInterpreter::HandleCompletion (const char *current_line,
1972 const char *last_char,
1973 int match_start_point,
1974 int max_return_elements,
1975 StringList &matches)
1977 // We parse the argument up to the cursor, so the last argument in parsed_line is
1978 // the one containing the cursor, and the cursor is after the last character.
1980 Args parsed_line(current_line, last_char - current_line);
1981 Args partial_parsed_line(current_line, cursor - current_line);
1983 // Don't complete comments, and if the line we are completing is just the history repeat character,
1984 // substitute the appropriate history line.
1985 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1988 if (first_arg[0] == m_comment_char)
1990 else if (first_arg[0] == CommandHistory::g_repeat_char)
1992 const char *history_string = m_command_history.FindString (first_arg);
1993 if (history_string != NULL)
1996 matches.InsertStringAtIndex(0, history_string);
2006 int num_args = partial_parsed_line.GetArgumentCount();
2007 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2008 int cursor_char_position;
2010 if (cursor_index == -1)
2011 cursor_char_position = 0;
2013 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
2015 if (cursor > current_line && cursor[-1] == ' ')
2017 // We are just after a space. If we are in an argument, then we will continue
2018 // parsing, but if we are between arguments, then we have to complete whatever the next
2019 // element would be.
2020 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2021 // protected by a quote) then the space will also be in the parsed argument...
2023 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2024 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2026 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
2028 cursor_char_position = 0;
2032 int num_command_matches;
2036 // Only max_return_elements == -1 is supported at present:
2037 assert (max_return_elements == -1);
2039 num_command_matches = HandleCompletionMatches (parsed_line,
2041 cursor_char_position,
2043 max_return_elements,
2047 if (num_command_matches <= 0)
2048 return num_command_matches;
2052 // If we got an empty string, insert nothing.
2053 matches.InsertStringAtIndex(0, "");
2057 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2058 // put an empty string in element 0.
2059 std::string command_partial_str;
2060 if (cursor_index >= 0)
2061 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2062 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
2064 std::string common_prefix;
2065 matches.LongestCommonPrefix (common_prefix);
2066 const size_t partial_name_len = command_partial_str.size();
2068 // If we matched a unique single command, add a space...
2069 // Only do this if the completer told us this was a complete word, however...
2070 if (num_command_matches == 1 && word_complete)
2072 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2073 if (quote_char != '\0')
2074 common_prefix.push_back(quote_char);
2076 common_prefix.push_back(' ');
2078 common_prefix.erase (0, partial_name_len);
2079 matches.InsertStringAtIndex(0, common_prefix.c_str());
2081 return num_command_matches;
2085 CommandInterpreter::~CommandInterpreter ()
2090 CommandInterpreter::GetPrompt ()
2092 return m_debugger.GetPrompt();
2096 CommandInterpreter::SetPrompt (const char *new_prompt)
2098 m_debugger.SetPrompt (new_prompt);
2102 CommandInterpreter::GetConfirmationInputReaderCallback
2105 InputReader &reader,
2106 lldb::InputReaderAction action,
2111 File &out_file = reader.GetDebugger().GetOutputFile();
2112 bool *response_ptr = (bool *) baton;
2116 case eInputReaderActivate:
2117 if (out_file.IsValid())
2119 if (reader.GetPrompt())
2121 out_file.Printf ("%s", reader.GetPrompt());
2127 case eInputReaderDeactivate:
2130 case eInputReaderReactivate:
2131 if (out_file.IsValid() && reader.GetPrompt())
2133 out_file.Printf ("%s", reader.GetPrompt());
2138 case eInputReaderAsynchronousOutputWritten:
2141 case eInputReaderGotToken:
2144 reader.SetIsDone(true);
2146 else if (bytes[0] == 'y' || bytes[0] == 'Y')
2148 *response_ptr = true;
2149 reader.SetIsDone(true);
2151 else if (bytes[0] == 'n' || bytes[0] == 'N')
2153 *response_ptr = false;
2154 reader.SetIsDone(true);
2158 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
2160 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
2166 case eInputReaderInterrupt:
2167 case eInputReaderEndOfFile:
2168 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2169 reader.SetIsDone (true);
2172 case eInputReaderDone:
2181 CommandInterpreter::Confirm (const char *message, bool default_answer)
2183 // Check AutoConfirm first:
2184 if (m_debugger.GetAutoConfirm())
2185 return default_answer;
2187 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2188 bool response = default_answer;
2191 std::string prompt(message);
2192 prompt.append(": [");
2194 prompt.append ("Y/n] ");
2196 prompt.append ("y/N] ");
2198 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2200 eInputReaderGranularityLine, // token size, to pass to callback function
2202 prompt.c_str(), // prompt
2203 true)); // echo input
2206 GetDebugger().PushInputReader (reader_sp);
2208 reader_sp->WaitOnReaderIsDone();
2214 CommandInterpreter::GetAliasOptions (const char *alias_name)
2216 OptionArgMap::iterator pos;
2217 OptionArgVectorSP ret_val;
2219 std::string alias (alias_name);
2221 if (HasAliasOptions())
2223 pos = m_alias_options.find (alias);
2224 if (pos != m_alias_options.end())
2225 ret_val = pos->second;
2232 CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2234 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2235 if (pos != m_alias_options.end())
2237 m_alias_options.erase (pos);
2242 CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2244 m_alias_options[alias_name] = option_arg_vector_sp;
2248 CommandInterpreter::HasCommands ()
2250 return (!m_command_dict.empty());
2254 CommandInterpreter::HasAliases ()
2256 return (!m_alias_dict.empty());
2260 CommandInterpreter::HasUserCommands ()
2262 return (!m_user_dict.empty());
2266 CommandInterpreter::HasAliasOptions ()
2268 return (!m_alias_options.empty());
2272 CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2273 const char *alias_name,
2275 std::string &raw_input_string,
2276 CommandReturnObject &result)
2278 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
2280 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
2282 // Make sure that the alias name is the 0th element in cmd_args
2283 std::string alias_name_str = alias_name;
2284 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2285 cmd_args.Unshift (alias_name);
2287 Args new_args (alias_cmd_obj->GetCommandName());
2288 if (new_args.GetArgumentCount() == 2)
2291 if (option_arg_vector_sp.get())
2293 if (wants_raw_input)
2295 // We have a command that both has command options and takes raw input. Make *sure* it has a
2296 // " -- " in the right place in the raw_input_string.
2297 size_t pos = raw_input_string.find(" -- ");
2298 if (pos == std::string::npos)
2300 // None found; assume it goes at the beginning of the raw input string
2301 raw_input_string.insert (0, " -- ");
2305 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2306 const size_t old_size = cmd_args.GetArgumentCount();
2307 std::vector<bool> used (old_size + 1, false);
2311 for (size_t i = 0; i < option_arg_vector->size(); ++i)
2313 OptionArgPair option_pair = (*option_arg_vector)[i];
2314 OptionArgValue value_pair = option_pair.second;
2315 int value_type = value_pair.first;
2316 std::string option = option_pair.first;
2317 std::string value = value_pair.second;
2318 if (option.compare ("<argument>") == 0)
2320 if (!wants_raw_input
2321 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2322 new_args.AppendArgument (value.c_str());
2326 if (value_type != OptionParser::eOptionalArgument)
2327 new_args.AppendArgument (option.c_str());
2328 if (value.compare ("<no-argument>") != 0)
2330 int index = GetOptionArgumentPosition (value.c_str());
2333 // value was NOT a positional argument; must be a real value
2334 if (value_type != OptionParser::eOptionalArgument)
2335 new_args.AppendArgument (value.c_str());
2339 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2340 new_args.AppendArgument (buffer);
2344 else if (index >= cmd_args.GetArgumentCount())
2346 result.AppendErrorWithFormat
2347 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2349 result.SetStatus (eReturnStatusFailed);
2354 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2355 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2356 if (strpos != std::string::npos)
2358 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2361 if (value_type != OptionParser::eOptionalArgument)
2362 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2366 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2367 cmd_args.GetArgumentAtIndex (index));
2368 new_args.AppendArgument (buffer);
2376 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
2378 if (!used[j] && !wants_raw_input)
2379 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2383 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2387 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2388 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2389 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2391 if (wants_raw_input)
2394 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2399 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2405 CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2407 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2410 char *cptr = (char *) in_string;
2412 // Does it start with '%'
2417 // Is the rest of it entirely digits?
2418 if (isdigit (cptr[0]))
2420 const char *start = cptr;
2421 while (isdigit (cptr[0]))
2424 // We've gotten to the end of the digits; are we at the end of the string?
2425 if (cptr[0] == '\0')
2426 position = atoi (start);
2434 CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2439 // In the current working directory we don't load any program specific
2440 // .lldbinit files, we only look for a "./.lldbinit" file.
2441 if (m_skip_lldbinit_files)
2444 init_file.SetFile ("./.lldbinit", true);
2448 // If we aren't looking in the current working directory we are looking
2449 // in the home directory. We will first see if there is an application
2450 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2451 // "-" and the name of the program. If this file doesn't exist, we fall
2452 // back to just the "~/.lldbinit" file. We also obey any requests to not
2453 // load the init files.
2454 const char *init_file_path = "~/.lldbinit";
2456 if (m_skip_app_init_files == false)
2458 FileSpec program_file_spec (Host::GetProgramFileSpec());
2459 const char *program_name = program_file_spec.GetFilename().AsCString();
2463 char program_init_file_name[PATH_MAX];
2464 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2465 init_file.SetFile (program_init_file_name, true);
2466 if (!init_file.Exists())
2471 if (!init_file && !m_skip_lldbinit_files)
2472 init_file.SetFile (init_file_path, true);
2475 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2476 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2478 if (init_file.Exists())
2480 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2481 bool stop_on_continue = true;
2482 bool stop_on_error = false;
2483 bool echo_commands = false;
2484 bool print_results = false;
2486 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
2490 // nothing to be done if the file doesn't exist
2491 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2496 CommandInterpreter::GetPlatform (bool prefer_target_platform)
2498 PlatformSP platform_sp;
2499 if (prefer_target_platform)
2501 ExecutionContext exe_ctx(GetExecutionContext());
2502 Target *target = exe_ctx.GetTargetPtr();
2504 platform_sp = target->GetPlatform();
2508 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2513 CommandInterpreter::HandleCommands (const StringList &commands,
2514 ExecutionContext *override_context,
2515 bool stop_on_continue,
2519 LazyBool add_to_history,
2520 CommandReturnObject &result)
2522 size_t num_lines = commands.GetSize();
2524 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2525 // Make sure you reset this value anywhere you return from the function.
2527 bool old_async_execution = m_debugger.GetAsyncExecution();
2529 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2530 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2532 if (override_context != NULL)
2533 UpdateExecutionContext (override_context);
2535 if (!stop_on_continue)
2537 m_debugger.SetAsyncExecution (false);
2540 for (size_t idx = 0; idx < num_lines; idx++)
2542 const char *cmd = commands.GetStringAtIndex(idx);
2548 result.AppendMessageWithFormat ("%s %s\n",
2553 CommandReturnObject tmp_result;
2554 // If override_context is not NULL, pass no_context_switching = true for
2555 // HandleCommand() since we updated our context already.
2557 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2558 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here.
2559 if (!add_to_history)
2560 m_command_source_depth++;
2561 bool success = HandleCommand(cmd, add_to_history, tmp_result,
2562 NULL, /* override_context */
2563 true, /* repeat_on_empty_command */
2564 override_context != NULL /* no_context_switching */);
2565 if (!add_to_history)
2566 m_command_source_depth--;
2570 if (tmp_result.Succeeded())
2571 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
2574 if (!success || !tmp_result.Succeeded())
2576 const char *error_msg = tmp_result.GetErrorData();
2577 if (error_msg == NULL || error_msg[0] == '\0')
2578 error_msg = "<unknown error>.\n";
2581 result.AppendErrorWithFormat("Aborting reading of commands after command #%zu: '%s' failed with %s",
2582 idx, cmd, error_msg);
2583 result.SetStatus (eReturnStatusFailed);
2584 m_debugger.SetAsyncExecution (old_async_execution);
2587 else if (print_results)
2589 result.AppendMessageWithFormat ("Command #%zu '%s' failed with %s",
2596 if (result.GetImmediateOutputStream())
2597 result.GetImmediateOutputStream()->Flush();
2599 if (result.GetImmediateErrorStream())
2600 result.GetImmediateErrorStream()->Flush();
2602 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2603 // could be running (for instance in Breakpoint Commands.
2604 // So we check the return value to see if it is has running in it.
2605 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2606 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2608 if (stop_on_continue)
2610 // If we caused the target to proceed, and we're going to stop in that case, set the
2611 // status in our real result before returning. This is an error if the continue was not the
2612 // last command in the set of commands to be run.
2613 if (idx != num_lines - 1)
2614 result.AppendErrorWithFormat("Aborting reading of commands after command #%zu: '%s' continued the target.\n",
2617 result.AppendMessageWithFormat ("Command #%zu '%s' continued the target.\n", idx + 1, cmd);
2619 result.SetStatus(tmp_result.GetStatus());
2620 m_debugger.SetAsyncExecution (old_async_execution);
2628 result.SetStatus (eReturnStatusSuccessFinishResult);
2629 m_debugger.SetAsyncExecution (old_async_execution);
2635 CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2636 ExecutionContext *context,
2637 bool stop_on_continue,
2641 LazyBool add_to_history,
2642 CommandReturnObject &result)
2644 if (cmd_file.Exists())
2647 StringList commands;
2648 success = commands.ReadFileLines(cmd_file);
2651 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2652 result.SetStatus (eReturnStatusFailed);
2655 m_command_source_depth++;
2656 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2657 m_command_source_depth--;
2661 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2662 cmd_file.GetFilename().AsCString());
2663 result.SetStatus (eReturnStatusFailed);
2669 CommandInterpreter::GetScriptInterpreter (bool can_create)
2671 if (m_script_interpreter_ap.get() != NULL)
2672 return m_script_interpreter_ap.get();
2677 // <rdar://problem/11751427>
2678 // we need to protect the initialization of the script interpreter
2679 // otherwise we could end up with two threads both trying to create
2680 // their instance of it, and for some languages (e.g. Python)
2681 // this is a bulletproof recipe for disaster!
2682 // this needs to be a function-level static because multiple Debugger instances living in the same process
2683 // still need to be isolated and not try to initialize Python concurrently
2684 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2685 Mutex::Locker interpreter_lock(g_interpreter_mutex);
2687 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
2689 log->Printf("Initializing the ScriptInterpreter now\n");
2691 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2692 switch (script_lang)
2694 case eScriptLanguagePython:
2695 #ifndef LLDB_DISABLE_PYTHON
2696 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2699 // Fall through to the None case when python is disabled
2701 case eScriptLanguageNone:
2702 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2706 return m_script_interpreter_ap.get();
2712 CommandInterpreter::GetSynchronous ()
2714 return m_synchronous_execution;
2718 CommandInterpreter::SetSynchronous (bool value)
2720 m_synchronous_execution = value;
2724 CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2725 const char *word_text,
2726 const char *separator,
2727 const char *help_text,
2728 size_t max_word_len)
2730 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2732 int indent_size = max_word_len + strlen (separator) + 2;
2734 strm.IndentMore (indent_size);
2736 StreamString text_strm;
2737 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text);
2739 size_t len = text_strm.GetSize();
2740 const char *text = text_strm.GetData();
2741 if (text[len - 1] == '\n')
2744 len = text_strm.GetSize();
2747 if (len < max_columns)
2749 // Output it as a single line.
2750 strm.Printf ("%s", text);
2754 // We need to break it up into multiple lines.
2755 bool first_line = true;
2759 const size_t final_end = strlen (text);
2761 while (end < final_end)
2764 text_width = max_columns - 1;
2766 text_width = max_columns - indent_size - 1;
2768 // Don't start the 'text' on a space, since we're already outputting the indentation.
2771 while ((start < final_end) && (text[start] == ' '))
2775 end = start + text_width;
2776 if (end > final_end)
2780 // If we're not at the end of the text, make sure we break the line on white space.
2782 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2787 const size_t sub_len = end - start;
2794 assert (start <= final_end);
2795 assert (start + sub_len <= final_end);
2797 strm.Write (text + start, sub_len);
2802 strm.IndentLess(indent_size);
2806 CommandInterpreter::OutputHelpText (Stream &strm,
2807 const char *word_text,
2808 const char *separator,
2809 const char *help_text,
2810 uint32_t max_word_len)
2812 int indent_size = max_word_len + strlen (separator) + 2;
2814 strm.IndentMore (indent_size);
2816 StreamString text_strm;
2817 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2819 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2821 size_t len = text_strm.GetSize();
2822 const char *text = text_strm.GetData();
2824 uint32_t chars_left = max_columns;
2826 for (uint32_t i = 0; i < len; i++)
2828 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2830 chars_left = max_columns - indent_size;
2836 strm.PutChar(text[i]);
2843 strm.IndentLess(indent_size);
2847 CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2848 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
2850 CommandObject::CommandMap::const_iterator pos;
2852 if (search_builtin_commands)
2854 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2856 const char *command_name = pos->first.c_str();
2857 CommandObject *cmd_obj = pos->second.get();
2859 if (cmd_obj->HelpTextContainsWord (search_word))
2861 commands_found.AppendString (command_name);
2862 commands_help.AppendString (cmd_obj->GetHelp());
2865 if (cmd_obj->IsMultiwordObject())
2866 cmd_obj->AproposAllSubCommands (command_name,
2874 if (search_user_commands)
2876 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
2878 const char *command_name = pos->first.c_str();
2879 CommandObject *cmd_obj = pos->second.get();
2881 if (cmd_obj->HelpTextContainsWord (search_word))
2883 commands_found.AppendString (command_name);
2884 commands_help.AppendString (cmd_obj->GetHelp());
2887 if (cmd_obj->IsMultiwordObject())
2888 cmd_obj->AproposAllSubCommands (command_name,
2899 CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2901 if (override_context != NULL)
2903 m_exe_ctx_ref = *override_context;
2907 const bool adopt_selected = true;
2908 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);