Path: blob/main/contrib/llvm-project/lldb/source/Commands/CommandObjectFrame.cpp
39587 views
//===-- CommandObjectFrame.cpp --------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7#include "CommandObjectFrame.h"8#include "lldb/Core/Debugger.h"9#include "lldb/Core/ValueObject.h"10#include "lldb/DataFormatters/DataVisualization.h"11#include "lldb/DataFormatters/ValueObjectPrinter.h"12#include "lldb/Host/Config.h"13#include "lldb/Host/OptionParser.h"14#include "lldb/Interpreter/CommandInterpreter.h"15#include "lldb/Interpreter/CommandOptionArgumentTable.h"16#include "lldb/Interpreter/CommandReturnObject.h"17#include "lldb/Interpreter/OptionArgParser.h"18#include "lldb/Interpreter/OptionGroupFormat.h"19#include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"20#include "lldb/Interpreter/OptionGroupVariable.h"21#include "lldb/Interpreter/Options.h"22#include "lldb/Symbol/Function.h"23#include "lldb/Symbol/SymbolContext.h"24#include "lldb/Symbol/Variable.h"25#include "lldb/Symbol/VariableList.h"26#include "lldb/Target/StackFrame.h"27#include "lldb/Target/StackFrameRecognizer.h"28#include "lldb/Target/StopInfo.h"29#include "lldb/Target/Target.h"30#include "lldb/Target/Thread.h"31#include "lldb/Utility/Args.h"3233#include <memory>34#include <optional>35#include <string>3637using namespace lldb;38using namespace lldb_private;3940#pragma mark CommandObjectFrameDiagnose4142// CommandObjectFrameInfo4344// CommandObjectFrameDiagnose4546#define LLDB_OPTIONS_frame_diag47#include "CommandOptions.inc"4849class CommandObjectFrameDiagnose : public CommandObjectParsed {50public:51class CommandOptions : public Options {52public:53CommandOptions() { OptionParsingStarting(nullptr); }5455~CommandOptions() override = default;5657Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,58ExecutionContext *execution_context) override {59Status error;60const int short_option = m_getopt_table[option_idx].val;61switch (short_option) {62case 'r':63reg = ConstString(option_arg);64break;6566case 'a': {67address.emplace();68if (option_arg.getAsInteger(0, *address)) {69address.reset();70error.SetErrorStringWithFormat("invalid address argument '%s'",71option_arg.str().c_str());72}73} break;7475case 'o': {76offset.emplace();77if (option_arg.getAsInteger(0, *offset)) {78offset.reset();79error.SetErrorStringWithFormat("invalid offset argument '%s'",80option_arg.str().c_str());81}82} break;8384default:85llvm_unreachable("Unimplemented option");86}8788return error;89}9091void OptionParsingStarting(ExecutionContext *execution_context) override {92address.reset();93reg.reset();94offset.reset();95}9697llvm::ArrayRef<OptionDefinition> GetDefinitions() override {98return llvm::ArrayRef(g_frame_diag_options);99}100101// Options.102std::optional<lldb::addr_t> address;103std::optional<ConstString> reg;104std::optional<int64_t> offset;105};106107CommandObjectFrameDiagnose(CommandInterpreter &interpreter)108: CommandObjectParsed(interpreter, "frame diagnose",109"Try to determine what path the current stop "110"location used to get to a register or address",111nullptr,112eCommandRequiresThread | eCommandTryTargetAPILock |113eCommandProcessMustBeLaunched |114eCommandProcessMustBePaused) {115AddSimpleArgumentList(eArgTypeFrameIndex, eArgRepeatOptional);116}117118~CommandObjectFrameDiagnose() override = default;119120Options *GetOptions() override { return &m_options; }121122protected:123void DoExecute(Args &command, CommandReturnObject &result) override {124Thread *thread = m_exe_ctx.GetThreadPtr();125StackFrameSP frame_sp = thread->GetSelectedFrame(SelectMostRelevantFrame);126127ValueObjectSP valobj_sp;128129if (m_options.address) {130if (m_options.reg || m_options.offset) {131result.AppendError(132"`frame diagnose --address` is incompatible with other arguments.");133return;134}135valobj_sp = frame_sp->GuessValueForAddress(*m_options.address);136} else if (m_options.reg) {137valobj_sp = frame_sp->GuessValueForRegisterAndOffset(138*m_options.reg, m_options.offset.value_or(0));139} else {140StopInfoSP stop_info_sp = thread->GetStopInfo();141if (!stop_info_sp) {142result.AppendError("No arguments provided, and no stop info.");143return;144}145146valobj_sp = StopInfo::GetCrashingDereference(stop_info_sp);147}148149if (!valobj_sp) {150result.AppendError("No diagnosis available.");151return;152}153154DumpValueObjectOptions::DeclPrintingHelper helper =155[&valobj_sp](ConstString type, ConstString var,156const DumpValueObjectOptions &opts,157Stream &stream) -> bool {158const ValueObject::GetExpressionPathFormat format = ValueObject::159GetExpressionPathFormat::eGetExpressionPathFormatHonorPointers;160valobj_sp->GetExpressionPath(stream, format);161stream.PutCString(" =");162return true;163};164165DumpValueObjectOptions options;166options.SetDeclPrintingHelper(helper);167// We've already handled the case where the value object sp is null, so168// this is just to make sure future changes don't skip that:169assert(valobj_sp.get() && "Must have a valid ValueObject to print");170ValueObjectPrinter printer(*valobj_sp, &result.GetOutputStream(),171options);172if (llvm::Error error = printer.PrintValueObject())173result.AppendError(toString(std::move(error)));174}175176CommandOptions m_options;177};178179#pragma mark CommandObjectFrameInfo180181// CommandObjectFrameInfo182183class CommandObjectFrameInfo : public CommandObjectParsed {184public:185CommandObjectFrameInfo(CommandInterpreter &interpreter)186: CommandObjectParsed(interpreter, "frame info",187"List information about the current "188"stack frame in the current thread.",189"frame info",190eCommandRequiresFrame | eCommandTryTargetAPILock |191eCommandProcessMustBeLaunched |192eCommandProcessMustBePaused) {}193194~CommandObjectFrameInfo() override = default;195196protected:197void DoExecute(Args &command, CommandReturnObject &result) override {198m_exe_ctx.GetFrameRef().DumpUsingSettingsFormat(&result.GetOutputStream());199result.SetStatus(eReturnStatusSuccessFinishResult);200}201};202203#pragma mark CommandObjectFrameSelect204205// CommandObjectFrameSelect206207#define LLDB_OPTIONS_frame_select208#include "CommandOptions.inc"209210class CommandObjectFrameSelect : public CommandObjectParsed {211public:212class CommandOptions : public Options {213public:214CommandOptions() { OptionParsingStarting(nullptr); }215216~CommandOptions() override = default;217218Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,219ExecutionContext *execution_context) override {220Status error;221const int short_option = m_getopt_table[option_idx].val;222switch (short_option) {223case 'r': {224int32_t offset = 0;225if (option_arg.getAsInteger(0, offset) || offset == INT32_MIN) {226error.SetErrorStringWithFormat("invalid frame offset argument '%s'",227option_arg.str().c_str());228} else229relative_frame_offset = offset;230break;231}232233default:234llvm_unreachable("Unimplemented option");235}236237return error;238}239240void OptionParsingStarting(ExecutionContext *execution_context) override {241relative_frame_offset.reset();242}243244llvm::ArrayRef<OptionDefinition> GetDefinitions() override {245return llvm::ArrayRef(g_frame_select_options);246}247248std::optional<int32_t> relative_frame_offset;249};250251CommandObjectFrameSelect(CommandInterpreter &interpreter)252: CommandObjectParsed(interpreter, "frame select",253"Select the current stack frame by "254"index from within the current thread "255"(see 'thread backtrace'.)",256nullptr,257eCommandRequiresThread | eCommandTryTargetAPILock |258eCommandProcessMustBeLaunched |259eCommandProcessMustBePaused) {260AddSimpleArgumentList(eArgTypeFrameIndex, eArgRepeatOptional);261}262263~CommandObjectFrameSelect() override = default;264265Options *GetOptions() override { return &m_options; }266267protected:268void DoExecute(Args &command, CommandReturnObject &result) override {269// No need to check "thread" for validity as eCommandRequiresThread ensures270// it is valid271Thread *thread = m_exe_ctx.GetThreadPtr();272273uint32_t frame_idx = UINT32_MAX;274if (m_options.relative_frame_offset) {275// The one and only argument is a signed relative frame index276frame_idx = thread->GetSelectedFrameIndex(SelectMostRelevantFrame);277if (frame_idx == UINT32_MAX)278frame_idx = 0;279280if (*m_options.relative_frame_offset < 0) {281if (static_cast<int32_t>(frame_idx) >=282-*m_options.relative_frame_offset)283frame_idx += *m_options.relative_frame_offset;284else {285if (frame_idx == 0) {286// If you are already at the bottom of the stack, then just warn287// and don't reset the frame.288result.AppendError("Already at the bottom of the stack.");289return;290} else291frame_idx = 0;292}293} else if (*m_options.relative_frame_offset > 0) {294// I don't want "up 20" where "20" takes you past the top of the stack295// to produce an error, but rather to just go to the top. OTOH, start296// by seeing if the requested frame exists, in which case we can avoid297// counting the stack here...298const uint32_t frame_requested = frame_idx299+ *m_options.relative_frame_offset;300StackFrameSP frame_sp = thread->GetStackFrameAtIndex(frame_requested);301if (frame_sp)302frame_idx = frame_requested;303else {304// The request went past the stack, so handle that case:305const uint32_t num_frames = thread->GetStackFrameCount();306if (static_cast<int32_t>(num_frames - frame_idx) >307*m_options.relative_frame_offset)308frame_idx += *m_options.relative_frame_offset;309else {310if (frame_idx == num_frames - 1) {311// If we are already at the top of the stack, just warn and don't312// reset the frame.313result.AppendError("Already at the top of the stack.");314return;315} else316frame_idx = num_frames - 1;317}318}319}320} else {321if (command.GetArgumentCount() > 1) {322result.AppendErrorWithFormat(323"too many arguments; expected frame-index, saw '%s'.\n",324command[0].c_str());325m_options.GenerateOptionUsage(326result.GetErrorStream(), *this,327GetCommandInterpreter().GetDebugger().GetTerminalWidth());328return;329}330331if (command.GetArgumentCount() == 1) {332if (command[0].ref().getAsInteger(0, frame_idx)) {333result.AppendErrorWithFormat("invalid frame index argument '%s'.",334command[0].c_str());335return;336}337} else if (command.GetArgumentCount() == 0) {338frame_idx = thread->GetSelectedFrameIndex(SelectMostRelevantFrame);339if (frame_idx == UINT32_MAX) {340frame_idx = 0;341}342}343}344345bool success = thread->SetSelectedFrameByIndexNoisily(346frame_idx, result.GetOutputStream());347if (success) {348m_exe_ctx.SetFrameSP(thread->GetSelectedFrame(SelectMostRelevantFrame));349result.SetStatus(eReturnStatusSuccessFinishResult);350} else {351result.AppendErrorWithFormat("Frame index (%u) out of range.\n",352frame_idx);353}354}355356CommandOptions m_options;357};358359#pragma mark CommandObjectFrameVariable360// List images with associated information361class CommandObjectFrameVariable : public CommandObjectParsed {362public:363CommandObjectFrameVariable(CommandInterpreter &interpreter)364: CommandObjectParsed(365interpreter, "frame variable",366"Show variables for the current stack frame. Defaults to all "367"arguments and local variables in scope. Names of argument, "368"local, file static and file global variables can be specified.",369nullptr,370eCommandRequiresFrame | eCommandTryTargetAPILock |371eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |372eCommandRequiresProcess),373m_option_variable(374true), // Include the frame specific options by passing "true"375m_option_format(eFormatDefault) {376SetHelpLong(R"(377Children of aggregate variables can be specified such as 'var->child.x'. In378'frame variable', the operators -> and [] do not invoke operator overloads if379they exist, but directly access the specified element. If you want to trigger380operator overloads use the expression command to print the variable instead.381382It is worth noting that except for overloaded operators, when printing local383variables 'expr local_var' and 'frame var local_var' produce the same results.384However, 'frame variable' is more efficient, since it uses debug information and385memory reads directly, rather than parsing and evaluating an expression, which386may even involve JITing and running code in the target program.)");387388AddSimpleArgumentList(eArgTypeVarName, eArgRepeatStar);389390m_option_group.Append(&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);391m_option_group.Append(&m_option_format,392OptionGroupFormat::OPTION_GROUP_FORMAT |393OptionGroupFormat::OPTION_GROUP_GDB_FMT,394LLDB_OPT_SET_1);395m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);396m_option_group.Finalize();397}398399~CommandObjectFrameVariable() override = default;400401Options *GetOptions() override { return &m_option_group; }402403protected:404llvm::StringRef GetScopeString(VariableSP var_sp) {405if (!var_sp)406return llvm::StringRef();407408switch (var_sp->GetScope()) {409case eValueTypeVariableGlobal:410return "GLOBAL: ";411case eValueTypeVariableStatic:412return "STATIC: ";413case eValueTypeVariableArgument:414return "ARG: ";415case eValueTypeVariableLocal:416return "LOCAL: ";417case eValueTypeVariableThreadLocal:418return "THREAD: ";419default:420break;421}422423return llvm::StringRef();424}425426/// Returns true if `scope` matches any of the options in `m_option_variable`.427bool ScopeRequested(lldb::ValueType scope) {428switch (scope) {429case eValueTypeVariableGlobal:430case eValueTypeVariableStatic:431return m_option_variable.show_globals;432case eValueTypeVariableArgument:433return m_option_variable.show_args;434case eValueTypeVariableLocal:435return m_option_variable.show_locals;436case eValueTypeInvalid:437case eValueTypeRegister:438case eValueTypeRegisterSet:439case eValueTypeConstResult:440case eValueTypeVariableThreadLocal:441case eValueTypeVTable:442case eValueTypeVTableEntry:443return false;444}445llvm_unreachable("Unexpected scope value");446}447448/// Finds all the variables in `all_variables` whose name matches `regex`,449/// inserting them into `matches`. Variables already contained in `matches`450/// are not inserted again.451/// Nullopt is returned in case of no matches.452/// A sub-range of `matches` with all newly inserted variables is returned.453/// This may be empty if all matches were already contained in `matches`.454std::optional<llvm::ArrayRef<VariableSP>>455findUniqueRegexMatches(RegularExpression ®ex,456VariableList &matches,457const VariableList &all_variables) {458bool any_matches = false;459const size_t previous_num_vars = matches.GetSize();460461for (const VariableSP &var : all_variables) {462if (!var->NameMatches(regex) || !ScopeRequested(var->GetScope()))463continue;464any_matches = true;465matches.AddVariableIfUnique(var);466}467468if (any_matches)469return matches.toArrayRef().drop_front(previous_num_vars);470return std::nullopt;471}472473void DoExecute(Args &command, CommandReturnObject &result) override {474// No need to check "frame" for validity as eCommandRequiresFrame ensures475// it is valid476StackFrame *frame = m_exe_ctx.GetFramePtr();477478Stream &s = result.GetOutputStream();479480// Using a regex should behave like looking for an exact name match: it481// also finds globals.482m_option_variable.show_globals |= m_option_variable.use_regex;483484// Be careful about the stack frame, if any summary formatter runs code, it485// might clear the StackFrameList for the thread. So hold onto a shared486// pointer to the frame so it stays alive.487488Status error;489VariableList *variable_list =490frame->GetVariableList(m_option_variable.show_globals, &error);491492if (error.Fail() && (!variable_list || variable_list->GetSize() == 0)) {493result.AppendError(error.AsCString());494495}496ValueObjectSP valobj_sp;497498TypeSummaryImplSP summary_format_sp;499if (!m_option_variable.summary.IsCurrentValueEmpty())500DataVisualization::NamedSummaryFormats::GetSummaryFormat(501ConstString(m_option_variable.summary.GetCurrentValue()),502summary_format_sp);503else if (!m_option_variable.summary_string.IsCurrentValueEmpty())504summary_format_sp = std::make_shared<StringSummaryFormat>(505TypeSummaryImpl::Flags(),506m_option_variable.summary_string.GetCurrentValue());507508DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(509eLanguageRuntimeDescriptionDisplayVerbosityFull, eFormatDefault,510summary_format_sp));511512const SymbolContext &sym_ctx =513frame->GetSymbolContext(eSymbolContextFunction);514if (sym_ctx.function && sym_ctx.function->IsTopLevelFunction())515m_option_variable.show_globals = true;516517if (variable_list) {518const Format format = m_option_format.GetFormat();519options.SetFormat(format);520521if (!command.empty()) {522VariableList regex_var_list;523524// If we have any args to the variable command, we will make variable525// objects from them...526for (auto &entry : command) {527if (m_option_variable.use_regex) {528llvm::StringRef name_str = entry.ref();529RegularExpression regex(name_str);530if (regex.IsValid()) {531std::optional<llvm::ArrayRef<VariableSP>> results =532findUniqueRegexMatches(regex, regex_var_list, *variable_list);533if (!results) {534result.AppendErrorWithFormat(535"no variables matched the regular expression '%s'.",536entry.c_str());537continue;538}539for (const VariableSP &var_sp : *results) {540valobj_sp = frame->GetValueObjectForFrameVariable(541var_sp, m_varobj_options.use_dynamic);542if (valobj_sp) {543std::string scope_string;544if (m_option_variable.show_scope)545scope_string = GetScopeString(var_sp).str();546547if (!scope_string.empty())548s.PutCString(scope_string);549550if (m_option_variable.show_decl &&551var_sp->GetDeclaration().GetFile()) {552bool show_fullpaths = false;553bool show_module = true;554if (var_sp->DumpDeclaration(&s, show_fullpaths,555show_module))556s.PutCString(": ");557}558auto &strm = result.GetOutputStream();559if (llvm::Error error = valobj_sp->Dump(strm, options))560result.AppendError(toString(std::move(error)));561}562}563} else {564if (llvm::Error err = regex.GetError())565result.AppendError(llvm::toString(std::move(err)));566else567result.AppendErrorWithFormat(568"unknown regex error when compiling '%s'", entry.c_str());569}570} else // No regex, either exact variable names or variable571// expressions.572{573Status error;574uint32_t expr_path_options =575StackFrame::eExpressionPathOptionCheckPtrVsMember |576StackFrame::eExpressionPathOptionsAllowDirectIVarAccess |577StackFrame::eExpressionPathOptionsInspectAnonymousUnions;578lldb::VariableSP var_sp;579valobj_sp = frame->GetValueForVariableExpressionPath(580entry.ref(), m_varobj_options.use_dynamic, expr_path_options,581var_sp, error);582if (valobj_sp) {583std::string scope_string;584if (m_option_variable.show_scope)585scope_string = GetScopeString(var_sp).str();586587if (!scope_string.empty())588s.PutCString(scope_string);589if (m_option_variable.show_decl && var_sp &&590var_sp->GetDeclaration().GetFile()) {591var_sp->GetDeclaration().DumpStopContext(&s, false);592s.PutCString(": ");593}594595options.SetFormat(format);596options.SetVariableFormatDisplayLanguage(597valobj_sp->GetPreferredDisplayLanguage());598599Stream &output_stream = result.GetOutputStream();600options.SetRootValueObjectName(601valobj_sp->GetParent() ? entry.c_str() : nullptr);602if (llvm::Error error = valobj_sp->Dump(output_stream, options))603result.AppendError(toString(std::move(error)));604} else {605if (auto error_cstr = error.AsCString(nullptr))606result.AppendError(error_cstr);607else608result.AppendErrorWithFormat(609"unable to find any variable expression path that matches "610"'%s'.",611entry.c_str());612}613}614}615} else // No command arg specified. Use variable_list, instead.616{617const size_t num_variables = variable_list->GetSize();618if (num_variables > 0) {619for (size_t i = 0; i < num_variables; i++) {620VariableSP var_sp = variable_list->GetVariableAtIndex(i);621if (!ScopeRequested(var_sp->GetScope()))622continue;623std::string scope_string;624if (m_option_variable.show_scope)625scope_string = GetScopeString(var_sp).str();626627// Use the variable object code to make sure we are using the same628// APIs as the public API will be using...629valobj_sp = frame->GetValueObjectForFrameVariable(630var_sp, m_varobj_options.use_dynamic);631if (valobj_sp) {632// When dumping all variables, don't print any variables that are633// not in scope to avoid extra unneeded output634if (valobj_sp->IsInScope()) {635if (!valobj_sp->GetTargetSP()636->GetDisplayRuntimeSupportValues() &&637valobj_sp->IsRuntimeSupportValue())638continue;639640if (!scope_string.empty())641s.PutCString(scope_string);642643if (m_option_variable.show_decl &&644var_sp->GetDeclaration().GetFile()) {645var_sp->GetDeclaration().DumpStopContext(&s, false);646s.PutCString(": ");647}648649options.SetFormat(format);650options.SetVariableFormatDisplayLanguage(651valobj_sp->GetPreferredDisplayLanguage());652options.SetRootValueObjectName(653var_sp ? var_sp->GetName().AsCString() : nullptr);654if (llvm::Error error =655valobj_sp->Dump(result.GetOutputStream(), options))656result.AppendError(toString(std::move(error)));657}658}659}660}661}662if (result.GetStatus() != eReturnStatusFailed)663result.SetStatus(eReturnStatusSuccessFinishResult);664}665666if (m_option_variable.show_recognized_args) {667auto recognized_frame = frame->GetRecognizedFrame();668if (recognized_frame) {669ValueObjectListSP recognized_arg_list =670recognized_frame->GetRecognizedArguments();671if (recognized_arg_list) {672for (auto &rec_value_sp : recognized_arg_list->GetObjects()) {673options.SetFormat(m_option_format.GetFormat());674options.SetVariableFormatDisplayLanguage(675rec_value_sp->GetPreferredDisplayLanguage());676options.SetRootValueObjectName(rec_value_sp->GetName().AsCString());677if (llvm::Error error =678rec_value_sp->Dump(result.GetOutputStream(), options))679result.AppendError(toString(std::move(error)));680}681}682}683}684685m_interpreter.PrintWarningsIfNecessary(result.GetOutputStream(),686m_cmd_name);687688// Increment statistics.689TargetStats &target_stats = GetSelectedOrDummyTarget().GetStatistics();690if (result.Succeeded())691target_stats.GetFrameVariableStats().NotifySuccess();692else693target_stats.GetFrameVariableStats().NotifyFailure();694}695696OptionGroupOptions m_option_group;697OptionGroupVariable m_option_variable;698OptionGroupFormat m_option_format;699OptionGroupValueObjectDisplay m_varobj_options;700};701702#pragma mark CommandObjectFrameRecognizer703704#define LLDB_OPTIONS_frame_recognizer_add705#include "CommandOptions.inc"706707class CommandObjectFrameRecognizerAdd : public CommandObjectParsed {708private:709class CommandOptions : public Options {710public:711CommandOptions() = default;712~CommandOptions() override = default;713714Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,715ExecutionContext *execution_context) override {716Status error;717const int short_option = m_getopt_table[option_idx].val;718719switch (short_option) {720case 'f': {721bool value, success;722value = OptionArgParser::ToBoolean(option_arg, true, &success);723if (success) {724m_first_instruction_only = value;725} else {726error.SetErrorStringWithFormat(727"invalid boolean value '%s' passed for -f option",728option_arg.str().c_str());729}730} break;731case 'l':732m_class_name = std::string(option_arg);733break;734case 's':735m_module = std::string(option_arg);736break;737case 'n':738m_symbols.push_back(std::string(option_arg));739break;740case 'x':741m_regex = true;742break;743default:744llvm_unreachable("Unimplemented option");745}746747return error;748}749750void OptionParsingStarting(ExecutionContext *execution_context) override {751m_module = "";752m_symbols.clear();753m_class_name = "";754m_regex = false;755m_first_instruction_only = true;756}757758llvm::ArrayRef<OptionDefinition> GetDefinitions() override {759return llvm::ArrayRef(g_frame_recognizer_add_options);760}761762// Instance variables to hold the values for command options.763std::string m_class_name;764std::string m_module;765std::vector<std::string> m_symbols;766bool m_regex;767bool m_first_instruction_only;768};769770CommandOptions m_options;771772Options *GetOptions() override { return &m_options; }773774protected:775void DoExecute(Args &command, CommandReturnObject &result) override;776777public:778CommandObjectFrameRecognizerAdd(CommandInterpreter &interpreter)779: CommandObjectParsed(interpreter, "frame recognizer add",780"Add a new frame recognizer.", nullptr) {781SetHelpLong(R"(782Frame recognizers allow for retrieving information about special frames based on783ABI, arguments or other special properties of that frame, even without source784code or debug info. Currently, one use case is to extract function arguments785that would otherwise be unaccesible, or augment existing arguments.786787Adding a custom frame recognizer is possible by implementing a Python class788and using the 'frame recognizer add' command. The Python class should have a789'get_recognized_arguments' method and it will receive an argument of type790lldb.SBFrame representing the current frame that we are trying to recognize.791The method should return a (possibly empty) list of lldb.SBValue objects that792represent the recognized arguments.793794An example of a recognizer that retrieves the file descriptor values from libc795functions 'read', 'write' and 'close' follows:796797class LibcFdRecognizer(object):798def get_recognized_arguments(self, frame):799if frame.name in ["read", "write", "close"]:800fd = frame.EvaluateExpression("$arg1").unsigned801target = frame.thread.process.target802value = target.CreateValueFromExpression("fd", "(int)%d" % fd)803return [value]804return []805806The file containing this implementation can be imported via 'command script807import' and then we can register this recognizer with 'frame recognizer add'.808It's important to restrict the recognizer to the libc library (which is809libsystem_kernel.dylib on macOS) to avoid matching functions with the same name810in other modules:811812(lldb) command script import .../fd_recognizer.py813(lldb) frame recognizer add -l fd_recognizer.LibcFdRecognizer -n read -s libsystem_kernel.dylib814815When the program is stopped at the beginning of the 'read' function in libc, we816can view the recognizer arguments in 'frame variable':817818(lldb) b read819(lldb) r820Process 1234 stopped821* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.3822frame #0: 0x00007fff06013ca0 libsystem_kernel.dylib`read823(lldb) frame variable824(int) fd = 3825826)");827}828~CommandObjectFrameRecognizerAdd() override = default;829};830831void CommandObjectFrameRecognizerAdd::DoExecute(Args &command,832CommandReturnObject &result) {833#if LLDB_ENABLE_PYTHON834if (m_options.m_class_name.empty()) {835result.AppendErrorWithFormat(836"%s needs a Python class name (-l argument).\n", m_cmd_name.c_str());837return;838}839840if (m_options.m_module.empty()) {841result.AppendErrorWithFormat("%s needs a module name (-s argument).\n",842m_cmd_name.c_str());843return;844}845846if (m_options.m_symbols.empty()) {847result.AppendErrorWithFormat(848"%s needs at least one symbol name (-n argument).\n",849m_cmd_name.c_str());850return;851}852853if (m_options.m_regex && m_options.m_symbols.size() > 1) {854result.AppendErrorWithFormat(855"%s needs only one symbol regular expression (-n argument).\n",856m_cmd_name.c_str());857return;858}859860ScriptInterpreter *interpreter = GetDebugger().GetScriptInterpreter();861862if (interpreter &&863!interpreter->CheckObjectExists(m_options.m_class_name.c_str())) {864result.AppendWarning("The provided class does not exist - please define it "865"before attempting to use this frame recognizer");866}867868StackFrameRecognizerSP recognizer_sp =869StackFrameRecognizerSP(new ScriptedStackFrameRecognizer(870interpreter, m_options.m_class_name.c_str()));871if (m_options.m_regex) {872auto module =873RegularExpressionSP(new RegularExpression(m_options.m_module));874auto func =875RegularExpressionSP(new RegularExpression(m_options.m_symbols.front()));876GetSelectedOrDummyTarget().GetFrameRecognizerManager().AddRecognizer(877recognizer_sp, module, func, m_options.m_first_instruction_only);878} else {879auto module = ConstString(m_options.m_module);880std::vector<ConstString> symbols(m_options.m_symbols.begin(),881m_options.m_symbols.end());882GetSelectedOrDummyTarget().GetFrameRecognizerManager().AddRecognizer(883recognizer_sp, module, symbols, m_options.m_first_instruction_only);884}885#endif886887result.SetStatus(eReturnStatusSuccessFinishNoResult);888}889890class CommandObjectFrameRecognizerClear : public CommandObjectParsed {891public:892CommandObjectFrameRecognizerClear(CommandInterpreter &interpreter)893: CommandObjectParsed(interpreter, "frame recognizer clear",894"Delete all frame recognizers.", nullptr) {}895896~CommandObjectFrameRecognizerClear() override = default;897898protected:899void DoExecute(Args &command, CommandReturnObject &result) override {900GetSelectedOrDummyTarget()901.GetFrameRecognizerManager()902.RemoveAllRecognizers();903result.SetStatus(eReturnStatusSuccessFinishResult);904}905};906907class CommandObjectFrameRecognizerDelete : public CommandObjectParsed {908public:909CommandObjectFrameRecognizerDelete(CommandInterpreter &interpreter)910: CommandObjectParsed(interpreter, "frame recognizer delete",911"Delete an existing frame recognizer by id.",912nullptr) {913AddSimpleArgumentList(eArgTypeRecognizerID);914}915916~CommandObjectFrameRecognizerDelete() override = default;917918void919HandleArgumentCompletion(CompletionRequest &request,920OptionElementVector &opt_element_vector) override {921if (request.GetCursorIndex() != 0)922return;923924GetSelectedOrDummyTarget().GetFrameRecognizerManager().ForEach(925[&request](uint32_t rid, std::string rname, std::string module,926llvm::ArrayRef<lldb_private::ConstString> symbols,927bool regexp) {928StreamString strm;929if (rname.empty())930rname = "(internal)";931932strm << rname;933if (!module.empty())934strm << ", module " << module;935if (!symbols.empty())936for (auto &symbol : symbols)937strm << ", symbol " << symbol;938if (regexp)939strm << " (regexp)";940941request.TryCompleteCurrentArg(std::to_string(rid), strm.GetString());942});943}944945protected:946void DoExecute(Args &command, CommandReturnObject &result) override {947if (command.GetArgumentCount() == 0) {948if (!m_interpreter.Confirm(949"About to delete all frame recognizers, do you want to do that?",950true)) {951result.AppendMessage("Operation cancelled...");952return;953}954955GetSelectedOrDummyTarget()956.GetFrameRecognizerManager()957.RemoveAllRecognizers();958result.SetStatus(eReturnStatusSuccessFinishResult);959return;960}961962if (command.GetArgumentCount() != 1) {963result.AppendErrorWithFormat("'%s' takes zero or one arguments.\n",964m_cmd_name.c_str());965return;966}967968uint32_t recognizer_id;969if (!llvm::to_integer(command.GetArgumentAtIndex(0), recognizer_id)) {970result.AppendErrorWithFormat("'%s' is not a valid recognizer id.\n",971command.GetArgumentAtIndex(0));972return;973}974975if (!GetSelectedOrDummyTarget()976.GetFrameRecognizerManager()977.RemoveRecognizerWithID(recognizer_id)) {978result.AppendErrorWithFormat("'%s' is not a valid recognizer id.\n",979command.GetArgumentAtIndex(0));980return;981}982result.SetStatus(eReturnStatusSuccessFinishResult);983}984};985986class CommandObjectFrameRecognizerList : public CommandObjectParsed {987public:988CommandObjectFrameRecognizerList(CommandInterpreter &interpreter)989: CommandObjectParsed(interpreter, "frame recognizer list",990"Show a list of active frame recognizers.",991nullptr) {}992993~CommandObjectFrameRecognizerList() override = default;994995protected:996void DoExecute(Args &command, CommandReturnObject &result) override {997bool any_printed = false;998GetSelectedOrDummyTarget().GetFrameRecognizerManager().ForEach(999[&result, &any_printed](1000uint32_t recognizer_id, std::string name, std::string module,1001llvm::ArrayRef<ConstString> symbols, bool regexp) {1002Stream &stream = result.GetOutputStream();10031004if (name.empty())1005name = "(internal)";10061007stream << std::to_string(recognizer_id) << ": " << name;1008if (!module.empty())1009stream << ", module " << module;1010if (!symbols.empty())1011for (auto &symbol : symbols)1012stream << ", symbol " << symbol;1013if (regexp)1014stream << " (regexp)";10151016stream.EOL();1017stream.Flush();10181019any_printed = true;1020});10211022if (any_printed)1023result.SetStatus(eReturnStatusSuccessFinishResult);1024else {1025result.GetOutputStream().PutCString("no matching results found.\n");1026result.SetStatus(eReturnStatusSuccessFinishNoResult);1027}1028}1029};10301031class CommandObjectFrameRecognizerInfo : public CommandObjectParsed {1032public:1033CommandObjectFrameRecognizerInfo(CommandInterpreter &interpreter)1034: CommandObjectParsed(1035interpreter, "frame recognizer info",1036"Show which frame recognizer is applied a stack frame (if any).",1037nullptr) {1038AddSimpleArgumentList(eArgTypeFrameIndex);1039}10401041~CommandObjectFrameRecognizerInfo() override = default;10421043protected:1044void DoExecute(Args &command, CommandReturnObject &result) override {1045const char *frame_index_str = command.GetArgumentAtIndex(0);1046uint32_t frame_index;1047if (!llvm::to_integer(frame_index_str, frame_index)) {1048result.AppendErrorWithFormat("'%s' is not a valid frame index.",1049frame_index_str);1050return;1051}10521053Process *process = m_exe_ctx.GetProcessPtr();1054if (process == nullptr) {1055result.AppendError("no process");1056return;1057}1058Thread *thread = m_exe_ctx.GetThreadPtr();1059if (thread == nullptr) {1060result.AppendError("no thread");1061return;1062}1063if (command.GetArgumentCount() != 1) {1064result.AppendErrorWithFormat(1065"'%s' takes exactly one frame index argument.\n", m_cmd_name.c_str());1066return;1067}10681069StackFrameSP frame_sp = thread->GetStackFrameAtIndex(frame_index);1070if (!frame_sp) {1071result.AppendErrorWithFormat("no frame with index %u", frame_index);1072return;1073}10741075auto recognizer = GetSelectedOrDummyTarget()1076.GetFrameRecognizerManager()1077.GetRecognizerForFrame(frame_sp);10781079Stream &output_stream = result.GetOutputStream();1080output_stream.Printf("frame %d ", frame_index);1081if (recognizer) {1082output_stream << "is recognized by ";1083output_stream << recognizer->GetName();1084} else {1085output_stream << "not recognized by any recognizer";1086}1087output_stream.EOL();1088result.SetStatus(eReturnStatusSuccessFinishResult);1089}1090};10911092class CommandObjectFrameRecognizer : public CommandObjectMultiword {1093public:1094CommandObjectFrameRecognizer(CommandInterpreter &interpreter)1095: CommandObjectMultiword(1096interpreter, "frame recognizer",1097"Commands for editing and viewing frame recognizers.",1098"frame recognizer [<sub-command-options>] ") {1099LoadSubCommand("add", CommandObjectSP(new CommandObjectFrameRecognizerAdd(1100interpreter)));1101LoadSubCommand(1102"clear",1103CommandObjectSP(new CommandObjectFrameRecognizerClear(interpreter)));1104LoadSubCommand(1105"delete",1106CommandObjectSP(new CommandObjectFrameRecognizerDelete(interpreter)));1107LoadSubCommand("list", CommandObjectSP(new CommandObjectFrameRecognizerList(1108interpreter)));1109LoadSubCommand("info", CommandObjectSP(new CommandObjectFrameRecognizerInfo(1110interpreter)));1111}11121113~CommandObjectFrameRecognizer() override = default;1114};11151116#pragma mark CommandObjectMultiwordFrame11171118// CommandObjectMultiwordFrame11191120CommandObjectMultiwordFrame::CommandObjectMultiwordFrame(1121CommandInterpreter &interpreter)1122: CommandObjectMultiword(interpreter, "frame",1123"Commands for selecting and "1124"examing the current "1125"thread's stack frames.",1126"frame <subcommand> [<subcommand-options>]") {1127LoadSubCommand("diagnose",1128CommandObjectSP(new CommandObjectFrameDiagnose(interpreter)));1129LoadSubCommand("info",1130CommandObjectSP(new CommandObjectFrameInfo(interpreter)));1131LoadSubCommand("select",1132CommandObjectSP(new CommandObjectFrameSelect(interpreter)));1133LoadSubCommand("variable",1134CommandObjectSP(new CommandObjectFrameVariable(interpreter)));1135#if LLDB_ENABLE_PYTHON1136LoadSubCommand("recognizer", CommandObjectSP(new CommandObjectFrameRecognizer(1137interpreter)));1138#endif1139}11401141CommandObjectMultiwordFrame::~CommandObjectMultiwordFrame() = default;114211431144