13#include "lldb/Host/Config.h"
41#pragma mark CommandObjectFrameDiagnose
47#define LLDB_OPTIONS_frame_diag
48#include "CommandOptions.inc"
62 switch (short_option) {
69 if (option_arg.getAsInteger(0, *
address)) {
71 error.SetErrorStringWithFormat(
"invalid address argument '%s'",
72 option_arg.str().c_str());
78 if (option_arg.getAsInteger(0, *
offset)) {
80 error.SetErrorStringWithFormat(
"invalid offset argument '%s'",
81 option_arg.str().c_str());
86 llvm_unreachable(
"Unimplemented option");
99 return llvm::ArrayRef(g_frame_diag_options);
104 std::optional<ConstString>
reg;
110 "Try to determine what path the current stop "
111 "location used to get to a register or address",
113 eCommandRequiresThread | eCommandTryTargetAPILock |
114 eCommandProcessMustBeLaunched |
115 eCommandProcessMustBePaused) {
133 "`frame diagnose --address` is incompatible with other arguments.");
138 valobj_sp = frame_sp->GuessValueForRegisterAndOffset(
143 result.
AppendError(
"No arguments provided, and no stop info.");
160 GetExpressionPathFormat::eGetExpressionPathFormatHonorPointers;
161 valobj_sp->GetExpressionPath(stream, format);
162 stream.PutCString(
" =");
170 assert(valobj_sp.get() &&
"Must have a valid ValueObject to print");
180#pragma mark CommandObjectFrameInfo
188 "List information about the current "
189 "stack frame in the current thread.",
191 eCommandRequiresFrame | eCommandTryTargetAPILock |
192 eCommandProcessMustBeLaunched |
193 eCommandProcessMustBePaused) {}
204#pragma mark CommandObjectFrameSelect
208#define LLDB_OPTIONS_frame_select
209#include "CommandOptions.inc"
223 switch (short_option) {
226 if (option_arg.getAsInteger(0, offset) || offset == INT32_MIN) {
227 error.SetErrorStringWithFormat(
"invalid frame offset argument '%s'",
228 option_arg.str().c_str());
235 llvm_unreachable(
"Unimplemented option");
246 return llvm::ArrayRef(g_frame_select_options);
254 "Select the current stack frame by "
255 "index from within the current thread "
256 "(see 'thread backtrace'.)",
258 eCommandRequiresThread | eCommandTryTargetAPILock |
259 eCommandProcessMustBeLaunched |
260 eCommandProcessMustBePaused) {
282 if (
static_cast<int32_t
>(frame_idx) >=
286 if (frame_idx == 0) {
289 result.
AppendError(
"Already at the bottom of the stack.");
299 const uint32_t frame_requested = frame_idx
303 frame_idx = frame_requested;
307 if (
static_cast<int32_t
>(num_frames - frame_idx) >
311 if (frame_idx == num_frames - 1) {
314 result.
AppendError(
"Already at the top of the stack.");
317 frame_idx = num_frames - 1;
324 "too many arguments; expected frame-index, saw '%s'.\n",
333 if (command[0].ref().getAsInteger(0, frame_idx)) {
360#pragma mark CommandObjectFrameVariable
366 interpreter,
"frame variable",
367 "Show variables for the current stack frame. Defaults to all "
368 "arguments and local variables in scope. Names of argument, "
369 "local, file static and file global variables can be specified.",
371 eCommandRequiresFrame | eCommandTryTargetAPILock |
372 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
373 eCommandRequiresProcess),
378Children of aggregate variables can be specified such as 'var->child.x'. In
379'frame variable', the operators -> and [] do not invoke operator overloads if
380they exist, but directly access the specified element. If you want to trigger
381operator overloads use the expression command to print the variable instead.
383It is worth noting that except for overloaded operators, when printing local
384variables 'expr local_var' and 'frame var local_var' produce the same results.
385However, 'frame variable' is more efficient, since it uses debug information and
386memory reads directly, rather than parsing and evaluating an expression, which
387may even involve JITing and running code in the target program.)");
407 return llvm::StringRef();
409 switch (var_sp->GetScope()) {
424 return llvm::StringRef();
446 llvm_unreachable(
"Unexpected scope value");
455 std::optional<llvm::ArrayRef<VariableSP>>
459 bool any_matches =
false;
460 const size_t previous_num_vars = matches.
GetSize();
470 return matches.
toArrayRef().drop_front(previous_num_vars);
493 if (
error.Fail() && (!variable_list || variable_list->
GetSize() == 0)) {
505 summary_format_sp = std::make_shared<StringSummaryFormat>(
522 if (!command.
empty()) {
527 for (
auto &entry : command) {
529 llvm::StringRef name_str = entry.ref();
532 std::optional<llvm::ArrayRef<VariableSP>> results =
536 "no variables matched the regular expression '%s'.",
544 std::string scope_string;
548 if (!scope_string.empty())
552 var_sp->GetDeclaration().GetFile()) {
553 bool show_fullpaths =
false;
554 bool show_module =
true;
555 if (var_sp->DumpDeclaration(&s, show_fullpaths,
560 if (llvm::Error
error = valobj_sp->Dump(strm, options))
565 if (llvm::Error err = regex.
GetError())
566 result.
AppendError(llvm::toString(std::move(err)));
569 "unknown regex error when compiling '%s'", entry.c_str());
575 uint32_t expr_path_options =
584 std::string scope_string;
588 if (!scope_string.empty())
591 var_sp->GetDeclaration().GetFile()) {
592 var_sp->GetDeclaration().DumpStopContext(&s,
false);
598 valobj_sp->GetPreferredDisplayLanguage());
602 valobj_sp->GetParent() ? entry.c_str() :
nullptr);
603 if (llvm::Error
error = valobj_sp->Dump(output_stream, options))
606 if (
auto error_cstr =
error.AsCString(
nullptr))
610 "unable to find any variable expression path that matches "
618 const size_t num_variables = variable_list->
GetSize();
619 if (num_variables > 0) {
620 for (
size_t i = 0; i < num_variables; i++) {
624 std::string scope_string;
635 if (valobj_sp->IsInScope()) {
636 if (!valobj_sp->GetTargetSP()
637 ->GetDisplayRuntimeSupportValues() &&
638 valobj_sp->IsRuntimeSupportValue())
641 if (!scope_string.empty())
645 var_sp->GetDeclaration().GetFile()) {
646 var_sp->GetDeclaration().DumpStopContext(&s,
false);
652 valobj_sp->GetPreferredDisplayLanguage());
654 var_sp ? var_sp->GetName().AsCString() :
nullptr);
655 if (llvm::Error
error =
669 if (recognized_frame) {
671 recognized_frame->GetRecognizedArguments();
672 if (recognized_arg_list) {
673 for (
auto &rec_value_sp : recognized_arg_list->GetObjects()) {
676 rec_value_sp->GetPreferredDisplayLanguage());
678 if (llvm::Error
error =
703#pragma mark CommandObjectFrameRecognizer
705#define LLDB_OPTIONS_frame_recognizer_add
706#include "CommandOptions.inc"
720 switch (short_option) {
727 error.SetErrorStringWithFormat(
728 "invalid boolean value '%s' passed for -f option",
729 option_arg.str().c_str());
739 m_symbols.push_back(std::string(option_arg));
745 llvm_unreachable(
"Unimplemented option");
760 return llvm::ArrayRef(g_frame_recognizer_add_options);
781 "Add a new frame recognizer.", nullptr) {
783Frame recognizers allow for retrieving information about special frames based on
784ABI, arguments or other special properties of that frame, even without source
785code or debug info. Currently, one use case is to extract function arguments
786that would otherwise be unaccesible, or augment existing arguments.
788Adding a custom frame recognizer is possible by implementing a Python class
789and using the 'frame recognizer add' command. The Python class should have a
790'get_recognized_arguments' method and it will receive an argument of type
791lldb.SBFrame representing the current frame that we are trying to recognize.
792The method should return a (possibly empty) list of lldb.SBValue objects that
793represent the recognized arguments.
795An example of a recognizer that retrieves the file descriptor values from libc
796functions 'read', 'write' and 'close' follows:
798 class LibcFdRecognizer(object):
799 def get_recognized_arguments(self, frame):
800 if frame.name in ["read", "write", "close"]:
801 fd = frame.EvaluateExpression("$arg1").unsigned
802 target = frame.thread.process.target
803 value = target.CreateValueFromExpression("fd", "(int)%d" % fd)
807The file containing this implementation can be imported via 'command script
808import' and then we can register this recognizer with 'frame recognizer add'.
809It's important to restrict the recognizer to the libc library (which is
810libsystem_kernel.dylib on macOS) to avoid matching functions with the same name
813(lldb) command script import .../fd_recognizer.py
814(lldb) frame recognizer add -l fd_recognizer.LibcFdRecognizer -n read -s libsystem_kernel.dylib
816When the program is stopped at the beginning of the 'read' function in libc, we
817can view the recognizer arguments in 'frame variable':
822* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.3
823 frame #0: 0x00007fff06013ca0 libsystem_kernel.dylib`read
834#if LLDB_ENABLE_PYTHON
837 "%s needs a Python class name (-l argument).\n",
m_cmd_name.c_str());
849 "%s needs at least one symbol name (-n argument).\n",
856 "%s needs only one symbol regular expression (-n argument).\n",
865 result.
AppendWarning(
"The provided class does not exist - please define it "
866 "before attempting to use this frame recognizer");
895 "Delete all frame recognizers.", nullptr) {}
910 "Delete an existing frame recognizer by id.",
924 [&request](uint32_t rid, std::string rname, std::string module,
925 llvm::ArrayRef<lldb_private::ConstString> symbols,
929 rname =
"(internal)";
933 strm <<
", module " << module;
934 if (!symbols.empty())
935 for (
auto &symbol : symbols)
936 strm <<
", symbol " << symbol;
948 "About to delete all frame recognizers, do you want to do that?",
965 uint32_t recognizer_id;
972 if (!
GetTarget().GetFrameRecognizerManager().RemoveRecognizerWithID(
986 "Show a list of active frame recognizers.",
993 bool any_printed =
false;
995 [&result, &any_printed](
996 uint32_t recognizer_id, std::string name, std::string module,
997 llvm::ArrayRef<ConstString> symbols,
bool regexp) {
1001 name =
"(internal)";
1003 stream << std::to_string(recognizer_id) <<
": " << name;
1004 if (!module.empty())
1005 stream <<
", module " << module;
1006 if (!symbols.empty())
1007 for (
auto &symbol : symbols)
1008 stream <<
", symbol " << symbol;
1010 stream <<
" (regexp)";
1031 interpreter,
"frame recognizer info",
1032 "Show which frame recognizer is applied a stack frame (if any).",
1042 uint32_t frame_index;
1043 if (!llvm::to_integer(frame_index_str, frame_index)) {
1050 if (process ==
nullptr) {
1055 if (thread ==
nullptr) {
1061 "'%s' takes exactly one frame index argument.\n",
m_cmd_name.c_str());
1075 output_stream.
Printf(
"frame %d ", frame_index);
1077 output_stream <<
"is recognized by ";
1078 output_stream << recognizer->GetName();
1080 output_stream <<
"not recognized by any recognizer";
1082 output_stream.
EOL();
1091 interpreter,
"frame recognizer",
1092 "Commands for editing and viewing frame recognizers.",
1093 "frame recognizer [<sub-command-options>] ") {
1111#pragma mark CommandObjectMultiwordFrame
1118 "Commands for selecting and "
1119 "examing the current "
1120 "thread's stack frames.",
1121 "frame <subcommand> [<subcommand-options>]") {
1130#if LLDB_ENABLE_PYTHON
static llvm::raw_ostream & error(Stream &strm)
CommandObjectFrameInfo(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectFrameInfo() override=default
void OptionParsingStarting(ExecutionContext *execution_context) override
std::vector< std::string > m_symbols
bool m_first_instruction_only
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
~CommandOptions() override=default
CommandObjectFrameRecognizerAdd(CommandInterpreter &interpreter)
Options * GetOptions() override
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectFrameRecognizerAdd() override=default
CommandObjectFrameRecognizerClear(CommandInterpreter &interpreter)
~CommandObjectFrameRecognizerClear() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectFrameRecognizerDelete() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The default version handles argument definitions that have only one argument type,...
CommandObjectFrameRecognizerDelete(CommandInterpreter &interpreter)
CommandObjectFrameRecognizerInfo(CommandInterpreter &interpreter)
~CommandObjectFrameRecognizerInfo() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectFrameRecognizerList(CommandInterpreter &interpreter)
~CommandObjectFrameRecognizerList() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectFrameRecognizer() override=default
CommandObjectFrameRecognizer(CommandInterpreter &interpreter)
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
std::optional< int32_t > relative_frame_offset
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
~CommandOptions() override=default
~CommandObjectFrameSelect() override=default
CommandObjectFrameSelect(CommandInterpreter &interpreter)
Options * GetOptions() override
void DoExecute(Args &command, CommandReturnObject &result) override
OptionGroupOptions m_option_group
OptionGroupFormat m_option_format
Options * GetOptions() override
OptionGroupVariable m_option_variable
OptionGroupValueObjectDisplay m_varobj_options
bool ScopeRequested(lldb::ValueType scope)
Returns true if scope matches any of the options in m_option_variable.
llvm::StringRef GetScopeString(VariableSP var_sp)
std::optional< llvm::ArrayRef< VariableSP > > findUniqueRegexMatches(RegularExpression ®ex, VariableList &matches, const VariableList &all_variables)
Finds all the variables in all_variables whose name matches regex, inserting them into matches.
~CommandObjectFrameVariable() override=default
CommandObjectFrameVariable(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
A command line argument class.
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
bool Confirm(llvm::StringRef message, bool default_answer)
void PrintWarningsIfNecessary(Stream &s, const std::string &cmd_name)
CommandObjectMultiwordFrame(CommandInterpreter &interpreter)
~CommandObjectMultiwordFrame() override
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
virtual void SetHelpLong(llvm::StringRef str)
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
ExecutionContext m_exe_ctx
CommandInterpreter & GetCommandInterpreter()
CommandInterpreter & m_interpreter
void AppendMessage(llvm::StringRef in_string)
void void AppendError(llvm::StringRef in_string)
Stream & GetErrorStream()
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
lldb::ReturnStatus GetStatus() const
void void AppendWarning(llvm::StringRef in_string)
Stream & GetOutputStream()
"lldb/Utility/ArgCompletionRequest.h"
void TryCompleteCurrentArg(llvm::StringRef completion, llvm::StringRef description="")
Adds a possible completion string if the completion would complete the current argument.
size_t GetCursorIndex() const
A uniqued constant string class.
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
DumpValueObjectOptions & SetVariableFormatDisplayLanguage(lldb::LanguageType lang=lldb::eLanguageTypeUnknown)
std::function< bool(ConstString, ConstString, const DumpValueObjectOptions &, Stream &)> DeclPrintingHelper
DumpValueObjectOptions & SetDeclPrintingHelper(DeclPrintingHelper helper)
DumpValueObjectOptions & SetRootValueObjectName(const char *name=nullptr)
DumpValueObjectOptions & SetFormat(lldb::Format format=lldb::eFormatDefault)
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
void SetFrameSP(const lldb::StackFrameSP &frame_sp)
Set accessor to set only the frame shared pointer.
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
StackFrame & GetFrameRef() const
Returns a reference to the thread object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
Thread * GetThreadPtr() const
Returns a pointer to the thread object.
bool IsTopLevelFunction()
Get whether this function represents a 'top-level' function.
void Append(OptionGroup *group)
Append options from a OptionGroup class.
DumpValueObjectOptions GetAsDumpOptions(LanguageRuntimeDescriptionDisplayVerbosity lang_descr_verbosity=eLanguageRuntimeDescriptionDisplayVerbosityFull, lldb::Format format=lldb::eFormatDefault, lldb::TypeSummaryImplSP summary_sp=lldb::TypeSummaryImplSP())
lldb::DynamicValueType use_dynamic
OptionValueString summary_string
OptionValueString summary
bool show_recognized_args
bool IsCurrentValueEmpty() const
const char * GetCurrentValue() const
A command line option parsing protocol class.
void GenerateOptionUsage(Stream &strm, CommandObject &cmd, uint32_t screen_width)
std::vector< Option > m_getopt_table
A plug-in interface definition class for debugging a process.
bool IsValid() const
Test if this object contains a valid regular expression.
llvm::Error GetError() const
Return an error if the regular expression failed to compile.
virtual bool CheckObjectExists(const char *name)
Python implementation for frame recognizers.
lldb::StackFrameRecognizerSP GetRecognizerForFrame(lldb::StackFrameSP frame)
void RemoveAllRecognizers()
void ForEach(std::function< void(uint32_t recognizer_id, std::string recognizer_name, std::string module, llvm::ArrayRef< ConstString > symbols, bool regexp)> const &callback)
void AddRecognizer(lldb::StackFrameRecognizerSP recognizer, ConstString module, llvm::ArrayRef< ConstString > symbols, bool first_instruction_only=true)
This base class provides an interface to stack frames.
@ eExpressionPathOptionCheckPtrVsMember
@ eExpressionPathOptionsInspectAnonymousUnions
@ eExpressionPathOptionsAllowDirectIVarAccess
VariableList * GetVariableList(bool get_file_globals, Status *error_ptr)
Retrieve the list of variables that are in scope at this StackFrame's pc.
void DumpUsingSettingsFormat(Stream *strm, bool show_unique=false, const char *frame_marker=nullptr)
Print a description for this frame using the frame-format formatter settings.
lldb::ValueObjectSP GetValueForVariableExpressionPath(llvm::StringRef var_expr, lldb::DynamicValueType use_dynamic, uint32_t options, lldb::VariableSP &var_sp, Status &error)
Create a ValueObject for a variable name / pathname, possibly including simple dereference/child sele...
lldb::ValueObjectSP GetValueObjectForFrameVariable(const lldb::VariableSP &variable_sp, lldb::DynamicValueType use_dynamic)
Create a ValueObject for a given Variable in this StackFrame.
const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
lldb::RecognizedStackFrameSP GetRecognizedFrame()
static lldb::ValueObjectSP GetCrashingDereference(lldb::StopInfoSP &stop_info_sp, lldb::addr_t *crashing_address=nullptr)
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
virtual void Flush()=0
Flush the stream.
size_t EOL()
Output and End of Line character to the stream.
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
A class that represents statistics for a since lldb_private::Target.
StatsSuccessFail & GetFrameVariableStats()
TargetStats & GetStatistics()
StackFrameRecognizerManager & GetFrameRecognizerManager()
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
lldb::StackFrameSP GetSelectedFrame(SelectMostRelevant select_most_relevant)
uint32_t GetSelectedFrameIndex(SelectMostRelevant select_most_relevant)
lldb::StopInfoSP GetStopInfo()
bool SetSelectedFrameByIndexNoisily(uint32_t frame_idx, Stream &output_stream)
virtual uint32_t GetStackFrameCount()
GetStackFrameCount can be expensive.
llvm::Error PrintValueObject()
bool AddVariableIfUnique(const lldb::VariableSP &var_sp)
lldb::VariableSP GetVariableAtIndex(size_t idx) const
llvm::ArrayRef< lldb::VariableSP > toArrayRef()
@ SelectMostRelevantFrame
A class that represents a running process on the host machine.
std::vector< OptionArgElement > OptionElementVector
const char * toString(AppleArm64ExceptionClass EC)
@ eLanguageRuntimeDescriptionDisplayVerbosityFull
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::TypeSummaryImpl > TypeSummaryImplSP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Format
Display format definitions.
std::shared_ptr< lldb_private::RegularExpression > RegularExpressionSP
std::shared_ptr< lldb_private::ValueObjectList > ValueObjectListSP
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
std::shared_ptr< lldb_private::Variable > VariableSP
std::shared_ptr< lldb_private::StackFrameRecognizer > StackFrameRecognizerSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
@ eValueTypeVTableEntry
function pointer in virtual function table
@ eValueTypeVTable
virtual function table
@ eValueTypeVariableGlobal
globals variable
@ eValueTypeConstResult
constant result variables
@ eValueTypeVariableLocal
function local variables
@ eValueTypeVariableArgument
function argument variables
@ eValueTypeRegister
stack frame register value
@ eValueTypeVariableStatic
static variable
@ eValueTypeRegisterSet
A collection of stack frame register values.
@ eValueTypeVariableThreadLocal
thread local storage variable
static bool ToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr)