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/lldb-python.h"
12 #include "lldb/Interpreter/CommandObject.h"
20 #include "lldb/Core/Address.h"
21 #include "lldb/Core/ArchSpec.h"
22 #include "lldb/Interpreter/Options.h"
24 // These are for the Sourcename completers.
25 // FIXME: Make a separate file for the completers.
26 #include "lldb/Host/FileSpec.h"
27 #include "lldb/Core/FileSpecList.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/Target.h"
31 #include "lldb/Interpreter/CommandInterpreter.h"
32 #include "lldb/Interpreter/CommandReturnObject.h"
33 #include "lldb/Interpreter/ScriptInterpreter.h"
34 #include "lldb/Interpreter/ScriptInterpreterPython.h"
37 using namespace lldb_private;
39 //-------------------------------------------------------------------------
41 //-------------------------------------------------------------------------
43 CommandObject::CommandObject
45 CommandInterpreter &interpreter,
51 m_interpreter (interpreter),
52 m_cmd_name (name ? name : ""),
59 m_deprecated_command_override_callback (nullptr),
60 m_command_override_callback (nullptr),
61 m_command_override_baton (nullptr)
64 m_cmd_help_short = help;
65 if (syntax && syntax[0])
66 m_cmd_syntax = syntax;
69 CommandObject::~CommandObject ()
74 CommandObject::GetHelp ()
76 return m_cmd_help_short.c_str();
80 CommandObject::GetHelpLong ()
82 return m_cmd_help_long.c_str();
86 CommandObject::GetSyntax ()
88 if (m_cmd_syntax.length() == 0)
90 StreamString syntax_str;
91 syntax_str.Printf ("%s", GetCommandName());
92 if (GetOptions() != nullptr)
93 syntax_str.Printf (" <cmd-options>");
94 if (m_arguments.size() > 0)
96 syntax_str.Printf (" ");
97 if (WantsRawCommandString() && GetOptions() && GetOptions()->NumCommandOptions())
98 syntax_str.Printf("-- ");
99 GetFormattedCommandArguments (syntax_str);
101 m_cmd_syntax = syntax_str.GetData ();
104 return m_cmd_syntax.c_str();
108 CommandObject::GetCommandName ()
110 return m_cmd_name.c_str();
114 CommandObject::SetCommandName (const char *name)
120 CommandObject::SetHelp (const char *cstr)
122 m_cmd_help_short = cstr;
126 CommandObject::SetHelpLong (const char *cstr)
128 m_cmd_help_long = cstr;
132 CommandObject::SetHelpLong (std::string str)
134 m_cmd_help_long = str;
138 CommandObject::SetSyntax (const char *cstr)
144 CommandObject::GetOptions ()
146 // By default commands don't have options unless this virtual function
147 // is overridden by base classes.
152 CommandObject::ParseOptions
155 CommandReturnObject &result
158 // See if the subclass has options?
159 Options *options = GetOptions();
160 if (options != nullptr)
163 options->NotifyOptionParsingStarting();
165 // ParseOptions calls getopt_long_only, which always skips the zero'th item in the array and starts at position 1,
166 // so we need to push a dummy value into position zero.
167 args.Unshift("dummy_string");
168 error = args.ParseOptions (*options);
170 // The "dummy_string" will have already been removed by ParseOptions,
171 // so no need to remove it.
174 error = options->NotifyOptionParsingFinished();
178 if (options->VerifyOptions (result))
183 const char *error_cstr = error.AsCString();
186 // We got an error string, lets use that
187 result.AppendError(error_cstr);
191 // No error string, output the usage information into result
192 options->GenerateOptionUsage (result.GetErrorStream(), this);
195 result.SetStatus (eReturnStatusFailed);
204 CommandObject::CheckRequirements (CommandReturnObject &result)
206 #ifdef LLDB_CONFIGURATION_DEBUG
207 // Nothing should be stored in m_exe_ctx between running commands as m_exe_ctx
208 // has shared pointers to the target, process, thread and frame and we don't
209 // want any CommandObject instances to keep any of these objects around
210 // longer than for a single command. Every command should call
211 // CommandObject::Cleanup() after it has completed
212 assert (m_exe_ctx.GetTargetPtr() == NULL);
213 assert (m_exe_ctx.GetProcessPtr() == NULL);
214 assert (m_exe_ctx.GetThreadPtr() == NULL);
215 assert (m_exe_ctx.GetFramePtr() == NULL);
218 // Lock down the interpreter's execution context prior to running the
219 // command so we guarantee the selected target, process, thread and frame
220 // can't go away during the execution
221 m_exe_ctx = m_interpreter.GetExecutionContext();
223 const uint32_t flags = GetFlags().Get();
224 if (flags & (eFlagRequiresTarget |
225 eFlagRequiresProcess |
226 eFlagRequiresThread |
228 eFlagTryTargetAPILock ))
231 if ((flags & eFlagRequiresTarget) && !m_exe_ctx.HasTargetScope())
233 result.AppendError (GetInvalidTargetDescription());
237 if ((flags & eFlagRequiresProcess) && !m_exe_ctx.HasProcessScope())
239 if (!m_exe_ctx.HasTargetScope())
240 result.AppendError (GetInvalidTargetDescription());
242 result.AppendError (GetInvalidProcessDescription());
246 if ((flags & eFlagRequiresThread) && !m_exe_ctx.HasThreadScope())
248 if (!m_exe_ctx.HasTargetScope())
249 result.AppendError (GetInvalidTargetDescription());
250 else if (!m_exe_ctx.HasProcessScope())
251 result.AppendError (GetInvalidProcessDescription());
253 result.AppendError (GetInvalidThreadDescription());
257 if ((flags & eFlagRequiresFrame) && !m_exe_ctx.HasFrameScope())
259 if (!m_exe_ctx.HasTargetScope())
260 result.AppendError (GetInvalidTargetDescription());
261 else if (!m_exe_ctx.HasProcessScope())
262 result.AppendError (GetInvalidProcessDescription());
263 else if (!m_exe_ctx.HasThreadScope())
264 result.AppendError (GetInvalidThreadDescription());
266 result.AppendError (GetInvalidFrameDescription());
270 if ((flags & eFlagRequiresRegContext) && (m_exe_ctx.GetRegisterContext() == nullptr))
272 result.AppendError (GetInvalidRegContextDescription());
276 if (flags & eFlagTryTargetAPILock)
278 Target *target = m_exe_ctx.GetTargetPtr();
280 m_api_locker.Lock (target->GetAPIMutex());
284 if (GetFlags().AnySet (CommandObject::eFlagProcessMustBeLaunched | CommandObject::eFlagProcessMustBePaused))
286 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
287 if (process == nullptr)
289 // A process that is not running is considered paused.
290 if (GetFlags().Test(CommandObject::eFlagProcessMustBeLaunched))
292 result.AppendError ("Process must exist.");
293 result.SetStatus (eReturnStatusFailed);
299 StateType state = process->GetState();
303 case eStateSuspended:
308 case eStateConnected:
309 case eStateAttaching:
310 case eStateLaunching:
314 if (GetFlags().Test(CommandObject::eFlagProcessMustBeLaunched))
316 result.AppendError ("Process must be launched.");
317 result.SetStatus (eReturnStatusFailed);
324 if (GetFlags().Test(CommandObject::eFlagProcessMustBePaused))
326 result.AppendError ("Process is running. Use 'process interrupt' to pause execution.");
327 result.SetStatus (eReturnStatusFailed);
337 CommandObject::Cleanup ()
340 m_api_locker.Unlock();
344 class CommandDictCommandPartialMatch
347 CommandDictCommandPartialMatch (const char *match_str)
349 m_match_str = match_str;
351 bool operator() (const std::pair<std::string, lldb::CommandObjectSP> map_element) const
353 // A NULL or empty string matches everything.
354 if (m_match_str == nullptr || *m_match_str == '\0')
357 return map_element.first.find (m_match_str, 0) == 0;
361 const char *m_match_str;
365 CommandObject::AddNamesMatchingPartialString (CommandObject::CommandMap &in_map, const char *cmd_str,
368 int number_added = 0;
369 CommandDictCommandPartialMatch matcher(cmd_str);
371 CommandObject::CommandMap::iterator matching_cmds = std::find_if (in_map.begin(), in_map.end(), matcher);
373 while (matching_cmds != in_map.end())
376 matches.AppendString((*matching_cmds).first.c_str());
377 matching_cmds = std::find_if (++matching_cmds, in_map.end(), matcher);;
383 CommandObject::HandleCompletion
387 int &cursor_char_position,
388 int match_start_point,
389 int max_return_elements,
394 // Default implmentation of WantsCompletion() is !WantsRawCommandString().
395 // Subclasses who want raw command string but desire, for example,
396 // argument completion should override WantsCompletion() to return true,
398 if (WantsRawCommandString() && !WantsCompletion())
400 // FIXME: Abstract telling the completion to insert the completion character.
406 // Can we do anything generic with the options?
407 Options *cur_options = GetOptions();
408 CommandReturnObject result;
409 OptionElementVector opt_element_vector;
411 if (cur_options != nullptr)
413 // Re-insert the dummy command name string which will have been
415 input.Unshift ("dummy-string");
419 // I stick an element on the end of the input, because if the last element is
420 // option that requires an argument, getopt_long_only will freak out.
422 input.AppendArgument ("<FAKE-VALUE>");
424 input.ParseArgsForCompletion (*cur_options, opt_element_vector, cursor_index);
426 input.DeleteArgumentAtIndex(input.GetArgumentCount() - 1);
428 bool handled_by_options;
429 handled_by_options = cur_options->HandleOptionCompletion (input,
432 cursor_char_position,
437 if (handled_by_options)
438 return matches.GetSize();
441 // If we got here, the last word is not an option or an option argument.
442 return HandleArgumentCompletion (input,
444 cursor_char_position,
454 CommandObject::HelpTextContainsWord (const char *search_word)
456 std::string options_usage_help;
458 bool found_word = false;
460 const char *short_help = GetHelp();
461 const char *long_help = GetHelpLong();
462 const char *syntax_help = GetSyntax();
464 if (short_help && strcasestr (short_help, search_word))
466 else if (long_help && strcasestr (long_help, search_word))
468 else if (syntax_help && strcasestr (syntax_help, search_word))
472 && GetOptions() != nullptr)
474 StreamString usage_help;
475 GetOptions()->GenerateOptionUsage (usage_help, this);
476 if (usage_help.GetSize() > 0)
478 const char *usage_text = usage_help.GetData();
479 if (strcasestr (usage_text, search_word))
488 CommandObject::GetNumArgumentEntries ()
490 return m_arguments.size();
493 CommandObject::CommandArgumentEntry *
494 CommandObject::GetArgumentEntryAtIndex (int idx)
496 if (static_cast<size_t>(idx) < m_arguments.size())
497 return &(m_arguments[idx]);
502 CommandObject::ArgumentTableEntry *
503 CommandObject::FindArgumentDataByType (CommandArgumentType arg_type)
505 const ArgumentTableEntry *table = CommandObject::GetArgumentTable();
507 for (int i = 0; i < eArgTypeLastArg; ++i)
508 if (table[i].arg_type == arg_type)
509 return (ArgumentTableEntry *) &(table[i]);
515 CommandObject::GetArgumentHelp (Stream &str, CommandArgumentType arg_type, CommandInterpreter &interpreter)
517 const ArgumentTableEntry* table = CommandObject::GetArgumentTable();
518 ArgumentTableEntry *entry = (ArgumentTableEntry *) &(table[arg_type]);
520 // The table is *supposed* to be kept in arg_type order, but someone *could* have messed it up...
522 if (entry->arg_type != arg_type)
523 entry = CommandObject::FindArgumentDataByType (arg_type);
528 StreamString name_str;
529 name_str.Printf ("<%s>", entry->arg_name);
531 if (entry->help_function)
533 const char* help_text = entry->help_function();
534 if (!entry->help_function.self_formatting)
536 interpreter.OutputFormattedHelpText (str, name_str.GetData(), "--", help_text,
541 interpreter.OutputHelpText(str, name_str.GetData(), "--", help_text,
546 interpreter.OutputFormattedHelpText (str, name_str.GetData(), "--", entry->help_text, name_str.GetSize());
550 CommandObject::GetArgumentName (CommandArgumentType arg_type)
552 ArgumentTableEntry *entry = (ArgumentTableEntry *) &(CommandObject::GetArgumentTable()[arg_type]);
554 // The table is *supposed* to be kept in arg_type order, but someone *could* have messed it up...
556 if (entry->arg_type != arg_type)
557 entry = CommandObject::FindArgumentDataByType (arg_type);
560 return entry->arg_name;
563 str << "Arg name for type (" << arg_type << ") not in arg table!";
564 return str.GetData();
568 CommandObject::IsPairType (ArgumentRepetitionType arg_repeat_type)
570 if ((arg_repeat_type == eArgRepeatPairPlain)
571 || (arg_repeat_type == eArgRepeatPairOptional)
572 || (arg_repeat_type == eArgRepeatPairPlus)
573 || (arg_repeat_type == eArgRepeatPairStar)
574 || (arg_repeat_type == eArgRepeatPairRange)
575 || (arg_repeat_type == eArgRepeatPairRangeOptional))
581 static CommandObject::CommandArgumentEntry
582 OptSetFiltered(uint32_t opt_set_mask, CommandObject::CommandArgumentEntry &cmd_arg_entry)
584 CommandObject::CommandArgumentEntry ret_val;
585 for (unsigned i = 0; i < cmd_arg_entry.size(); ++i)
586 if (opt_set_mask & cmd_arg_entry[i].arg_opt_set_association)
587 ret_val.push_back(cmd_arg_entry[i]);
591 // Default parameter value of opt_set_mask is LLDB_OPT_SET_ALL, which means take
592 // all the argument data into account. On rare cases where some argument sticks
593 // with certain option sets, this function returns the option set filtered args.
595 CommandObject::GetFormattedCommandArguments (Stream &str, uint32_t opt_set_mask)
597 int num_args = m_arguments.size();
598 for (int i = 0; i < num_args; ++i)
602 CommandArgumentEntry arg_entry =
603 opt_set_mask == LLDB_OPT_SET_ALL ? m_arguments[i]
604 : OptSetFiltered(opt_set_mask, m_arguments[i]);
605 int num_alternatives = arg_entry.size();
607 if ((num_alternatives == 2)
608 && IsPairType (arg_entry[0].arg_repetition))
610 const char *first_name = GetArgumentName (arg_entry[0].arg_type);
611 const char *second_name = GetArgumentName (arg_entry[1].arg_type);
612 switch (arg_entry[0].arg_repetition)
614 case eArgRepeatPairPlain:
615 str.Printf ("<%s> <%s>", first_name, second_name);
617 case eArgRepeatPairOptional:
618 str.Printf ("[<%s> <%s>]", first_name, second_name);
620 case eArgRepeatPairPlus:
621 str.Printf ("<%s> <%s> [<%s> <%s> [...]]", first_name, second_name, first_name, second_name);
623 case eArgRepeatPairStar:
624 str.Printf ("[<%s> <%s> [<%s> <%s> [...]]]", first_name, second_name, first_name, second_name);
626 case eArgRepeatPairRange:
627 str.Printf ("<%s_1> <%s_1> ... <%s_n> <%s_n>", first_name, second_name, first_name, second_name);
629 case eArgRepeatPairRangeOptional:
630 str.Printf ("[<%s_1> <%s_1> ... <%s_n> <%s_n>]", first_name, second_name, first_name, second_name);
632 // Explicitly test for all the rest of the cases, so if new types get added we will notice the
633 // missing case statement(s).
634 case eArgRepeatPlain:
635 case eArgRepeatOptional:
638 case eArgRepeatRange:
639 // These should not be reached, as they should fail the IsPairType test above.
646 for (int j = 0; j < num_alternatives; ++j)
649 names.Printf (" | ");
650 names.Printf ("%s", GetArgumentName (arg_entry[j].arg_type));
652 switch (arg_entry[0].arg_repetition)
654 case eArgRepeatPlain:
655 str.Printf ("<%s>", names.GetData());
658 str.Printf ("<%s> [<%s> [...]]", names.GetData(), names.GetData());
661 str.Printf ("[<%s> [<%s> [...]]]", names.GetData(), names.GetData());
663 case eArgRepeatOptional:
664 str.Printf ("[<%s>]", names.GetData());
666 case eArgRepeatRange:
667 str.Printf ("<%s_1> .. <%s_n>", names.GetData(), names.GetData());
669 // Explicitly test for all the rest of the cases, so if new types get added we will notice the
670 // missing case statement(s).
671 case eArgRepeatPairPlain:
672 case eArgRepeatPairOptional:
673 case eArgRepeatPairPlus:
674 case eArgRepeatPairStar:
675 case eArgRepeatPairRange:
676 case eArgRepeatPairRangeOptional:
677 // These should not be hit, as they should pass the IsPairType test above, and control should
678 // have gone into the other branch of the if statement.
686 CommandObject::LookupArgumentName (const char *arg_name)
688 CommandArgumentType return_type = eArgTypeLastArg;
690 std::string arg_name_str (arg_name);
691 size_t len = arg_name_str.length();
692 if (arg_name[0] == '<'
693 && arg_name[len-1] == '>')
694 arg_name_str = arg_name_str.substr (1, len-2);
696 const ArgumentTableEntry *table = GetArgumentTable();
697 for (int i = 0; i < eArgTypeLastArg; ++i)
698 if (arg_name_str.compare (table[i].arg_name) == 0)
699 return_type = g_arguments_data[i].arg_type;
705 RegisterNameHelpTextCallback ()
707 return "Register names can be specified using the architecture specific names. "
708 "They can also be specified using generic names. Not all generic entities have "
709 "registers backing them on all architectures. When they don't the generic name "
710 "will return an error.\n"
711 "The generic names defined in lldb are:\n"
713 "pc - program counter register\n"
714 "ra - return address register\n"
715 "fp - frame pointer register\n"
716 "sp - stack pointer register\n"
717 "flags - the flags register\n"
718 "arg{1-6} - integer argument passing registers.\n";
722 BreakpointIDHelpTextCallback ()
724 return "Breakpoint ID's consist major and minor numbers; the major number "
725 "corresponds to the single entity that was created with a 'breakpoint set' "
726 "command; the minor numbers correspond to all the locations that were actually "
727 "found/set based on the major breakpoint. A full breakpoint ID might look like "
728 "3.14, meaning the 14th location set for the 3rd breakpoint. You can specify "
729 "all the locations of a breakpoint by just indicating the major breakpoint "
730 "number. A valid breakpoint id consists either of just the major id number, "
731 "or the major number, a dot, and the location number (e.g. 3 or 3.2 could "
732 "both be valid breakpoint ids).";
736 BreakpointIDRangeHelpTextCallback ()
738 return "A 'breakpoint id list' is a manner of specifying multiple breakpoints. "
739 "This can be done through several mechanisms. The easiest way is to just "
740 "enter a space-separated list of breakpoint ids. To specify all the "
741 "breakpoint locations under a major breakpoint, you can use the major "
742 "breakpoint number followed by '.*', eg. '5.*' means all the locations under "
743 "breakpoint 5. You can also indicate a range of breakpoints by using "
744 "<start-bp-id> - <end-bp-id>. The start-bp-id and end-bp-id for a range can "
745 "be any valid breakpoint ids. It is not legal, however, to specify a range "
746 "using specific locations that cross major breakpoint numbers. I.e. 3.2 - 3.7"
747 " is legal; 2 - 5 is legal; but 3.2 - 4.4 is not legal.";
751 BreakpointNameHelpTextCallback ()
753 return "A name that can be added to a breakpoint when it is created, or later "
754 "on with the \"breakpoint name add\" command. "
755 "Breakpoint names can be used to specify breakpoints in all the places breakpoint ID's "
756 "and breakpoint ID ranges can be used. As such they provide a convenient way to group breakpoints, "
757 "and to operate on breakpoints you create without having to track the breakpoint number. "
758 "Note, the attributes you set when using a breakpoint name in a breakpoint command don't "
759 "adhere to the name, but instead are set individually on all the breakpoints currently tagged with that name. Future breakpoints "
760 "tagged with that name will not pick up the attributes previously given using that name. "
761 "In order to distinguish breakpoint names from breakpoint ID's and ranges, "
762 "names must start with a letter from a-z or A-Z and cannot contain spaces, \".\" or \"-\". "
763 "Also, breakpoint names can only be applied to breakpoints, not to breakpoint locations.";
767 GDBFormatHelpTextCallback ()
769 return "A GDB format consists of a repeat count, a format letter and a size letter. "
770 "The repeat count is optional and defaults to 1. The format letter is optional "
771 "and defaults to the previous format that was used. The size letter is optional "
772 "and defaults to the previous size that was used.\n"
774 "Format letters include:\n"
778 "u - unsigned decimal\n"
788 "Size letters include:\n"
789 "b - 1 byte (byte)\n"
790 "h - 2 bytes (halfword)\n"
791 "w - 4 bytes (word)\n"
792 "g - 8 bytes (giant)\n"
795 "32xb - show 32 1 byte hexadecimal integer values\n"
796 "16xh - show 16 2 byte hexadecimal integer values\n"
797 "64 - show 64 2 byte hexadecimal integer values (format and size from the last format)\n"
798 "dw - show 1 4 byte decimal integer value\n"
803 FormatHelpTextCallback ()
806 static char* help_text_ptr = nullptr;
809 return help_text_ptr;
812 sstr << "One of the format names (or one-character names) that can be used to show a variable's value:\n";
813 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f+1))
815 if (f != eFormatDefault)
818 char format_char = FormatManager::GetFormatAsFormatChar(f);
820 sstr.Printf("'%c' or ", format_char);
822 sstr.Printf ("\"%s\"", FormatManager::GetFormatAsCString(f));
827 std::string data = sstr.GetString();
829 help_text_ptr = new char[data.length()+1];
831 data.copy(help_text_ptr, data.length());
833 return help_text_ptr;
837 LanguageTypeHelpTextCallback ()
839 static char* help_text_ptr = nullptr;
842 return help_text_ptr;
845 sstr << "One of the following languages:\n";
847 for (unsigned int l = eLanguageTypeUnknown; l < eNumLanguageTypes; ++l)
849 sstr << " " << LanguageRuntime::GetNameForLanguageType(static_cast<LanguageType>(l)) << "\n";
854 std::string data = sstr.GetString();
856 help_text_ptr = new char[data.length()+1];
858 data.copy(help_text_ptr, data.length());
860 return help_text_ptr;
864 SummaryStringHelpTextCallback()
867 "A summary string is a way to extract information from variables in order to present them using a summary.\n"
868 "Summary strings contain static text, variables, scopes and control sequences:\n"
869 " - Static text can be any sequence of non-special characters, i.e. anything but '{', '}', '$', or '\\'.\n"
870 " - Variables are sequences of characters beginning with ${, ending with } and that contain symbols in the format described below.\n"
871 " - Scopes are any sequence of text between { and }. Anything included in a scope will only appear in the output summary if there were no errors.\n"
872 " - Control sequences are the usual C/C++ '\\a', '\\n', ..., plus '\\$', '\\{' and '\\}'.\n"
873 "A summary string works by copying static text verbatim, turning control sequences into their character counterpart, expanding variables and trying to expand scopes.\n"
874 "A variable is expanded by giving it a value other than its textual representation, and the way this is done depends on what comes after the ${ marker.\n"
875 "The most common sequence if ${var followed by an expression path, which is the text one would type to access a member of an aggregate types, given a variable of that type"
876 " (e.g. if type T has a member named x, which has a member named y, and if t is of type T, the expression path would be .x.y and the way to fit that into a summary string would be"
877 " ${var.x.y}). You can also use ${*var followed by an expression path and in that case the object referred by the path will be dereferenced before being displayed."
878 " If the object is not a pointer, doing so will cause an error. For additional details on expression paths, you can type 'help expr-path'. \n"
879 "By default, summary strings attempt to display the summary for any variable they reference, and if that fails the value. If neither can be shown, nothing is displayed."
880 "In a summary string, you can also use an array index [n], or a slice-like range [n-m]. This can have two different meanings depending on what kind of object the expression"
882 " - if it is a scalar type (any basic type like int, float, ...) the expression is a bitfield, i.e. the bits indicated by the indexing operator are extracted out of the number"
883 " and displayed as an individual variable\n"
884 " - if it is an array or pointer the array items indicated by the indexing operator are shown as the result of the variable. if the expression is an array, real array items are"
885 " printed; if it is a pointer, the pointer-as-array syntax is used to obtain the values (this means, the latter case can have no range checking)\n"
886 "If you are trying to display an array for which the size is known, you can also use [] instead of giving an exact range. This has the effect of showing items 0 thru size - 1.\n"
887 "Additionally, a variable can contain an (optional) format code, as in ${var.x.y%code}, where code can be any of the valid formats described in 'help format', or one of the"
888 " special symbols only allowed as part of a variable:\n"
889 " %V: show the value of the object by default\n"
890 " %S: show the summary of the object by default\n"
891 " %@: show the runtime-provided object description (for Objective-C, it calls NSPrintForDebugger; for C/C++ it does nothing)\n"
892 " %L: show the location of the object (memory address or a register name)\n"
893 " %#: show the number of children of the object\n"
894 " %T: show the type of the object\n"
895 "Another variable that you can use in summary strings is ${svar . This sequence works exactly like ${var, including the fact that ${*svar is an allowed sequence, but uses"
896 " the object's synthetic children provider instead of the actual objects. For instance, if you are using STL synthetic children providers, the following summary string would"
897 " count the number of actual elements stored in an std::list:\n"
898 "type summary add -s \"${svar%#}\" -x \"std::list<\"";
902 ExprPathHelpTextCallback()
905 "An expression path is the sequence of symbols that is used in C/C++ to access a member variable of an aggregate object (class).\n"
906 "For instance, given a class:\n"
912 "the expression to read item b in the item pointed to by next for foo aFoo would be aFoo.next->b.\n"
913 "Given that aFoo could just be any object of type foo, the string '.next->b' is the expression path, because it can be attached to any foo instance to achieve the effect.\n"
914 "Expression paths in LLDB include dot (.) and arrow (->) operators, and most commands using expression paths have ways to also accept the star (*) operator.\n"
915 "The meaning of these operators is the same as the usual one given to them by the C/C++ standards.\n"
916 "LLDB also has support for indexing ([ ]) in expression paths, and extends the traditional meaning of the square brackets operator to allow bitfield extraction:\n"
917 "for objects of native types (int, float, char, ...) saying '[n-m]' as an expression path (where n and m are any positive integers, e.g. [3-5]) causes LLDB to extract"
918 " bits n thru m from the value of the variable. If n == m, [n] is also allowed as a shortcut syntax. For arrays and pointers, expression paths can only contain one index"
919 " and the meaning of the operation is the same as the one defined by C/C++ (item extraction). Some commands extend bitfield-like syntax for arrays and pointers with the"
920 " meaning of array slicing (taking elements n thru m inside the array or pointed-to memory).";
924 CommandObject::GenerateHelpText (CommandReturnObject &result)
926 GenerateHelpText(result.GetOutputStream());
928 result.SetStatus (eReturnStatusSuccessFinishNoResult);
932 CommandObject::GenerateHelpText (Stream &output_strm)
934 CommandInterpreter& interpreter = GetCommandInterpreter();
935 if (GetOptions() != nullptr)
937 if (WantsRawCommandString())
939 std::string help_text (GetHelp());
940 help_text.append (" This command takes 'raw' input (no need to quote stuff).");
941 interpreter.OutputFormattedHelpText (output_strm, "", "", help_text.c_str(), 1);
944 interpreter.OutputFormattedHelpText (output_strm, "", "", GetHelp(), 1);
945 output_strm.Printf ("\nSyntax: %s\n", GetSyntax());
946 GetOptions()->GenerateOptionUsage (output_strm, this);
947 const char *long_help = GetHelpLong();
948 if ((long_help != nullptr)
949 && (strlen (long_help) > 0))
950 output_strm.Printf ("\n%s", long_help);
951 if (WantsRawCommandString() && !WantsCompletion())
953 // Emit the message about using ' -- ' between the end of the command options and the raw input
954 // conditionally, i.e., only if the command object does not want completion.
955 interpreter.OutputFormattedHelpText (output_strm, "", "",
956 "\nIMPORTANT NOTE: Because this command takes 'raw' input, if you use any command options"
957 " you must use ' -- ' between the end of the command options and the beginning of the raw input.", 1);
959 else if (GetNumArgumentEntries() > 0
961 && GetOptions()->NumCommandOptions() > 0)
963 // Also emit a warning about using "--" in case you are using a command that takes options and arguments.
964 interpreter.OutputFormattedHelpText (output_strm, "", "",
965 "\nThis command takes options and free-form arguments. If your arguments resemble"
966 " option specifiers (i.e., they start with a - or --), you must use ' -- ' between"
967 " the end of the command options and the beginning of the arguments.", 1);
970 else if (IsMultiwordObject())
972 if (WantsRawCommandString())
974 std::string help_text (GetHelp());
975 help_text.append (" This command takes 'raw' input (no need to quote stuff).");
976 interpreter.OutputFormattedHelpText (output_strm, "", "", help_text.c_str(), 1);
979 interpreter.OutputFormattedHelpText (output_strm, "", "", GetHelp(), 1);
980 GenerateHelpText (output_strm);
984 const char *long_help = GetHelpLong();
985 if ((long_help != nullptr)
986 && (strlen (long_help) > 0))
987 output_strm.Printf ("%s", long_help);
988 else if (WantsRawCommandString())
990 std::string help_text (GetHelp());
991 help_text.append (" This command takes 'raw' input (no need to quote stuff).");
992 interpreter.OutputFormattedHelpText (output_strm, "", "", help_text.c_str(), 1);
995 interpreter.OutputFormattedHelpText (output_strm, "", "", GetHelp(), 1);
996 output_strm.Printf ("\nSyntax: %s\n", GetSyntax());
1001 CommandObject::AddIDsArgumentData(CommandArgumentEntry &arg, CommandArgumentType ID, CommandArgumentType IDRange)
1003 CommandArgumentData id_arg;
1004 CommandArgumentData id_range_arg;
1006 // Create the first variant for the first (and only) argument for this command.
1007 id_arg.arg_type = ID;
1008 id_arg.arg_repetition = eArgRepeatOptional;
1010 // Create the second variant for the first (and only) argument for this command.
1011 id_range_arg.arg_type = IDRange;
1012 id_range_arg.arg_repetition = eArgRepeatOptional;
1014 // The first (and only) argument for this command could be either an id or an id_range.
1015 // Push both variants into the entry for the first argument for this command.
1016 arg.push_back(id_arg);
1017 arg.push_back(id_range_arg);
1021 CommandObject::GetArgumentTypeAsCString (const lldb::CommandArgumentType arg_type)
1023 if (arg_type >=0 && arg_type < eArgTypeLastArg)
1024 return g_arguments_data[arg_type].arg_name;
1030 CommandObject::GetArgumentDescriptionAsCString (const lldb::CommandArgumentType arg_type)
1032 if (arg_type >=0 && arg_type < eArgTypeLastArg)
1033 return g_arguments_data[arg_type].help_text;
1038 CommandObject::GetDummyTarget()
1040 return m_interpreter.GetDebugger().GetDummyTarget();
1044 CommandObject::GetSelectedOrDummyTarget(bool prefer_dummy)
1046 return m_interpreter.GetDebugger().GetSelectedOrDummyTarget(prefer_dummy);
1050 CommandObjectParsed::Execute (const char *args_string, CommandReturnObject &result)
1052 bool handled = false;
1053 Args cmd_args (args_string);
1054 if (HasOverrideCallback())
1056 Args full_args (GetCommandName ());
1057 full_args.AppendArguments(cmd_args);
1058 handled = InvokeOverrideCallback (full_args.GetConstArgumentVector(), result);
1062 for (size_t i = 0; i < cmd_args.GetArgumentCount(); ++i)
1064 const char *tmp_str = cmd_args.GetArgumentAtIndex (i);
1065 if (tmp_str[0] == '`') // back-quote
1066 cmd_args.ReplaceArgumentAtIndex (i, m_interpreter.ProcessEmbeddedScriptCommands (tmp_str));
1069 if (CheckRequirements(result))
1071 if (ParseOptions (cmd_args, result))
1073 // Call the command-specific version of 'Execute', passing it the already processed arguments.
1074 handled = DoExecute (cmd_args, result);
1084 CommandObjectRaw::Execute (const char *args_string, CommandReturnObject &result)
1086 bool handled = false;
1087 if (HasOverrideCallback())
1089 std::string full_command (GetCommandName ());
1090 full_command += ' ';
1091 full_command += args_string;
1092 const char *argv[2] = { nullptr, nullptr };
1093 argv[0] = full_command.c_str();
1094 handled = InvokeOverrideCallback (argv, result);
1098 if (CheckRequirements(result))
1099 handled = DoExecute (args_string, result);
1107 const char *arch_helper()
1109 static StreamString g_archs_help;
1110 if (g_archs_help.Empty())
1113 ArchSpec::AutoComplete(nullptr, archs);
1114 g_archs_help.Printf("These are the supported architecture names:\n");
1115 archs.Join("\n", g_archs_help);
1117 return g_archs_help.GetData();
1120 CommandObject::ArgumentTableEntry
1121 CommandObject::g_arguments_data[] =
1123 { eArgTypeAddress, "address", CommandCompletions::eNoCompletion, { nullptr, false }, "A valid address in the target program's execution space." },
1124 { eArgTypeAddressOrExpression, "address-expression", CommandCompletions::eNoCompletion, { nullptr, false }, "An expression that resolves to an address." },
1125 { eArgTypeAliasName, "alias-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of an abbreviation (alias) for a debugger command." },
1126 { 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.)" },
1127 { eArgTypeArchitecture, "arch", CommandCompletions::eArchitectureCompletion, { arch_helper, true }, "The architecture name, e.g. i386 or x86_64." },
1128 { eArgTypeBoolean, "boolean", CommandCompletions::eNoCompletion, { nullptr, false }, "A Boolean value: 'true' or 'false'" },
1129 { eArgTypeBreakpointID, "breakpt-id", CommandCompletions::eNoCompletion, { BreakpointIDHelpTextCallback, false }, nullptr },
1130 { eArgTypeBreakpointIDRange, "breakpt-id-list", CommandCompletions::eNoCompletion, { BreakpointIDRangeHelpTextCallback, false }, nullptr },
1131 { eArgTypeBreakpointName, "breakpoint-name", CommandCompletions::eNoCompletion, { BreakpointNameHelpTextCallback, false }, nullptr },
1132 { eArgTypeByteSize, "byte-size", CommandCompletions::eNoCompletion, { nullptr, false }, "Number of bytes to use." },
1133 { eArgTypeClassName, "class-name", CommandCompletions::eNoCompletion, { nullptr, false }, "Then name of a class from the debug information in the program." },
1134 { eArgTypeCommandName, "cmd-name", CommandCompletions::eNoCompletion, { nullptr, false }, "A debugger command (may be multiple words), without any options or arguments." },
1135 { eArgTypeCount, "count", CommandCompletions::eNoCompletion, { nullptr, false }, "An unsigned integer." },
1136 { eArgTypeDirectoryName, "directory", CommandCompletions::eDiskDirectoryCompletion, { nullptr, false }, "A directory name." },
1137 { 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" },
1138 { eArgTypeDescriptionVerbosity, "description-verbosity", CommandCompletions::eNoCompletion, { nullptr, false }, "How verbose the output of 'po' should be." },
1139 { eArgTypeEndAddress, "end-address", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1140 { eArgTypeExpression, "expr", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1141 { eArgTypeExpressionPath, "expr-path", CommandCompletions::eNoCompletion, { ExprPathHelpTextCallback, true }, nullptr },
1142 { eArgTypeExprFormat, "expression-format", CommandCompletions::eNoCompletion, { nullptr, false }, "[ [bool|b] | [bin] | [char|c] | [oct|o] | [dec|i|d|u] | [hex|x] | [float|f] | [cstr|s] ]" },
1143 { eArgTypeFilename, "filename", CommandCompletions::eDiskFileCompletion, { nullptr, false }, "The name of a file (can include path)." },
1144 { eArgTypeFormat, "format", CommandCompletions::eNoCompletion, { FormatHelpTextCallback, true }, nullptr },
1145 { eArgTypeFrameIndex, "frame-index", CommandCompletions::eNoCompletion, { nullptr, false }, "Index into a thread's list of frames." },
1146 { eArgTypeFullName, "fullname", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1147 { eArgTypeFunctionName, "function-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a function." },
1148 { eArgTypeFunctionOrSymbol, "function-or-symbol", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a function or symbol." },
1149 { eArgTypeGDBFormat, "gdb-format", CommandCompletions::eNoCompletion, { GDBFormatHelpTextCallback, true }, nullptr },
1150 { eArgTypeHelpText, "help-text", CommandCompletions::eNoCompletion, { nullptr, false }, "Text to be used as help for some other entity in LLDB" },
1151 { eArgTypeIndex, "index", CommandCompletions::eNoCompletion, { nullptr, false }, "An index into a list." },
1152 { eArgTypeLanguage, "language", CommandCompletions::eNoCompletion, { LanguageTypeHelpTextCallback, true }, nullptr },
1153 { eArgTypeLineNum, "linenum", CommandCompletions::eNoCompletion, { nullptr, false }, "Line number in a source file." },
1154 { 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." },
1155 { 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)." },
1156 { eArgTypeMethod, "method", CommandCompletions::eNoCompletion, { nullptr, false }, "A C++ method name." },
1157 { eArgTypeName, "name", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1158 { eArgTypeNewPathPrefix, "new-path-prefix", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1159 { eArgTypeNumLines, "num-lines", CommandCompletions::eNoCompletion, { nullptr, false }, "The number of lines to use." },
1160 { eArgTypeNumberPerLine, "number-per-line", CommandCompletions::eNoCompletion, { nullptr, false }, "The number of items per line to display." },
1161 { eArgTypeOffset, "offset", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1162 { eArgTypeOldPathPrefix, "old-path-prefix", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1163 { eArgTypeOneLiner, "one-line-command", CommandCompletions::eNoCompletion, { nullptr, false }, "A command that is entered as a single line of text." },
1164 { eArgTypePath, "path", CommandCompletions::eDiskFileCompletion, { nullptr, false }, "Path." },
1165 { eArgTypePermissionsNumber, "perms-numeric", CommandCompletions::eNoCompletion, { nullptr, false }, "Permissions given as an octal number (e.g. 755)." },
1166 { eArgTypePermissionsString, "perms=string", CommandCompletions::eNoCompletion, { nullptr, false }, "Permissions given as a string value (e.g. rw-r-xr--)." },
1167 { eArgTypePid, "pid", CommandCompletions::eNoCompletion, { nullptr, false }, "The process ID number." },
1168 { eArgTypePlugin, "plugin", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1169 { eArgTypeProcessName, "process-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of the process." },
1170 { eArgTypePythonClass, "python-class", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a Python class." },
1171 { eArgTypePythonFunction, "python-function", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a Python function." },
1172 { eArgTypePythonScript, "python-script", CommandCompletions::eNoCompletion, { nullptr, false }, "Source code written in Python." },
1173 { eArgTypeQueueName, "queue-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of the thread queue." },
1174 { eArgTypeRegisterName, "register-name", CommandCompletions::eNoCompletion, { RegisterNameHelpTextCallback, true }, nullptr },
1175 { eArgTypeRegularExpression, "regular-expression", CommandCompletions::eNoCompletion, { nullptr, false }, "A regular expression." },
1176 { eArgTypeRunArgs, "run-args", CommandCompletions::eNoCompletion, { nullptr, false }, "Arguments to be passed to the target program when it starts executing." },
1177 { eArgTypeRunMode, "run-mode", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1178 { eArgTypeScriptedCommandSynchronicity, "script-cmd-synchronicity", CommandCompletions::eNoCompletion, { nullptr, false }, "The synchronicity to use to run scripted commands with regard to LLDB event system." },
1179 { eArgTypeScriptLang, "script-language", CommandCompletions::eNoCompletion, { nullptr, false }, "The scripting language to be used for script-based commands. Currently only Python is valid." },
1180 { eArgTypeSearchWord, "search-word", CommandCompletions::eNoCompletion, { nullptr, false }, "The word for which you wish to search for information about." },
1181 { eArgTypeSelector, "selector", CommandCompletions::eNoCompletion, { nullptr, false }, "An Objective-C selector name." },
1182 { 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)." },
1183 { 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)." },
1184 { eArgTypeSettingPrefix, "setting-prefix", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a settable internal debugger variable up to a dot ('.'), e.g. 'target.process.'" },
1185 { 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." },
1186 { eArgTypeShlibName, "shlib-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a shared library." },
1187 { eArgTypeSourceFile, "source-file", CommandCompletions::eSourceFileCompletion, { nullptr, false }, "The name of a source file.." },
1188 { eArgTypeSortOrder, "sort-order", CommandCompletions::eNoCompletion, { nullptr, false }, "Specify a sort order when dumping lists." },
1189 { eArgTypeStartAddress, "start-address", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1190 { eArgTypeSummaryString, "summary-string", CommandCompletions::eNoCompletion, { SummaryStringHelpTextCallback, true }, nullptr },
1191 { eArgTypeSymbol, "symbol", CommandCompletions::eSymbolCompletion, { nullptr, false }, "Any symbol name (function name, variable, argument, etc.)" },
1192 { eArgTypeThreadID, "thread-id", CommandCompletions::eNoCompletion, { nullptr, false }, "Thread ID number." },
1193 { eArgTypeThreadIndex, "thread-index", CommandCompletions::eNoCompletion, { nullptr, false }, "Index into the process' list of threads." },
1194 { eArgTypeThreadName, "thread-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The thread's name." },
1195 { eArgTypeUnsignedInteger, "unsigned-integer", CommandCompletions::eNoCompletion, { nullptr, false }, "An unsigned integer." },
1196 { eArgTypeUnixSignal, "unix-signal", CommandCompletions::eNoCompletion, { nullptr, false }, "A valid Unix signal name or number (e.g. SIGKILL, KILL or 9)." },
1197 { eArgTypeVarName, "variable-name", CommandCompletions::eNoCompletion, { nullptr, false }, "The name of a variable in your program." },
1198 { eArgTypeValue, "value", CommandCompletions::eNoCompletion, { nullptr, false }, "A value could be anything, depending on where and how it is used." },
1199 { eArgTypeWidth, "width", CommandCompletions::eNoCompletion, { nullptr, false }, "Help text goes here." },
1200 { eArgTypeNone, "none", CommandCompletions::eNoCompletion, { nullptr, false }, "No help available for this." },
1201 { 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." },
1202 { eArgTypeWatchpointID, "watchpt-id", CommandCompletions::eNoCompletion, { nullptr, false }, "Watchpoint IDs are positive integers." },
1203 { eArgTypeWatchpointIDRange, "watchpt-id-list", CommandCompletions::eNoCompletion, { nullptr, false }, "For example, '1-3' or '1 to 3'." },
1204 { eArgTypeWatchType, "watch-type", CommandCompletions::eNoCompletion, { nullptr, false }, "Specify the type for a watchpoint." }
1207 const CommandObject::ArgumentTableEntry*
1208 CommandObject::GetArgumentTable ()
1210 // If this assertion fires, then the table above is out of date with the CommandArgumentType enumeration
1211 assert ((sizeof (CommandObject::g_arguments_data) / sizeof (CommandObject::ArgumentTableEntry)) == eArgTypeLastArg);
1212 return CommandObject::g_arguments_data;