1 //===-- CommandObject.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/Interpreter/CommandObject.h"
19 #include "lldb/Core/Address.h"
20 #include "lldb/Interpreter/Options.h"
21 #include "lldb/Utility/ArchSpec.h"
23 // These are for the Sourcename completers.
24 // FIXME: Make a separate file for the completers.
25 #include "lldb/Core/FileSpecList.h"
26 #include "lldb/DataFormatters/FormatManager.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Utility/FileSpec.h"
31 #include "lldb/Target/Language.h"
33 #include "lldb/Interpreter/CommandInterpreter.h"
34 #include "lldb/Interpreter/CommandReturnObject.h"
37 using namespace lldb_private;
39 //-------------------------------------------------------------------------
41 //-------------------------------------------------------------------------
43 CommandObject::CommandObject(CommandInterpreter &interpreter, llvm::StringRef name,
44 llvm::StringRef help, llvm::StringRef syntax, uint32_t flags)
45 : m_interpreter(interpreter), m_cmd_name(name),
46 m_cmd_help_short(), m_cmd_help_long(), m_cmd_syntax(), m_flags(flags),
47 m_arguments(), m_deprecated_command_override_callback(nullptr),
48 m_command_override_callback(nullptr), m_command_override_baton(nullptr) {
49 m_cmd_help_short = help;
50 m_cmd_syntax = syntax;
53 CommandObject::~CommandObject() {}
55 llvm::StringRef CommandObject::GetHelp() { return m_cmd_help_short; }
57 llvm::StringRef CommandObject::GetHelpLong() { return m_cmd_help_long; }
59 llvm::StringRef CommandObject::GetSyntax() {
60 if (!m_cmd_syntax.empty())
63 StreamString syntax_str;
64 syntax_str.PutCString(GetCommandName());
66 if (!IsDashDashCommand() && GetOptions() != nullptr)
67 syntax_str.PutCString(" <cmd-options>");
69 if (!m_arguments.empty()) {
70 syntax_str.PutCString(" ");
72 if (!IsDashDashCommand() && WantsRawCommandString() && GetOptions() &&
73 GetOptions()->NumCommandOptions())
74 syntax_str.PutCString("-- ");
75 GetFormattedCommandArguments(syntax_str);
77 m_cmd_syntax = syntax_str.GetString();
82 llvm::StringRef CommandObject::GetCommandName() const { return m_cmd_name; }
84 void CommandObject::SetCommandName(llvm::StringRef name) { m_cmd_name = name; }
86 void CommandObject::SetHelp(llvm::StringRef str) { m_cmd_help_short = str; }
88 void CommandObject::SetHelpLong(llvm::StringRef str) { m_cmd_help_long = str; }
90 void CommandObject::SetSyntax(llvm::StringRef str) { m_cmd_syntax = str; }
92 Options *CommandObject::GetOptions() {
93 // By default commands don't have options unless this virtual function is
94 // overridden by base classes.
98 bool CommandObject::ParseOptions(Args &args, CommandReturnObject &result) {
99 // See if the subclass has options?
100 Options *options = GetOptions();
101 if (options != nullptr) {
104 auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
105 options->NotifyOptionParsingStarting(&exe_ctx);
107 const bool require_validation = true;
108 llvm::Expected<Args> args_or = options->Parse(
109 args, &exe_ctx, GetCommandInterpreter().GetPlatform(true),
113 args = std::move(*args_or);
114 error = options->NotifyOptionParsingFinished(&exe_ctx);
116 error = args_or.takeError();
118 if (error.Success()) {
119 if (options->VerifyOptions(result))
122 const char *error_cstr = error.AsCString();
124 // We got an error string, lets use that
125 result.AppendError(error_cstr);
127 // No error string, output the usage information into result
128 options->GenerateOptionUsage(
129 result.GetErrorStream(), this,
130 GetCommandInterpreter().GetDebugger().GetTerminalWidth());
133 result.SetStatus(eReturnStatusFailed);
139 bool CommandObject::CheckRequirements(CommandReturnObject &result) {
140 #ifdef LLDB_CONFIGURATION_DEBUG
141 // Nothing should be stored in m_exe_ctx between running commands as
142 // m_exe_ctx has shared pointers to the target, process, thread and frame and
143 // we don't want any CommandObject instances to keep any of these objects
144 // around longer than for a single command. Every command should call
145 // CommandObject::Cleanup() after it has completed
146 assert(m_exe_ctx.GetTargetPtr() == NULL);
147 assert(m_exe_ctx.GetProcessPtr() == NULL);
148 assert(m_exe_ctx.GetThreadPtr() == NULL);
149 assert(m_exe_ctx.GetFramePtr() == NULL);
152 // Lock down the interpreter's execution context prior to running the command
153 // so we guarantee the selected target, process, thread and frame can't go
154 // away during the execution
155 m_exe_ctx = m_interpreter.GetExecutionContext();
157 const uint32_t flags = GetFlags().Get();
158 if (flags & (eCommandRequiresTarget | eCommandRequiresProcess |
159 eCommandRequiresThread | eCommandRequiresFrame |
160 eCommandTryTargetAPILock)) {
162 if ((flags & eCommandRequiresTarget) && !m_exe_ctx.HasTargetScope()) {
163 result.AppendError(GetInvalidTargetDescription());
167 if ((flags & eCommandRequiresProcess) && !m_exe_ctx.HasProcessScope()) {
168 if (!m_exe_ctx.HasTargetScope())
169 result.AppendError(GetInvalidTargetDescription());
171 result.AppendError(GetInvalidProcessDescription());
175 if ((flags & eCommandRequiresThread) && !m_exe_ctx.HasThreadScope()) {
176 if (!m_exe_ctx.HasTargetScope())
177 result.AppendError(GetInvalidTargetDescription());
178 else if (!m_exe_ctx.HasProcessScope())
179 result.AppendError(GetInvalidProcessDescription());
181 result.AppendError(GetInvalidThreadDescription());
185 if ((flags & eCommandRequiresFrame) && !m_exe_ctx.HasFrameScope()) {
186 if (!m_exe_ctx.HasTargetScope())
187 result.AppendError(GetInvalidTargetDescription());
188 else if (!m_exe_ctx.HasProcessScope())
189 result.AppendError(GetInvalidProcessDescription());
190 else if (!m_exe_ctx.HasThreadScope())
191 result.AppendError(GetInvalidThreadDescription());
193 result.AppendError(GetInvalidFrameDescription());
197 if ((flags & eCommandRequiresRegContext) &&
198 (m_exe_ctx.GetRegisterContext() == nullptr)) {
199 result.AppendError(GetInvalidRegContextDescription());
203 if (flags & eCommandTryTargetAPILock) {
204 Target *target = m_exe_ctx.GetTargetPtr();
207 std::unique_lock<std::recursive_mutex>(target->GetAPIMutex());
211 if (GetFlags().AnySet(eCommandProcessMustBeLaunched |
212 eCommandProcessMustBePaused)) {
213 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
214 if (process == nullptr) {
215 // A process that is not running is considered paused.
216 if (GetFlags().Test(eCommandProcessMustBeLaunched)) {
217 result.AppendError("Process must exist.");
218 result.SetStatus(eReturnStatusFailed);
222 StateType state = process->GetState();
225 case eStateSuspended:
230 case eStateConnected:
231 case eStateAttaching:
232 case eStateLaunching:
236 if (GetFlags().Test(eCommandProcessMustBeLaunched)) {
237 result.AppendError("Process must be launched.");
238 result.SetStatus(eReturnStatusFailed);
245 if (GetFlags().Test(eCommandProcessMustBePaused)) {
246 result.AppendError("Process is running. Use 'process interrupt' to "
248 result.SetStatus(eReturnStatusFailed);
257 void CommandObject::Cleanup() {
259 if (m_api_locker.owns_lock())
260 m_api_locker.unlock();
263 int CommandObject::HandleCompletion(CompletionRequest &request) {
264 // Default implementation of WantsCompletion() is !WantsRawCommandString().
265 // Subclasses who want raw command string but desire, for example, argument
266 // completion should override WantsCompletion() to return true, instead.
267 if (WantsRawCommandString() && !WantsCompletion()) {
268 // FIXME: Abstract telling the completion to insert the completion
272 // Can we do anything generic with the options?
273 Options *cur_options = GetOptions();
274 CommandReturnObject result;
275 OptionElementVector opt_element_vector;
277 if (cur_options != nullptr) {
278 opt_element_vector = cur_options->ParseForCompletion(
279 request.GetParsedLine(), request.GetCursorIndex());
281 bool handled_by_options = cur_options->HandleOptionCompletion(
282 request, opt_element_vector, GetCommandInterpreter());
283 if (handled_by_options)
284 return request.GetNumberOfMatches();
287 // If we got here, the last word is not an option or an option argument.
288 return HandleArgumentCompletion(request, opt_element_vector);
292 bool CommandObject::HelpTextContainsWord(llvm::StringRef search_word,
293 bool search_short_help,
294 bool search_long_help,
296 bool search_options) {
297 std::string options_usage_help;
299 bool found_word = false;
301 llvm::StringRef short_help = GetHelp();
302 llvm::StringRef long_help = GetHelpLong();
303 llvm::StringRef syntax_help = GetSyntax();
305 if (search_short_help && short_help.contains_lower(search_word))
307 else if (search_long_help && long_help.contains_lower(search_word))
309 else if (search_syntax && syntax_help.contains_lower(search_word))
312 if (!found_word && search_options && GetOptions() != nullptr) {
313 StreamString usage_help;
314 GetOptions()->GenerateOptionUsage(
316 GetCommandInterpreter().GetDebugger().GetTerminalWidth());
317 if (!usage_help.Empty()) {
318 llvm::StringRef usage_text = usage_help.GetString();
319 if (usage_text.contains_lower(search_word))
327 bool CommandObject::ParseOptionsAndNotify(Args &args,
328 CommandReturnObject &result,
329 OptionGroupOptions &group_options,
330 ExecutionContext &exe_ctx) {
331 if (!ParseOptions(args, result))
334 Status error(group_options.NotifyOptionParsingFinished(&exe_ctx));
336 result.AppendError(error.AsCString());
337 result.SetStatus(eReturnStatusFailed);
343 int CommandObject::GetNumArgumentEntries() { return m_arguments.size(); }
345 CommandObject::CommandArgumentEntry *
346 CommandObject::GetArgumentEntryAtIndex(int idx) {
347 if (static_cast<size_t>(idx) < m_arguments.size())
348 return &(m_arguments[idx]);
353 const CommandObject::ArgumentTableEntry *
354 CommandObject::FindArgumentDataByType(CommandArgumentType arg_type) {
355 const ArgumentTableEntry *table = CommandObject::GetArgumentTable();
357 for (int i = 0; i < eArgTypeLastArg; ++i)
358 if (table[i].arg_type == arg_type)
364 void CommandObject::GetArgumentHelp(Stream &str, CommandArgumentType arg_type,
365 CommandInterpreter &interpreter) {
366 const ArgumentTableEntry *table = CommandObject::GetArgumentTable();
367 const ArgumentTableEntry *entry = &(table[arg_type]);
369 // The table is *supposed* to be kept in arg_type order, but someone *could*
370 // have messed it up...
372 if (entry->arg_type != arg_type)
373 entry = CommandObject::FindArgumentDataByType(arg_type);
378 StreamString name_str;
379 name_str.Printf("<%s>", entry->arg_name);
381 if (entry->help_function) {
382 llvm::StringRef help_text = entry->help_function();
383 if (!entry->help_function.self_formatting) {
384 interpreter.OutputFormattedHelpText(str, name_str.GetString(), "--",
385 help_text, name_str.GetSize());
387 interpreter.OutputHelpText(str, name_str.GetString(), "--", help_text,
391 interpreter.OutputFormattedHelpText(str, name_str.GetString(), "--",
392 entry->help_text, name_str.GetSize());
395 const char *CommandObject::GetArgumentName(CommandArgumentType arg_type) {
396 const ArgumentTableEntry *entry =
397 &(CommandObject::GetArgumentTable()[arg_type]);
399 // The table is *supposed* to be kept in arg_type order, but someone *could*
400 // have messed it up...
402 if (entry->arg_type != arg_type)
403 entry = CommandObject::FindArgumentDataByType(arg_type);
406 return entry->arg_name;
411 bool CommandObject::IsPairType(ArgumentRepetitionType arg_repeat_type) {
412 if ((arg_repeat_type == eArgRepeatPairPlain) ||
413 (arg_repeat_type == eArgRepeatPairOptional) ||
414 (arg_repeat_type == eArgRepeatPairPlus) ||
415 (arg_repeat_type == eArgRepeatPairStar) ||
416 (arg_repeat_type == eArgRepeatPairRange) ||
417 (arg_repeat_type == eArgRepeatPairRangeOptional))
423 static CommandObject::CommandArgumentEntry
424 OptSetFiltered(uint32_t opt_set_mask,
425 CommandObject::CommandArgumentEntry &cmd_arg_entry) {
426 CommandObject::CommandArgumentEntry ret_val;
427 for (unsigned i = 0; i < cmd_arg_entry.size(); ++i)
428 if (opt_set_mask & cmd_arg_entry[i].arg_opt_set_association)
429 ret_val.push_back(cmd_arg_entry[i]);
433 // Default parameter value of opt_set_mask is LLDB_OPT_SET_ALL, which means
434 // take all the argument data into account. On rare cases where some argument
435 // sticks with certain option sets, this function returns the option set
437 void CommandObject::GetFormattedCommandArguments(Stream &str,
438 uint32_t opt_set_mask) {
439 int num_args = m_arguments.size();
440 for (int i = 0; i < num_args; ++i) {
443 CommandArgumentEntry arg_entry =
444 opt_set_mask == LLDB_OPT_SET_ALL
446 : OptSetFiltered(opt_set_mask, m_arguments[i]);
447 int num_alternatives = arg_entry.size();
449 if ((num_alternatives == 2) && IsPairType(arg_entry[0].arg_repetition)) {
450 const char *first_name = GetArgumentName(arg_entry[0].arg_type);
451 const char *second_name = GetArgumentName(arg_entry[1].arg_type);
452 switch (arg_entry[0].arg_repetition) {
453 case eArgRepeatPairPlain:
454 str.Printf("<%s> <%s>", first_name, second_name);
456 case eArgRepeatPairOptional:
457 str.Printf("[<%s> <%s>]", first_name, second_name);
459 case eArgRepeatPairPlus:
460 str.Printf("<%s> <%s> [<%s> <%s> [...]]", first_name, second_name,
461 first_name, second_name);
463 case eArgRepeatPairStar:
464 str.Printf("[<%s> <%s> [<%s> <%s> [...]]]", first_name, second_name,
465 first_name, second_name);
467 case eArgRepeatPairRange:
468 str.Printf("<%s_1> <%s_1> ... <%s_n> <%s_n>", first_name, second_name,
469 first_name, second_name);
471 case eArgRepeatPairRangeOptional:
472 str.Printf("[<%s_1> <%s_1> ... <%s_n> <%s_n>]", first_name, second_name,
473 first_name, second_name);
475 // Explicitly test for all the rest of the cases, so if new types get
476 // added we will notice the missing case statement(s).
477 case eArgRepeatPlain:
478 case eArgRepeatOptional:
481 case eArgRepeatRange:
482 // These should not be reached, as they should fail the IsPairType test
488 for (int j = 0; j < num_alternatives; ++j) {
491 names.Printf("%s", GetArgumentName(arg_entry[j].arg_type));
494 std::string name_str = names.GetString();
495 switch (arg_entry[0].arg_repetition) {
496 case eArgRepeatPlain:
497 str.Printf("<%s>", name_str.c_str());
500 str.Printf("<%s> [<%s> [...]]", name_str.c_str(), name_str.c_str());
503 str.Printf("[<%s> [<%s> [...]]]", name_str.c_str(), name_str.c_str());
505 case eArgRepeatOptional:
506 str.Printf("[<%s>]", name_str.c_str());
508 case eArgRepeatRange:
509 str.Printf("<%s_1> .. <%s_n>", name_str.c_str(), name_str.c_str());
511 // Explicitly test for all the rest of the cases, so if new types get
512 // added we will notice the missing case statement(s).
513 case eArgRepeatPairPlain:
514 case eArgRepeatPairOptional:
515 case eArgRepeatPairPlus:
516 case eArgRepeatPairStar:
517 case eArgRepeatPairRange:
518 case eArgRepeatPairRangeOptional:
519 // These should not be hit, as they should pass the IsPairType test
520 // above, and control should have gone into the other branch of the if
529 CommandObject::LookupArgumentName(llvm::StringRef arg_name) {
530 CommandArgumentType return_type = eArgTypeLastArg;
532 arg_name = arg_name.ltrim('<').rtrim('>');
534 const ArgumentTableEntry *table = GetArgumentTable();
535 for (int i = 0; i < eArgTypeLastArg; ++i)
536 if (arg_name == table[i].arg_name)
537 return_type = g_arguments_data[i].arg_type;
542 static llvm::StringRef RegisterNameHelpTextCallback() {
543 return "Register names can be specified using the architecture specific "
545 "They can also be specified using generic names. Not all generic "
547 "registers backing them on all architectures. When they don't the "
549 "will return an error.\n"
550 "The generic names defined in lldb are:\n"
552 "pc - program counter register\n"
553 "ra - return address register\n"
554 "fp - frame pointer register\n"
555 "sp - stack pointer register\n"
556 "flags - the flags register\n"
557 "arg{1-6} - integer argument passing registers.\n";
560 static llvm::StringRef BreakpointIDHelpTextCallback() {
561 return "Breakpoints are identified using major and minor numbers; the major "
562 "number corresponds to the single entity that was created with a "
564 "set' command; the minor numbers correspond to all the locations that "
566 "actually found/set based on the major breakpoint. A full breakpoint "
568 "look like 3.14, meaning the 14th location set for the 3rd "
570 "can specify all the locations of a breakpoint by just indicating the "
572 "breakpoint number. A valid breakpoint ID consists either of just the "
574 "number, or the major number followed by a dot and the location "
576 "3 or 3.2 could both be valid breakpoint IDs.)";
579 static llvm::StringRef BreakpointIDRangeHelpTextCallback() {
580 return "A 'breakpoint ID list' is a manner of specifying multiple "
582 "This can be done through several mechanisms. The easiest way is to "
584 "enter a space-separated list of breakpoint IDs. To specify all the "
585 "breakpoint locations under a major breakpoint, you can use the major "
586 "breakpoint number followed by '.*', eg. '5.*' means all the "
588 "breakpoint 5. You can also indicate a range of breakpoints by using "
589 "<start-bp-id> - <end-bp-id>. The start-bp-id and end-bp-id for a "
591 "be any valid breakpoint IDs. It is not legal, however, to specify a "
593 "using specific locations that cross major breakpoint numbers. I.e. "
595 " is legal; 2 - 5 is legal; but 3.2 - 4.4 is not legal.";
598 static llvm::StringRef BreakpointNameHelpTextCallback() {
599 return "A name that can be added to a breakpoint when it is created, or "
601 "on with the \"breakpoint name add\" command. "
602 "Breakpoint names can be used to specify breakpoints in all the "
603 "places breakpoint IDs "
604 "and breakpoint ID ranges can be used. As such they provide a "
605 "convenient way to group breakpoints, "
606 "and to operate on breakpoints you create without having to track the "
607 "breakpoint number. "
608 "Note, the attributes you set when using a breakpoint name in a "
609 "breakpoint command don't "
610 "adhere to the name, but instead are set individually on all the "
611 "breakpoints currently tagged with that "
612 "name. Future breakpoints "
613 "tagged with that name will not pick up the attributes previously "
614 "given using that name. "
615 "In order to distinguish breakpoint names from breakpoint IDs and "
617 "names must start with a letter from a-z or A-Z and cannot contain "
618 "spaces, \".\" or \"-\". "
619 "Also, breakpoint names can only be applied to breakpoints, not to "
620 "breakpoint locations.";
623 static llvm::StringRef GDBFormatHelpTextCallback() {
624 return "A GDB format consists of a repeat count, a format letter and a size "
626 "The repeat count is optional and defaults to 1. The format letter is "
628 "and defaults to the previous format that was used. The size letter "
630 "and defaults to the previous size that was used.\n"
632 "Format letters include:\n"
636 "u - unsigned decimal\n"
646 "Size letters include:\n"
647 "b - 1 byte (byte)\n"
648 "h - 2 bytes (halfword)\n"
649 "w - 4 bytes (word)\n"
650 "g - 8 bytes (giant)\n"
653 "32xb - show 32 1 byte hexadecimal integer values\n"
654 "16xh - show 16 2 byte hexadecimal integer values\n"
655 "64 - show 64 2 byte hexadecimal integer values (format and size "
656 "from the last format)\n"
657 "dw - show 1 4 byte decimal integer value\n";
660 static llvm::StringRef FormatHelpTextCallback() {
661 static std::string help_text;
663 if (!help_text.empty())
667 sstr << "One of the format names (or one-character names) that can be used "
668 "to show a variable's value:\n";
669 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f + 1)) {
670 if (f != eFormatDefault)
673 char format_char = FormatManager::GetFormatAsFormatChar(f);
675 sstr.Printf("'%c' or ", format_char);
677 sstr.Printf("\"%s\"", FormatManager::GetFormatAsCString(f));
682 help_text = sstr.GetString();
687 static llvm::StringRef LanguageTypeHelpTextCallback() {
688 static std::string help_text;
690 if (!help_text.empty())
694 sstr << "One of the following languages:\n";
696 Language::PrintAllLanguages(sstr, " ", "\n");
700 help_text = sstr.GetString();
705 static llvm::StringRef SummaryStringHelpTextCallback() {
706 return "A summary string is a way to extract information from variables in "
707 "order to present them using a summary.\n"
708 "Summary strings contain static text, variables, scopes and control "
710 " - Static text can be any sequence of non-special characters, i.e. "
711 "anything but '{', '}', '$', or '\\'.\n"
712 " - Variables are sequences of characters beginning with ${, ending "
713 "with } and that contain symbols in the format described below.\n"
714 " - Scopes are any sequence of text between { and }. Anything "
715 "included in a scope will only appear in the output summary if there "
717 " - Control sequences are the usual C/C++ '\\a', '\\n', ..., plus "
718 "'\\$', '\\{' and '\\}'.\n"
719 "A summary string works by copying static text verbatim, turning "
720 "control sequences into their character counterpart, expanding "
721 "variables and trying to expand scopes.\n"
722 "A variable is expanded by giving it a value other than its textual "
723 "representation, and the way this is done depends on what comes after "
725 "The most common sequence if ${var followed by an expression path, "
726 "which is the text one would type to access a member of an aggregate "
727 "types, given a variable of that type"
728 " (e.g. if type T has a member named x, which has a member named y, "
729 "and if t is of type T, the expression path would be .x.y and the way "
730 "to fit that into a summary string would be"
731 " ${var.x.y}). You can also use ${*var followed by an expression path "
732 "and in that case the object referred by the path will be "
733 "dereferenced before being displayed."
734 " If the object is not a pointer, doing so will cause an error. For "
735 "additional details on expression paths, you can type 'help "
737 "By default, summary strings attempt to display the summary for any "
738 "variable they reference, and if that fails the value. If neither can "
739 "be shown, nothing is displayed."
740 "In a summary string, you can also use an array index [n], or a "
741 "slice-like range [n-m]. This can have two different meanings "
742 "depending on what kind of object the expression"
744 " - if it is a scalar type (any basic type like int, float, ...) the "
745 "expression is a bitfield, i.e. the bits indicated by the indexing "
746 "operator are extracted out of the number"
747 " and displayed as an individual variable\n"
748 " - if it is an array or pointer the array items indicated by the "
749 "indexing operator are shown as the result of the variable. if the "
750 "expression is an array, real array items are"
751 " printed; if it is a pointer, the pointer-as-array syntax is used to "
752 "obtain the values (this means, the latter case can have no range "
754 "If you are trying to display an array for which the size is known, "
755 "you can also use [] instead of giving an exact range. This has the "
756 "effect of showing items 0 thru size - 1.\n"
757 "Additionally, a variable can contain an (optional) format code, as "
758 "in ${var.x.y%code}, where code can be any of the valid formats "
759 "described in 'help format', or one of the"
760 " special symbols only allowed as part of a variable:\n"
761 " %V: show the value of the object by default\n"
762 " %S: show the summary of the object by default\n"
763 " %@: show the runtime-provided object description (for "
764 "Objective-C, it calls NSPrintForDebugger; for C/C++ it does "
766 " %L: show the location of the object (memory address or a "
768 " %#: show the number of children of the object\n"
769 " %T: show the type of the object\n"
770 "Another variable that you can use in summary strings is ${svar . "
771 "This sequence works exactly like ${var, including the fact that "
772 "${*svar is an allowed sequence, but uses"
773 " the object's synthetic children provider instead of the actual "
774 "objects. For instance, if you are using STL synthetic children "
775 "providers, the following summary string would"
776 " count the number of actual elements stored in an std::list:\n"
777 "type summary add -s \"${svar%#}\" -x \"std::list<\"";
780 static llvm::StringRef ExprPathHelpTextCallback() {
781 return "An expression path is the sequence of symbols that is used in C/C++ "
782 "to access a member variable of an aggregate object (class).\n"
783 "For instance, given a class:\n"
789 "the expression to read item b in the item pointed to by next for foo "
790 "aFoo would be aFoo.next->b.\n"
791 "Given that aFoo could just be any object of type foo, the string "
792 "'.next->b' is the expression path, because it can be attached to any "
793 "foo instance to achieve the effect.\n"
794 "Expression paths in LLDB include dot (.) and arrow (->) operators, "
795 "and most commands using expression paths have ways to also accept "
796 "the star (*) operator.\n"
797 "The meaning of these operators is the same as the usual one given to "
798 "them by the C/C++ standards.\n"
799 "LLDB also has support for indexing ([ ]) in expression paths, and "
800 "extends the traditional meaning of the square brackets operator to "
801 "allow bitfield extraction:\n"
802 "for objects of native types (int, float, char, ...) saying '[n-m]' "
803 "as an expression path (where n and m are any positive integers, e.g. "
804 "[3-5]) causes LLDB to extract"
805 " bits n thru m from the value of the variable. If n == m, [n] is "
806 "also allowed as a shortcut syntax. For arrays and pointers, "
807 "expression paths can only contain one index"
808 " and the meaning of the operation is the same as the one defined by "
809 "C/C++ (item extraction). Some commands extend bitfield-like syntax "
810 "for arrays and pointers with the"
811 " meaning of array slicing (taking elements n thru m inside the array "
812 "or pointed-to memory).";
815 void CommandObject::FormatLongHelpText(Stream &output_strm,
816 llvm::StringRef long_help) {
817 CommandInterpreter &interpreter = GetCommandInterpreter();
818 std::stringstream lineStream(long_help);
820 while (std::getline(lineStream, line)) {
825 size_t result = line.find_first_not_of(" \t");
826 if (result == std::string::npos) {
829 std::string whitespace_prefix = line.substr(0, result);
830 std::string remainder = line.substr(result);
831 interpreter.OutputFormattedHelpText(output_strm, whitespace_prefix.c_str(),
836 void CommandObject::GenerateHelpText(CommandReturnObject &result) {
837 GenerateHelpText(result.GetOutputStream());
839 result.SetStatus(eReturnStatusSuccessFinishNoResult);
842 void CommandObject::GenerateHelpText(Stream &output_strm) {
843 CommandInterpreter &interpreter = GetCommandInterpreter();
844 if (WantsRawCommandString()) {
845 std::string help_text(GetHelp());
846 help_text.append(" Expects 'raw' input (see 'help raw-input'.)");
847 interpreter.OutputFormattedHelpText(output_strm, "", "", help_text.c_str(),
850 interpreter.OutputFormattedHelpText(output_strm, "", "", GetHelp(), 1);
851 output_strm << "\nSyntax: " << GetSyntax() << "\n";
852 Options *options = GetOptions();
853 if (options != nullptr) {
854 options->GenerateOptionUsage(
856 GetCommandInterpreter().GetDebugger().GetTerminalWidth());
858 llvm::StringRef long_help = GetHelpLong();
859 if (!long_help.empty()) {
860 FormatLongHelpText(output_strm, long_help);
862 if (!IsDashDashCommand() && options && options->NumCommandOptions() > 0) {
863 if (WantsRawCommandString() && !WantsCompletion()) {
864 // Emit the message about using ' -- ' between the end of the command
865 // options and the raw input conditionally, i.e., only if the command
866 // object does not want completion.
867 interpreter.OutputFormattedHelpText(
869 "\nImportant Note: Because this command takes 'raw' input, if you "
870 "use any command options"
871 " you must use ' -- ' between the end of the command options and the "
872 "beginning of the raw input.",
874 } else if (GetNumArgumentEntries() > 0) {
875 // Also emit a warning about using "--" in case you are using a command
876 // that takes options and arguments.
877 interpreter.OutputFormattedHelpText(
879 "\nThis command takes options and free-form arguments. If your "
881 " option specifiers (i.e., they start with a - or --), you must use "
883 " the end of the command options and the beginning of the arguments.",
889 void CommandObject::AddIDsArgumentData(CommandArgumentEntry &arg,
890 CommandArgumentType ID,
891 CommandArgumentType IDRange) {
892 CommandArgumentData id_arg;
893 CommandArgumentData id_range_arg;
895 // Create the first variant for the first (and only) argument for this
897 id_arg.arg_type = ID;
898 id_arg.arg_repetition = eArgRepeatOptional;
900 // Create the second variant for the first (and only) argument for this
902 id_range_arg.arg_type = IDRange;
903 id_range_arg.arg_repetition = eArgRepeatOptional;
905 // The first (and only) argument for this command could be either an id or an
906 // id_range. Push both variants into the entry for the first argument for
908 arg.push_back(id_arg);
909 arg.push_back(id_range_arg);
912 const char *CommandObject::GetArgumentTypeAsCString(
913 const lldb::CommandArgumentType arg_type) {
914 assert(arg_type < eArgTypeLastArg &&
915 "Invalid argument type passed to GetArgumentTypeAsCString");
916 return g_arguments_data[arg_type].arg_name;
919 const char *CommandObject::GetArgumentDescriptionAsCString(
920 const lldb::CommandArgumentType arg_type) {
921 assert(arg_type < eArgTypeLastArg &&
922 "Invalid argument type passed to GetArgumentDescriptionAsCString");
923 return g_arguments_data[arg_type].help_text;
926 Target *CommandObject::GetDummyTarget() {
927 return m_interpreter.GetDebugger().GetDummyTarget();
930 Target *CommandObject::GetSelectedOrDummyTarget(bool prefer_dummy) {
931 return m_interpreter.GetDebugger().GetSelectedOrDummyTarget(prefer_dummy);
934 Thread *CommandObject::GetDefaultThread() {
935 Thread *thread_to_use = m_exe_ctx.GetThreadPtr();
937 return thread_to_use;
939 Process *process = m_exe_ctx.GetProcessPtr();
941 Target *target = m_exe_ctx.GetTargetPtr();
943 target = m_interpreter.GetDebugger().GetSelectedTarget().get();
946 process = target->GetProcessSP().get();
950 return process->GetThreadList().GetSelectedThread().get();
955 bool CommandObjectParsed::Execute(const char *args_string,
956 CommandReturnObject &result) {
957 bool handled = false;
958 Args cmd_args(args_string);
959 if (HasOverrideCallback()) {
960 Args full_args(GetCommandName());
961 full_args.AppendArguments(cmd_args);
963 InvokeOverrideCallback(full_args.GetConstArgumentVector(), result);
966 for (auto entry : llvm::enumerate(cmd_args.entries())) {
967 if (!entry.value().ref.empty() && entry.value().ref.front() == '`') {
968 cmd_args.ReplaceArgumentAtIndex(
970 m_interpreter.ProcessEmbeddedScriptCommands(entry.value().c_str()));
974 if (CheckRequirements(result)) {
975 if (ParseOptions(cmd_args, result)) {
976 // Call the command-specific version of 'Execute', passing it the
977 // already processed arguments.
978 handled = DoExecute(cmd_args, result);
987 bool CommandObjectRaw::Execute(const char *args_string,
988 CommandReturnObject &result) {
989 bool handled = false;
990 if (HasOverrideCallback()) {
991 std::string full_command(GetCommandName());
993 full_command += args_string;
994 const char *argv[2] = {nullptr, nullptr};
995 argv[0] = full_command.c_str();
996 handled = InvokeOverrideCallback(argv, result);
999 if (CheckRequirements(result))
1000 handled = DoExecute(args_string, result);
1007 static llvm::StringRef arch_helper() {
1008 static StreamString g_archs_help;
1009 if (g_archs_help.Empty()) {
1012 ArchSpec::ListSupportedArchNames(archs);
1013 g_archs_help.Printf("These are the supported architecture names:\n");
1014 archs.Join("\n", g_archs_help);
1016 return g_archs_help.GetString();
1019 CommandObject::ArgumentTableEntry CommandObject::g_arguments_data[] = {
1021 { eArgTypeAddress, "address", CommandCompletions::eNoCompletion, { nullptr, false }, "A valid address in the target program's execution space." },
1022 { eArgTypeAddressOrExpression, "address-expression", CommandCompletions::eNoCompletion, { nullptr, false }, "An expression that resolves to an address." },
1023 { eArgTypeAliasName, "alias-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of an abbreviation (alias) for a debugger command." },
1024 { eArgTypeAliasOptions, "options-for-aliased-command", CommandCompletions::eNoCompletion, { nullptr, false }, "Command options to be used as part of an alias (abbreviation) definition. (See 'help commands alias' for more information.)" },
1025 { eArgTypeArchitecture, "arch", CommandCompletions::eArchitectureCompletion, { arch_helper, true }, "The architecture name, e.g. i386 or x86_64." },
1026 { eArgTypeBoolean, "boolean", CommandCompletions::eNoCompletion, { nullptr, false }, "A Boolean value: 'true' or 'false'" },
1027 { eArgTypeBreakpointID, "breakpt-id", CommandCompletions::eNoCompletion, { BreakpointIDHelpTextCallback, false }, nullptr },
1028 { eArgTypeBreakpointIDRange, "breakpt-id-list", CommandCompletions::eNoCompletion, { BreakpointIDRangeHelpTextCallback, false }, nullptr },
1029 { eArgTypeBreakpointName, "breakpoint-name", CommandCompletions::eNoCompletion, { BreakpointNameHelpTextCallback, false }, nullptr },
1030 { eArgTypeByteSize, "byte-size", CommandCompletions::eNoCompletion, { nullptr, false }, "Number of bytes to use." },
1031 { eArgTypeClassName, "class-name", CommandCompletions::eNoCompletion, { nullptr, false }, "Then name of a class from the debug information in the program." },
1032 { eArgTypeCommandName, "cmd-name", CommandCompletions::eNoCompletion, { nullptr, false }, "A debugger command (may be multiple words), without any options or arguments." },
1033 { eArgTypeCount, "count", CommandCompletions::eNoCompletion, { nullptr, false }, "An unsigned integer." },
1034 { eArgTypeDirectoryName, "directory", CommandCompletions::eDiskDirectoryCompletion, { nullptr, false }, "A directory name." },
1035 { eArgTypeDisassemblyFlavor, "disassembly-flavor", CommandCompletions::eNoCompletion, { nullptr, false }, "A disassembly flavor recognized by your disassembly plugin. Currently the only valid options are \"att\" and \"intel\" for Intel targets" },
1036 { eArgTypeDescriptionVerbosity, "description-verbosity", CommandCompletions::eNoCompletion, { nullptr, false }, "How verbose the output of 'po' should be." },
1037 { eArgTypeEndAddress, "end-address", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1038 { eArgTypeExpression, "expr", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1039 { eArgTypeExpressionPath, "expr-path", CommandCompletions::eNoCompletion, { ExprPathHelpTextCallback, true }, nullptr },
1040 { eArgTypeExprFormat, "expression-format", CommandCompletions::eNoCompletion, { nullptr, false }, "[ [bool|b] | [bin] | [char|c] | [oct|o] | [dec|i|d|u] | [hex|x] | [float|f] | [cstr|s] ]" },
1041 { eArgTypeFilename, "filename", CommandCompletions::eDiskFileCompletion, { nullptr, false }, "The name of a file (can include path)." },
1042 { eArgTypeFormat, "format", CommandCompletions::eNoCompletion, { FormatHelpTextCallback, true }, nullptr },
1043 { eArgTypeFrameIndex, "frame-index", CommandCompletions::eNoCompletion, { nullptr, false }, "Index into a thread's list of frames." },
1044 { eArgTypeFullName, "fullname", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1045 { eArgTypeFunctionName, "function-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a function." },
1046 { eArgTypeFunctionOrSymbol, "function-or-symbol", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a function or symbol." },
1047 { eArgTypeGDBFormat, "gdb-format", CommandCompletions::eNoCompletion, { GDBFormatHelpTextCallback, true }, nullptr },
1048 { eArgTypeHelpText, "help-text", CommandCompletions::eNoCompletion, { nullptr, false }, "Text to be used as help for some other entity in LLDB" },
1049 { eArgTypeIndex, "index", CommandCompletions::eNoCompletion, { nullptr, false }, "An index into a list." },
1050 { eArgTypeLanguage, "source-language", CommandCompletions::eNoCompletion, { LanguageTypeHelpTextCallback, true }, nullptr },
1051 { eArgTypeLineNum, "linenum", CommandCompletions::eNoCompletion, { nullptr, false }, "Line number in a source file." },
1052 { eArgTypeLogCategory, "log-category", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a category within a log channel, e.g. all (try \"log list\" to see a list of all channels and their categories." },
1053 { eArgTypeLogChannel, "log-channel", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a log channel, e.g. process.gdb-remote (try \"log list\" to see a list of all channels and their categories)." },
1054 { eArgTypeMethod, "method", CommandCompletions::eNoCompletion, { nullptr, false }, "A C++ method name." },
1055 { eArgTypeName, "name", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1056 { eArgTypeNewPathPrefix, "new-path-prefix", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1057 { eArgTypeNumLines, "num-lines", CommandCompletions::eNoCompletion, { nullptr, false }, "The number of lines to use." },
1058 { eArgTypeNumberPerLine, "number-per-line", CommandCompletions::eNoCompletion, { nullptr, false }, "The number of items per line to display." },
1059 { eArgTypeOffset, "offset", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1060 { eArgTypeOldPathPrefix, "old-path-prefix", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1061 { eArgTypeOneLiner, "one-line-command", CommandCompletions::eNoCompletion, { nullptr, false }, "A command that is entered as a single line of text." },
1062 { eArgTypePath, "path", CommandCompletions::eDiskFileCompletion, { nullptr, false }, "Path." },
1063 { eArgTypePermissionsNumber, "perms-numeric", CommandCompletions::eNoCompletion, { nullptr, false }, "Permissions given as an octal number (e.g. 755)." },
1064 { eArgTypePermissionsString, "perms=string", CommandCompletions::eNoCompletion, { nullptr, false }, "Permissions given as a string value (e.g. rw-r-xr--)." },
1065 { eArgTypePid, "pid", CommandCompletions::eNoCompletion, { nullptr, false }, "The process ID number." },
1066 { eArgTypePlugin, "plugin", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1067 { eArgTypeProcessName, "process-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of the process." },
1068 { eArgTypePythonClass, "python-class", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a Python class." },
1069 { eArgTypePythonFunction, "python-function", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a Python function." },
1070 { eArgTypePythonScript, "python-script", CommandCompletions::eNoCompletion, { nullptr, false }, "Source code written in Python." },
1071 { eArgTypeQueueName, "queue-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of the thread queue." },
1072 { eArgTypeRegisterName, "register-name", CommandCompletions::eNoCompletion, { RegisterNameHelpTextCallback, true }, nullptr },
1073 { eArgTypeRegularExpression, "regular-expression", CommandCompletions::eNoCompletion, { nullptr, false }, "A regular expression." },
1074 { eArgTypeRunArgs, "run-args", CommandCompletions::eNoCompletion, { nullptr, false }, "Arguments to be passed to the target program when it starts executing." },
1075 { eArgTypeRunMode, "run-mode", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1076 { eArgTypeScriptedCommandSynchronicity, "script-cmd-synchronicity", CommandCompletions::eNoCompletion, { nullptr, false }, "The synchronicity to use to run scripted commands with regard to LLDB event system." },
1077 { eArgTypeScriptLang, "script-language", CommandCompletions::eNoCompletion, { nullptr, false }, "The scripting language to be used for script-based commands. Currently only Python is valid." },
1078 { eArgTypeSearchWord, "search-word", CommandCompletions::eNoCompletion, { nullptr, false }, "Any word of interest for search purposes." },
1079 { eArgTypeSelector, "selector", CommandCompletions::eNoCompletion, { nullptr, false }, "An Objective-C selector name." },
1080 { eArgTypeSettingIndex, "setting-index", CommandCompletions::eNoCompletion, { nullptr, false }, "An index into a settings variable that is an array (try 'settings list' to see all the possible settings variables and their types)." },
1081 { eArgTypeSettingKey, "setting-key", CommandCompletions::eNoCompletion, { nullptr, false }, "A key into a settings variables that is a dictionary (try 'settings list' to see all the possible settings variables and their types)." },
1082 { eArgTypeSettingPrefix, "setting-prefix", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a settable internal debugger variable up to a dot ('.'), e.g. 'target.process.'" },
1083 { eArgTypeSettingVariableName, "setting-variable-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a settable internal debugger variable. Type 'settings list' to see a complete list of such variables." },
1084 { eArgTypeShlibName, "shlib-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a shared library." },
1085 { eArgTypeSourceFile, "source-file", CommandCompletions::eSourceFileCompletion, { nullptr, false }, "The name of a source file.." },
1086 { eArgTypeSortOrder, "sort-order", CommandCompletions::eNoCompletion, { nullptr, false }, "Specify a sort order when dumping lists." },
1087 { eArgTypeStartAddress, "start-address", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1088 { eArgTypeSummaryString, "summary-string", CommandCompletions::eNoCompletion, { SummaryStringHelpTextCallback, true }, nullptr },
1089 { eArgTypeSymbol, "symbol", CommandCompletions::eSymbolCompletion, { nullptr, false }, "Any symbol name (function name, variable, argument, etc.)" },
1090 { eArgTypeThreadID, "thread-id", CommandCompletions::eNoCompletion, { nullptr, false }, "Thread ID number." },
1091 { eArgTypeThreadIndex, "thread-index", CommandCompletions::eNoCompletion, { nullptr, false }, "Index into the process' list of threads." },
1092 { eArgTypeThreadName, "thread-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The thread's name." },
1093 { eArgTypeTypeName, "type-name", CommandCompletions::eNoCompletion, { nullptr, false }, "A type name." },
1094 { eArgTypeUnsignedInteger, "unsigned-integer", CommandCompletions::eNoCompletion, { nullptr, false }, "An unsigned integer." },
1095 { eArgTypeUnixSignal, "unix-signal", CommandCompletions::eNoCompletion, { nullptr, false }, "A valid Unix signal name or number (e.g. SIGKILL, KILL or 9)." },
1096 { eArgTypeVarName, "variable-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a variable in your program." },
1097 { eArgTypeValue, "value", CommandCompletions::eNoCompletion, { nullptr, false }, "A value could be anything, depending on where and how it is used." },
1098 { eArgTypeWidth, "width", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1099 { eArgTypeNone, "none", CommandCompletions::eNoCompletion, { nullptr, false }, "No help available for this." },
1100 { eArgTypePlatform, "platform-name", CommandCompletions::ePlatformPluginCompletion, { nullptr, false }, "The name of an installed platform plug-in . Type 'platform list' to see a complete list of installed platforms." },
1101 { eArgTypeWatchpointID, "watchpt-id", CommandCompletions::eNoCompletion, { nullptr, false }, "Watchpoint IDs are positive integers." },
1102 { eArgTypeWatchpointIDRange, "watchpt-id-list", CommandCompletions::eNoCompletion, { nullptr, false }, "For example, '1-3' or '1 to 3'." },
1103 { eArgTypeWatchType, "watch-type", CommandCompletions::eNoCompletion, { nullptr, false }, "Specify the type for a watchpoint." },
1104 { eArgRawInput, "raw-input", CommandCompletions::eNoCompletion, { nullptr, false }, "Free-form text passed to a command without prior interpretation, allowing spaces without requiring quotes. To pass arguments and free form text put two dashes ' -- ' between the last argument and any raw input." },
1105 { eArgTypeCommand, "command", CommandCompletions::eNoCompletion, { nullptr, false }, "An LLDB Command line command." }
1109 const CommandObject::ArgumentTableEntry *CommandObject::GetArgumentTable() {
1110 // If this assertion fires, then the table above is out of date with the
1111 // CommandArgumentType enumeration
1112 assert((sizeof(CommandObject::g_arguments_data) /
1113 sizeof(CommandObject::ArgumentTableEntry)) == eArgTypeLastArg);
1114 return CommandObject::g_arguments_data;