1 //===-- CommandObjectRegister.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 "CommandObjectRegister.h"
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/DumpRegisterValue.h"
13 #include "lldb/Core/RegisterValue.h"
14 #include "lldb/Core/Scalar.h"
15 #include "lldb/Host/OptionParser.h"
16 #include "lldb/Interpreter/CommandInterpreter.h"
17 #include "lldb/Interpreter/CommandReturnObject.h"
18 #include "lldb/Interpreter/OptionGroupFormat.h"
19 #include "lldb/Interpreter/OptionValueArray.h"
20 #include "lldb/Interpreter/OptionValueBoolean.h"
21 #include "lldb/Interpreter/OptionValueUInt64.h"
22 #include "lldb/Interpreter/Options.h"
23 #include "lldb/Target/ExecutionContext.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Target/RegisterContext.h"
26 #include "lldb/Target/SectionLoadList.h"
27 #include "lldb/Target/Thread.h"
28 #include "lldb/Utility/Args.h"
29 #include "lldb/Utility/DataExtractor.h"
30 #include "llvm/Support/Errno.h"
33 using namespace lldb_private;
35 //----------------------------------------------------------------------
37 //----------------------------------------------------------------------
39 static OptionDefinition g_register_read_options[] = {
41 { LLDB_OPT_SET_ALL, false, "alternate", 'A', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display register names using the alternate register name if there is one." },
42 { LLDB_OPT_SET_1, false, "set", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex, "Specify which register sets to dump by index." },
43 { LLDB_OPT_SET_2, false, "all", 'a', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Show all register sets." },
47 class CommandObjectRegisterRead : public CommandObjectParsed {
49 CommandObjectRegisterRead(CommandInterpreter &interpreter)
50 : CommandObjectParsed(
51 interpreter, "register read",
52 "Dump the contents of one or more register values from the current "
53 "frame. If no register is specified, dumps them all.",
55 eCommandRequiresFrame | eCommandRequiresRegContext |
56 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
57 m_option_group(), m_format_options(eFormatDefault),
59 CommandArgumentEntry arg;
60 CommandArgumentData register_arg;
62 // Define the first (and only) variant of this arg.
63 register_arg.arg_type = eArgTypeRegisterName;
64 register_arg.arg_repetition = eArgRepeatStar;
66 // There is only one variant this argument could be; put it into the
68 arg.push_back(register_arg);
70 // Push the data for the first argument into the m_arguments vector.
71 m_arguments.push_back(arg);
74 m_option_group.Append(&m_format_options,
75 OptionGroupFormat::OPTION_GROUP_FORMAT |
76 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
78 m_option_group.Append(&m_command_options);
79 m_option_group.Finalize();
82 ~CommandObjectRegisterRead() override = default;
84 Options *GetOptions() override { return &m_option_group; }
86 bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm,
87 RegisterContext *reg_ctx, const RegisterInfo *reg_info) {
89 RegisterValue reg_value;
91 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
94 bool prefix_with_altname = (bool)m_command_options.alternate_name;
95 bool prefix_with_name = !prefix_with_altname;
96 DumpRegisterValue(reg_value, &strm, reg_info, prefix_with_name,
97 prefix_with_altname, m_format_options.GetFormat(), 8);
98 if ((reg_info->encoding == eEncodingUint) ||
99 (reg_info->encoding == eEncodingSint)) {
100 Process *process = exe_ctx.GetProcessPtr();
101 if (process && reg_info->byte_size == process->GetAddressByteSize()) {
102 addr_t reg_addr = reg_value.GetAsUInt64(LLDB_INVALID_ADDRESS);
103 if (reg_addr != LLDB_INVALID_ADDRESS) {
105 if (exe_ctx.GetTargetRef()
106 .GetSectionLoadList()
107 .ResolveLoadAddress(reg_addr, so_reg_addr)) {
108 strm.PutCString(" ");
109 so_reg_addr.Dump(&strm, exe_ctx.GetBestExecutionContextScope(),
110 Address::DumpStyleResolvedDescription);
122 bool DumpRegisterSet(const ExecutionContext &exe_ctx, Stream &strm,
123 RegisterContext *reg_ctx, size_t set_idx,
124 bool primitive_only = false) {
125 uint32_t unavailable_count = 0;
126 uint32_t available_count = 0;
129 return false; // thread has no registers (i.e. core files are corrupt,
130 // incomplete crash logs...)
132 const RegisterSet *const reg_set = reg_ctx->GetRegisterSet(set_idx);
134 strm.Printf("%s:\n", (reg_set->name ? reg_set->name : "unknown"));
136 const size_t num_registers = reg_set->num_registers;
137 for (size_t reg_idx = 0; reg_idx < num_registers; ++reg_idx) {
138 const uint32_t reg = reg_set->registers[reg_idx];
139 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg);
140 // Skip the dumping of derived register if primitive_only is true.
141 if (primitive_only && reg_info && reg_info->value_regs)
144 if (DumpRegister(exe_ctx, strm, reg_ctx, reg_info))
150 if (unavailable_count) {
152 strm.Printf("%u registers were unavailable.\n", unavailable_count);
156 return available_count > 0;
160 bool DoExecute(Args &command, CommandReturnObject &result) override {
161 Stream &strm = result.GetOutputStream();
162 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
164 const RegisterInfo *reg_info = nullptr;
165 if (command.GetArgumentCount() == 0) {
168 size_t num_register_sets = 1;
169 const size_t set_array_size = m_command_options.set_indexes.GetSize();
170 if (set_array_size > 0) {
171 for (size_t i = 0; i < set_array_size; ++i) {
172 set_idx = m_command_options.set_indexes[i]->GetUInt64Value(UINT32_MAX,
174 if (set_idx < reg_ctx->GetRegisterSetCount()) {
175 if (!DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx)) {
177 result.AppendErrorWithFormatv("register read failed: {0}\n",
178 llvm::sys::StrError());
180 result.AppendError("unknown error while reading registers.\n");
181 result.SetStatus(eReturnStatusFailed);
185 result.AppendErrorWithFormat(
186 "invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx);
187 result.SetStatus(eReturnStatusFailed);
192 if (m_command_options.dump_all_sets)
193 num_register_sets = reg_ctx->GetRegisterSetCount();
195 for (set_idx = 0; set_idx < num_register_sets; ++set_idx) {
196 // When dump_all_sets option is set, dump primitive as well as
197 // derived registers.
198 DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx,
199 !m_command_options.dump_all_sets.GetCurrentValue());
203 if (m_command_options.dump_all_sets) {
204 result.AppendError("the --all option can't be used when registers "
205 "names are supplied as arguments\n");
206 result.SetStatus(eReturnStatusFailed);
207 } else if (m_command_options.set_indexes.GetSize() > 0) {
208 result.AppendError("the --set <set> option can't be used when "
209 "registers names are supplied as arguments\n");
210 result.SetStatus(eReturnStatusFailed);
212 for (auto &entry : command) {
213 // in most LLDB commands we accept $rbx as the name for register RBX
214 // - and here we would reject it and non-existant. we should be more
215 // consistent towards the user and allow them to say reg read $rbx -
216 // internally, however, we should be strict and not allow ourselves
217 // to call our registers $rbx in our own API
218 auto arg_str = entry.ref;
219 arg_str.consume_front("$");
221 reg_info = reg_ctx->GetRegisterInfoByName(arg_str);
224 if (!DumpRegister(m_exe_ctx, strm, reg_ctx, reg_info))
225 strm.Printf("%-12s = error: unavailable\n", reg_info->name);
227 result.AppendErrorWithFormat("Invalid register name '%s'.\n",
228 arg_str.str().c_str());
233 return result.Succeeded();
236 class CommandOptions : public OptionGroup {
240 set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64)),
241 dump_all_sets(false, false), // Initial and default values are false
242 alternate_name(false, false) {}
244 ~CommandOptions() override = default;
246 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
247 return llvm::makeArrayRef(g_register_read_options);
250 void OptionParsingStarting(ExecutionContext *execution_context) override {
252 dump_all_sets.Clear();
253 alternate_name.Clear();
256 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
257 ExecutionContext *execution_context) override {
259 const int short_option = GetDefinitions()[option_idx].short_option;
260 switch (short_option) {
262 OptionValueSP value_sp(OptionValueUInt64::Create(option_value, error));
264 set_indexes.AppendValue(value_sp);
268 // When we don't use OptionValue::SetValueFromCString(const char *) to
269 // set an option value, it won't be marked as being set in the options
270 // so we make a call to let users know the value was set via option
271 dump_all_sets.SetCurrentValue(true);
272 dump_all_sets.SetOptionWasSet();
276 // When we don't use OptionValue::SetValueFromCString(const char *) to
277 // set an option value, it won't be marked as being set in the options
278 // so we make a call to let users know the value was set via option
279 alternate_name.SetCurrentValue(true);
280 dump_all_sets.SetOptionWasSet();
284 error.SetErrorStringWithFormat("unrecognized short option '%c'",
291 // Instance variables to hold the values for command options.
292 OptionValueArray set_indexes;
293 OptionValueBoolean dump_all_sets;
294 OptionValueBoolean alternate_name;
297 OptionGroupOptions m_option_group;
298 OptionGroupFormat m_format_options;
299 CommandOptions m_command_options;
302 //----------------------------------------------------------------------
304 //----------------------------------------------------------------------
305 class CommandObjectRegisterWrite : public CommandObjectParsed {
307 CommandObjectRegisterWrite(CommandInterpreter &interpreter)
308 : CommandObjectParsed(interpreter, "register write",
309 "Modify a single register value.", nullptr,
310 eCommandRequiresFrame | eCommandRequiresRegContext |
311 eCommandProcessMustBeLaunched |
312 eCommandProcessMustBePaused) {
313 CommandArgumentEntry arg1;
314 CommandArgumentEntry arg2;
315 CommandArgumentData register_arg;
316 CommandArgumentData value_arg;
318 // Define the first (and only) variant of this arg.
319 register_arg.arg_type = eArgTypeRegisterName;
320 register_arg.arg_repetition = eArgRepeatPlain;
322 // There is only one variant this argument could be; put it into the
324 arg1.push_back(register_arg);
326 // Define the first (and only) variant of this arg.
327 value_arg.arg_type = eArgTypeValue;
328 value_arg.arg_repetition = eArgRepeatPlain;
330 // There is only one variant this argument could be; put it into the
332 arg2.push_back(value_arg);
334 // Push the data for the first argument into the m_arguments vector.
335 m_arguments.push_back(arg1);
336 m_arguments.push_back(arg2);
339 ~CommandObjectRegisterWrite() override = default;
342 bool DoExecute(Args &command, CommandReturnObject &result) override {
343 DataExtractor reg_data;
344 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
346 if (command.GetArgumentCount() != 2) {
348 "register write takes exactly 2 arguments: <reg-name> <value>");
349 result.SetStatus(eReturnStatusFailed);
351 auto reg_name = command[0].ref;
352 auto value_str = command[1].ref;
354 // in most LLDB commands we accept $rbx as the name for register RBX -
355 // and here we would reject it and non-existant. we should be more
356 // consistent towards the user and allow them to say reg write $rbx -
357 // internally, however, we should be strict and not allow ourselves to
358 // call our registers $rbx in our own API
359 reg_name.consume_front("$");
361 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
364 RegisterValue reg_value;
366 Status error(reg_value.SetValueFromString(reg_info, value_str));
367 if (error.Success()) {
368 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
369 // Toss all frames and anything else in the thread after a register
371 m_exe_ctx.GetThreadRef().Flush();
372 result.SetStatus(eReturnStatusSuccessFinishNoResult);
376 if (error.AsCString()) {
377 result.AppendErrorWithFormat(
378 "Failed to write register '%s' with value '%s': %s\n",
379 reg_name.str().c_str(), value_str.str().c_str(),
382 result.AppendErrorWithFormat(
383 "Failed to write register '%s' with value '%s'",
384 reg_name.str().c_str(), value_str.str().c_str());
386 result.SetStatus(eReturnStatusFailed);
388 result.AppendErrorWithFormat("Register not found for '%s'.\n",
389 reg_name.str().c_str());
390 result.SetStatus(eReturnStatusFailed);
393 return result.Succeeded();
397 //----------------------------------------------------------------------
398 // CommandObjectRegister constructor
399 //----------------------------------------------------------------------
400 CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter)
401 : CommandObjectMultiword(interpreter, "register",
402 "Commands to access registers for the current "
403 "thread and stack frame.",
404 "register [read|write] ...") {
405 LoadSubCommand("read",
406 CommandObjectSP(new CommandObjectRegisterRead(interpreter)));
407 LoadSubCommand("write",
408 CommandObjectSP(new CommandObjectRegisterWrite(interpreter)));
411 CommandObjectRegister::~CommandObjectRegister() = default;