Path: blob/main/contrib/llvm-project/lldb/source/Commands/CommandObjectRegister.cpp
96333 views
//===-- CommandObjectRegister.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//===----------------------------------------------------------------------===//78#include "CommandObjectRegister.h"9#include "lldb/Core/Debugger.h"10#include "lldb/Core/DumpRegisterInfo.h"11#include "lldb/Core/DumpRegisterValue.h"12#include "lldb/Host/OptionParser.h"13#include "lldb/Interpreter/CommandInterpreter.h"14#include "lldb/Interpreter/CommandOptionArgumentTable.h"15#include "lldb/Interpreter/CommandReturnObject.h"16#include "lldb/Interpreter/OptionGroupFormat.h"17#include "lldb/Interpreter/OptionValueArray.h"18#include "lldb/Interpreter/OptionValueBoolean.h"19#include "lldb/Interpreter/OptionValueUInt64.h"20#include "lldb/Interpreter/Options.h"21#include "lldb/Target/ExecutionContext.h"22#include "lldb/Target/Process.h"23#include "lldb/Target/RegisterContext.h"24#include "lldb/Target/SectionLoadList.h"25#include "lldb/Target/Thread.h"26#include "lldb/Utility/Args.h"27#include "lldb/Utility/DataExtractor.h"28#include "lldb/Utility/RegisterValue.h"29#include "llvm/Support/Errno.h"3031using namespace lldb;32using namespace lldb_private;3334// "register read"35#define LLDB_OPTIONS_register_read36#include "CommandOptions.inc"3738class CommandObjectRegisterRead : public CommandObjectParsed {39public:40CommandObjectRegisterRead(CommandInterpreter &interpreter)41: CommandObjectParsed(42interpreter, "register read",43"Dump the contents of one or more register values from the current "44"frame. If no register is specified, dumps them all.",45nullptr,46eCommandRequiresFrame | eCommandRequiresRegContext |47eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),48m_format_options(eFormatDefault, UINT64_MAX, UINT64_MAX,49{{CommandArgumentType::eArgTypeFormat,50"Specify a format to be used for display. If this "51"is set, register fields will not be displayed."}}) {52AddSimpleArgumentList(eArgTypeRegisterName, eArgRepeatStar);5354// Add the "--format"55m_option_group.Append(&m_format_options,56OptionGroupFormat::OPTION_GROUP_FORMAT |57OptionGroupFormat::OPTION_GROUP_GDB_FMT,58LLDB_OPT_SET_ALL);59m_option_group.Append(&m_command_options);60m_option_group.Finalize();61}6263~CommandObjectRegisterRead() override = default;6465void66HandleArgumentCompletion(CompletionRequest &request,67OptionElementVector &opt_element_vector) override {68if (!m_exe_ctx.HasProcessScope())69return;70CommandObject::HandleArgumentCompletion(request, opt_element_vector);71}7273Options *GetOptions() override { return &m_option_group; }7475bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm,76RegisterContext ®_ctx, const RegisterInfo ®_info,77bool print_flags) {78RegisterValue reg_value;79if (!reg_ctx.ReadRegister(®_info, reg_value))80return false;8182strm.Indent();8384bool prefix_with_altname = (bool)m_command_options.alternate_name;85bool prefix_with_name = !prefix_with_altname;86DumpRegisterValue(reg_value, strm, reg_info, prefix_with_name,87prefix_with_altname, m_format_options.GetFormat(), 8,88exe_ctx.GetBestExecutionContextScope(), print_flags,89exe_ctx.GetTargetSP());90if ((reg_info.encoding == eEncodingUint) ||91(reg_info.encoding == eEncodingSint)) {92Process *process = exe_ctx.GetProcessPtr();93if (process && reg_info.byte_size == process->GetAddressByteSize()) {94addr_t reg_addr = reg_value.GetAsUInt64(LLDB_INVALID_ADDRESS);95if (reg_addr != LLDB_INVALID_ADDRESS) {96Address so_reg_addr;97if (exe_ctx.GetTargetRef().GetSectionLoadList().ResolveLoadAddress(98reg_addr, so_reg_addr)) {99strm.PutCString(" ");100so_reg_addr.Dump(&strm, exe_ctx.GetBestExecutionContextScope(),101Address::DumpStyleResolvedDescription);102}103}104}105}106strm.EOL();107return true;108}109110bool DumpRegisterSet(const ExecutionContext &exe_ctx, Stream &strm,111RegisterContext *reg_ctx, size_t set_idx,112bool primitive_only = false) {113uint32_t unavailable_count = 0;114uint32_t available_count = 0;115116if (!reg_ctx)117return false; // thread has no registers (i.e. core files are corrupt,118// incomplete crash logs...)119120const RegisterSet *const reg_set = reg_ctx->GetRegisterSet(set_idx);121if (reg_set) {122strm.Printf("%s:\n", (reg_set->name ? reg_set->name : "unknown"));123strm.IndentMore();124const size_t num_registers = reg_set->num_registers;125for (size_t reg_idx = 0; reg_idx < num_registers; ++reg_idx) {126const uint32_t reg = reg_set->registers[reg_idx];127const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg);128// Skip the dumping of derived register if primitive_only is true.129if (primitive_only && reg_info && reg_info->value_regs)130continue;131132if (reg_info && DumpRegister(exe_ctx, strm, *reg_ctx, *reg_info,133/*print_flags=*/false))134++available_count;135else136++unavailable_count;137}138strm.IndentLess();139if (unavailable_count) {140strm.Indent();141strm.Printf("%u registers were unavailable.\n", unavailable_count);142}143strm.EOL();144}145return available_count > 0;146}147148protected:149void DoExecute(Args &command, CommandReturnObject &result) override {150Stream &strm = result.GetOutputStream();151RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();152153if (command.GetArgumentCount() == 0) {154size_t set_idx;155156size_t num_register_sets = 1;157const size_t set_array_size = m_command_options.set_indexes.GetSize();158if (set_array_size > 0) {159for (size_t i = 0; i < set_array_size; ++i) {160set_idx =161m_command_options.set_indexes[i]->GetValueAs<uint64_t>().value_or(162UINT32_MAX);163if (set_idx < reg_ctx->GetRegisterSetCount()) {164if (!DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx)) {165if (errno)166result.AppendErrorWithFormatv("register read failed: {0}\n",167llvm::sys::StrError());168else169result.AppendError("unknown error while reading registers.\n");170break;171}172} else {173result.AppendErrorWithFormat(174"invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx);175break;176}177}178} else {179if (m_command_options.dump_all_sets)180num_register_sets = reg_ctx->GetRegisterSetCount();181182for (set_idx = 0; set_idx < num_register_sets; ++set_idx) {183// When dump_all_sets option is set, dump primitive as well as184// derived registers.185DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx,186!m_command_options.dump_all_sets.GetCurrentValue());187}188}189} else {190if (m_command_options.dump_all_sets) {191result.AppendError("the --all option can't be used when registers "192"names are supplied as arguments\n");193} else if (m_command_options.set_indexes.GetSize() > 0) {194result.AppendError("the --set <set> option can't be used when "195"registers names are supplied as arguments\n");196} else {197for (auto &entry : command) {198// in most LLDB commands we accept $rbx as the name for register RBX199// - and here we would reject it and non-existant. we should be more200// consistent towards the user and allow them to say reg read $rbx -201// internally, however, we should be strict and not allow ourselves202// to call our registers $rbx in our own API203auto arg_str = entry.ref();204arg_str.consume_front("$");205206if (const RegisterInfo *reg_info =207reg_ctx->GetRegisterInfoByName(arg_str)) {208// If they have asked for a specific format don't obscure that by209// printing flags afterwards.210bool print_flags =211!m_format_options.GetFormatValue().OptionWasSet();212if (!DumpRegister(m_exe_ctx, strm, *reg_ctx, *reg_info,213print_flags))214strm.Printf("%-12s = error: unavailable\n", reg_info->name);215} else {216result.AppendErrorWithFormat("Invalid register name '%s'.\n",217arg_str.str().c_str());218}219}220}221}222}223224class CommandOptions : public OptionGroup {225public:226CommandOptions()227: set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64)),228dump_all_sets(false, false), // Initial and default values are false229alternate_name(false, false) {}230231~CommandOptions() override = default;232233llvm::ArrayRef<OptionDefinition> GetDefinitions() override {234return llvm::ArrayRef(g_register_read_options);235}236237void OptionParsingStarting(ExecutionContext *execution_context) override {238set_indexes.Clear();239dump_all_sets.Clear();240alternate_name.Clear();241}242243Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,244ExecutionContext *execution_context) override {245Status error;246const int short_option = GetDefinitions()[option_idx].short_option;247switch (short_option) {248case 's': {249OptionValueSP value_sp(OptionValueUInt64::Create(option_value, error));250if (value_sp)251set_indexes.AppendValue(value_sp);252} break;253254case 'a':255// When we don't use OptionValue::SetValueFromCString(const char *) to256// set an option value, it won't be marked as being set in the options257// so we make a call to let users know the value was set via option258dump_all_sets.SetCurrentValue(true);259dump_all_sets.SetOptionWasSet();260break;261262case 'A':263// When we don't use OptionValue::SetValueFromCString(const char *) to264// set an option value, it won't be marked as being set in the options265// so we make a call to let users know the value was set via option266alternate_name.SetCurrentValue(true);267dump_all_sets.SetOptionWasSet();268break;269270default:271llvm_unreachable("Unimplemented option");272}273return error;274}275276// Instance variables to hold the values for command options.277OptionValueArray set_indexes;278OptionValueBoolean dump_all_sets;279OptionValueBoolean alternate_name;280};281282OptionGroupOptions m_option_group;283OptionGroupFormat m_format_options;284CommandOptions m_command_options;285};286287// "register write"288class CommandObjectRegisterWrite : public CommandObjectParsed {289public:290CommandObjectRegisterWrite(CommandInterpreter &interpreter)291: CommandObjectParsed(interpreter, "register write",292"Modify a single register value.", nullptr,293eCommandRequiresFrame | eCommandRequiresRegContext |294eCommandProcessMustBeLaunched |295eCommandProcessMustBePaused) {296CommandArgumentEntry arg1;297CommandArgumentEntry arg2;298CommandArgumentData register_arg;299CommandArgumentData value_arg;300301// Define the first (and only) variant of this arg.302register_arg.arg_type = eArgTypeRegisterName;303register_arg.arg_repetition = eArgRepeatPlain;304305// There is only one variant this argument could be; put it into the306// argument entry.307arg1.push_back(register_arg);308309// Define the first (and only) variant of this arg.310value_arg.arg_type = eArgTypeValue;311value_arg.arg_repetition = eArgRepeatPlain;312313// There is only one variant this argument could be; put it into the314// argument entry.315arg2.push_back(value_arg);316317// Push the data for the first argument into the m_arguments vector.318m_arguments.push_back(arg1);319m_arguments.push_back(arg2);320}321322~CommandObjectRegisterWrite() override = default;323324void325HandleArgumentCompletion(CompletionRequest &request,326OptionElementVector &opt_element_vector) override {327if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)328return;329330lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(331GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr);332}333334protected:335void DoExecute(Args &command, CommandReturnObject &result) override {336DataExtractor reg_data;337RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();338339if (command.GetArgumentCount() != 2) {340result.AppendError(341"register write takes exactly 2 arguments: <reg-name> <value>");342} else {343auto reg_name = command[0].ref();344auto value_str = command[1].ref();345346// in most LLDB commands we accept $rbx as the name for register RBX -347// and here we would reject it and non-existant. we should be more348// consistent towards the user and allow them to say reg write $rbx -349// internally, however, we should be strict and not allow ourselves to350// call our registers $rbx in our own API351reg_name.consume_front("$");352353const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);354355if (reg_info) {356RegisterValue reg_value;357358Status error(reg_value.SetValueFromString(reg_info, value_str));359if (error.Success()) {360if (reg_ctx->WriteRegister(reg_info, reg_value)) {361// Toss all frames and anything else in the thread after a register362// has been written.363m_exe_ctx.GetThreadRef().Flush();364result.SetStatus(eReturnStatusSuccessFinishNoResult);365return;366}367}368if (error.AsCString()) {369result.AppendErrorWithFormat(370"Failed to write register '%s' with value '%s': %s\n",371reg_name.str().c_str(), value_str.str().c_str(),372error.AsCString());373} else {374result.AppendErrorWithFormat(375"Failed to write register '%s' with value '%s'",376reg_name.str().c_str(), value_str.str().c_str());377}378} else {379result.AppendErrorWithFormat("Register not found for '%s'.\n",380reg_name.str().c_str());381}382}383}384};385386// "register info"387class CommandObjectRegisterInfo : public CommandObjectParsed {388public:389CommandObjectRegisterInfo(CommandInterpreter &interpreter)390: CommandObjectParsed(interpreter, "register info",391"View information about a register.", nullptr,392eCommandRequiresFrame | eCommandRequiresRegContext |393eCommandProcessMustBeLaunched |394eCommandProcessMustBePaused) {395SetHelpLong(R"(396Name The name lldb uses for the register, optionally with an alias.397Size The size of the register in bytes and again in bits.398Invalidates (*) The registers that would be changed if you wrote this399register. For example, writing to a narrower alias of a wider400register would change the value of the wider register.401Read from (*) The registers that the value of this register is constructed402from. For example, a narrower alias of a wider register will be403read from the wider register.404In sets (*) The register sets that contain this register. For example the405PC will be in the "General Purpose Register" set.406Fields (*) A table of the names and bit positions of the values contained407in this register.408409Fields marked with (*) may not always be present. Some information may be410different for the same register when connected to different debug servers.)");411412AddSimpleArgumentList(eArgTypeRegisterName);413}414415~CommandObjectRegisterInfo() override = default;416417void418HandleArgumentCompletion(CompletionRequest &request,419OptionElementVector &opt_element_vector) override {420if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)421return;422CommandObject::HandleArgumentCompletion(request, opt_element_vector);423}424425protected:426void DoExecute(Args &command, CommandReturnObject &result) override {427if (command.GetArgumentCount() != 1) {428result.AppendError("register info takes exactly 1 argument: <reg-name>");429return;430}431432llvm::StringRef reg_name = command[0].ref();433RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();434const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);435if (reg_info) {436DumpRegisterInfo(437result.GetOutputStream(), *reg_ctx, *reg_info,438GetCommandInterpreter().GetDebugger().GetTerminalWidth());439result.SetStatus(eReturnStatusSuccessFinishResult);440} else441result.AppendErrorWithFormat("No register found with name '%s'.\n",442reg_name.str().c_str());443}444};445446// CommandObjectRegister constructor447CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter)448: CommandObjectMultiword(interpreter, "register",449"Commands to access registers for the current "450"thread and stack frame.",451"register [read|write|info] ...") {452LoadSubCommand("read",453CommandObjectSP(new CommandObjectRegisterRead(interpreter)));454LoadSubCommand("write",455CommandObjectSP(new CommandObjectRegisterWrite(interpreter)));456LoadSubCommand("info",457CommandObjectSP(new CommandObjectRegisterInfo(interpreter)));458}459460CommandObjectRegister::~CommandObjectRegister() = default;461462463