1 //===-- CommandObjectRegister.cpp -------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "CommandObjectRegister.h"
10 #include "lldb/Core/Debugger.h"
11 #include "lldb/Core/DumpRegisterValue.h"
12 #include "lldb/Host/OptionParser.h"
13 #include "lldb/Interpreter/CommandReturnObject.h"
14 #include "lldb/Interpreter/OptionGroupFormat.h"
15 #include "lldb/Interpreter/OptionValueArray.h"
16 #include "lldb/Interpreter/OptionValueBoolean.h"
17 #include "lldb/Interpreter/OptionValueUInt64.h"
18 #include "lldb/Interpreter/Options.h"
19 #include "lldb/Target/ExecutionContext.h"
20 #include "lldb/Target/Process.h"
21 #include "lldb/Target/RegisterContext.h"
22 #include "lldb/Target/SectionLoadList.h"
23 #include "lldb/Target/Thread.h"
24 #include "lldb/Utility/Args.h"
25 #include "lldb/Utility/DataExtractor.h"
26 #include "lldb/Utility/RegisterValue.h"
27 #include "llvm/Support/Errno.h"
30 using namespace lldb_private
;
33 #define LLDB_OPTIONS_register_read
34 #include "CommandOptions.inc"
36 class CommandObjectRegisterRead
: public CommandObjectParsed
{
38 CommandObjectRegisterRead(CommandInterpreter
&interpreter
)
39 : CommandObjectParsed(
40 interpreter
, "register read",
41 "Dump the contents of one or more register values from the current "
42 "frame. If no register is specified, dumps them all.",
44 eCommandRequiresFrame
| eCommandRequiresRegContext
|
45 eCommandProcessMustBeLaunched
| eCommandProcessMustBePaused
),
46 m_option_group(), m_format_options(eFormatDefault
),
48 CommandArgumentEntry arg
;
49 CommandArgumentData register_arg
;
51 // Define the first (and only) variant of this arg.
52 register_arg
.arg_type
= eArgTypeRegisterName
;
53 register_arg
.arg_repetition
= eArgRepeatStar
;
55 // There is only one variant this argument could be; put it into the
57 arg
.push_back(register_arg
);
59 // Push the data for the first argument into the m_arguments vector.
60 m_arguments
.push_back(arg
);
63 m_option_group
.Append(&m_format_options
,
64 OptionGroupFormat::OPTION_GROUP_FORMAT
|
65 OptionGroupFormat::OPTION_GROUP_GDB_FMT
,
67 m_option_group
.Append(&m_command_options
);
68 m_option_group
.Finalize();
71 ~CommandObjectRegisterRead() override
= default;
73 Options
*GetOptions() override
{ return &m_option_group
; }
75 bool DumpRegister(const ExecutionContext
&exe_ctx
, Stream
&strm
,
76 RegisterContext
*reg_ctx
, const RegisterInfo
*reg_info
) {
78 RegisterValue reg_value
;
80 if (reg_ctx
->ReadRegister(reg_info
, reg_value
)) {
83 bool prefix_with_altname
= (bool)m_command_options
.alternate_name
;
84 bool prefix_with_name
= !prefix_with_altname
;
85 DumpRegisterValue(reg_value
, &strm
, reg_info
, prefix_with_name
,
86 prefix_with_altname
, m_format_options
.GetFormat(), 8);
87 if ((reg_info
->encoding
== eEncodingUint
) ||
88 (reg_info
->encoding
== eEncodingSint
)) {
89 Process
*process
= exe_ctx
.GetProcessPtr();
90 if (process
&& reg_info
->byte_size
== process
->GetAddressByteSize()) {
91 addr_t reg_addr
= reg_value
.GetAsUInt64(LLDB_INVALID_ADDRESS
);
92 if (reg_addr
!= LLDB_INVALID_ADDRESS
) {
94 if (exe_ctx
.GetTargetRef()
96 .ResolveLoadAddress(reg_addr
, so_reg_addr
)) {
98 so_reg_addr
.Dump(&strm
, exe_ctx
.GetBestExecutionContextScope(),
99 Address::DumpStyleResolvedDescription
);
111 bool DumpRegisterSet(const ExecutionContext
&exe_ctx
, Stream
&strm
,
112 RegisterContext
*reg_ctx
, size_t set_idx
,
113 bool primitive_only
= false) {
114 uint32_t unavailable_count
= 0;
115 uint32_t available_count
= 0;
118 return false; // thread has no registers (i.e. core files are corrupt,
119 // incomplete crash logs...)
121 const RegisterSet
*const reg_set
= reg_ctx
->GetRegisterSet(set_idx
);
123 strm
.Printf("%s:\n", (reg_set
->name
? reg_set
->name
: "unknown"));
125 const size_t num_registers
= reg_set
->num_registers
;
126 for (size_t reg_idx
= 0; reg_idx
< num_registers
; ++reg_idx
) {
127 const uint32_t reg
= reg_set
->registers
[reg_idx
];
128 const RegisterInfo
*reg_info
= reg_ctx
->GetRegisterInfoAtIndex(reg
);
129 // Skip the dumping of derived register if primitive_only is true.
130 if (primitive_only
&& reg_info
&& reg_info
->value_regs
)
133 if (DumpRegister(exe_ctx
, strm
, reg_ctx
, reg_info
))
139 if (unavailable_count
) {
141 strm
.Printf("%u registers were unavailable.\n", unavailable_count
);
145 return available_count
> 0;
149 bool DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
150 Stream
&strm
= result
.GetOutputStream();
151 RegisterContext
*reg_ctx
= m_exe_ctx
.GetRegisterContext();
153 const RegisterInfo
*reg_info
= nullptr;
154 if (command
.GetArgumentCount() == 0) {
157 size_t num_register_sets
= 1;
158 const size_t set_array_size
= m_command_options
.set_indexes
.GetSize();
159 if (set_array_size
> 0) {
160 for (size_t i
= 0; i
< set_array_size
; ++i
) {
161 set_idx
= m_command_options
.set_indexes
[i
]->GetUInt64Value(UINT32_MAX
,
163 if (set_idx
< reg_ctx
->GetRegisterSetCount()) {
164 if (!DumpRegisterSet(m_exe_ctx
, strm
, reg_ctx
, set_idx
)) {
166 result
.AppendErrorWithFormatv("register read failed: {0}\n",
167 llvm::sys::StrError());
169 result
.AppendError("unknown error while reading registers.\n");
170 result
.SetStatus(eReturnStatusFailed
);
174 result
.AppendErrorWithFormat(
175 "invalid register set index: %" PRIu64
"\n", (uint64_t)set_idx
);
176 result
.SetStatus(eReturnStatusFailed
);
181 if (m_command_options
.dump_all_sets
)
182 num_register_sets
= reg_ctx
->GetRegisterSetCount();
184 for (set_idx
= 0; set_idx
< num_register_sets
; ++set_idx
) {
185 // When dump_all_sets option is set, dump primitive as well as
186 // derived registers.
187 DumpRegisterSet(m_exe_ctx
, strm
, reg_ctx
, set_idx
,
188 !m_command_options
.dump_all_sets
.GetCurrentValue());
192 if (m_command_options
.dump_all_sets
) {
193 result
.AppendError("the --all option can't be used when registers "
194 "names are supplied as arguments\n");
195 result
.SetStatus(eReturnStatusFailed
);
196 } else if (m_command_options
.set_indexes
.GetSize() > 0) {
197 result
.AppendError("the --set <set> option can't be used when "
198 "registers names are supplied as arguments\n");
199 result
.SetStatus(eReturnStatusFailed
);
201 for (auto &entry
: command
) {
202 // in most LLDB commands we accept $rbx as the name for register RBX
203 // - and here we would reject it and non-existant. we should be more
204 // consistent towards the user and allow them to say reg read $rbx -
205 // internally, however, we should be strict and not allow ourselves
206 // to call our registers $rbx in our own API
207 auto arg_str
= entry
.ref();
208 arg_str
.consume_front("$");
210 reg_info
= reg_ctx
->GetRegisterInfoByName(arg_str
);
213 if (!DumpRegister(m_exe_ctx
, strm
, reg_ctx
, reg_info
))
214 strm
.Printf("%-12s = error: unavailable\n", reg_info
->name
);
216 result
.AppendErrorWithFormat("Invalid register name '%s'.\n",
217 arg_str
.str().c_str());
222 return result
.Succeeded();
225 class CommandOptions
: public OptionGroup
{
229 set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64
)),
230 dump_all_sets(false, false), // Initial and default values are false
231 alternate_name(false, false) {}
233 ~CommandOptions() override
= default;
235 llvm::ArrayRef
<OptionDefinition
> GetDefinitions() override
{
236 return llvm::makeArrayRef(g_register_read_options
);
239 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
241 dump_all_sets
.Clear();
242 alternate_name
.Clear();
245 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_value
,
246 ExecutionContext
*execution_context
) override
{
248 const int short_option
= GetDefinitions()[option_idx
].short_option
;
249 switch (short_option
) {
251 OptionValueSP
value_sp(OptionValueUInt64::Create(option_value
, error
));
253 set_indexes
.AppendValue(value_sp
);
257 // When we don't use OptionValue::SetValueFromCString(const char *) to
258 // set an option value, it won't be marked as being set in the options
259 // so we make a call to let users know the value was set via option
260 dump_all_sets
.SetCurrentValue(true);
261 dump_all_sets
.SetOptionWasSet();
265 // When we don't use OptionValue::SetValueFromCString(const char *) to
266 // set an option value, it won't be marked as being set in the options
267 // so we make a call to let users know the value was set via option
268 alternate_name
.SetCurrentValue(true);
269 dump_all_sets
.SetOptionWasSet();
273 llvm_unreachable("Unimplemented option");
278 // Instance variables to hold the values for command options.
279 OptionValueArray set_indexes
;
280 OptionValueBoolean dump_all_sets
;
281 OptionValueBoolean alternate_name
;
284 OptionGroupOptions m_option_group
;
285 OptionGroupFormat m_format_options
;
286 CommandOptions m_command_options
;
290 class CommandObjectRegisterWrite
: public CommandObjectParsed
{
292 CommandObjectRegisterWrite(CommandInterpreter
&interpreter
)
293 : CommandObjectParsed(interpreter
, "register write",
294 "Modify a single register value.", nullptr,
295 eCommandRequiresFrame
| eCommandRequiresRegContext
|
296 eCommandProcessMustBeLaunched
|
297 eCommandProcessMustBePaused
) {
298 CommandArgumentEntry arg1
;
299 CommandArgumentEntry arg2
;
300 CommandArgumentData register_arg
;
301 CommandArgumentData value_arg
;
303 // Define the first (and only) variant of this arg.
304 register_arg
.arg_type
= eArgTypeRegisterName
;
305 register_arg
.arg_repetition
= eArgRepeatPlain
;
307 // There is only one variant this argument could be; put it into the
309 arg1
.push_back(register_arg
);
311 // Define the first (and only) variant of this arg.
312 value_arg
.arg_type
= eArgTypeValue
;
313 value_arg
.arg_repetition
= eArgRepeatPlain
;
315 // There is only one variant this argument could be; put it into the
317 arg2
.push_back(value_arg
);
319 // Push the data for the first argument into the m_arguments vector.
320 m_arguments
.push_back(arg1
);
321 m_arguments
.push_back(arg2
);
324 ~CommandObjectRegisterWrite() override
= default;
327 bool DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
328 DataExtractor reg_data
;
329 RegisterContext
*reg_ctx
= m_exe_ctx
.GetRegisterContext();
331 if (command
.GetArgumentCount() != 2) {
333 "register write takes exactly 2 arguments: <reg-name> <value>");
334 result
.SetStatus(eReturnStatusFailed
);
336 auto reg_name
= command
[0].ref();
337 auto value_str
= command
[1].ref();
339 // in most LLDB commands we accept $rbx as the name for register RBX -
340 // and here we would reject it and non-existant. we should be more
341 // consistent towards the user and allow them to say reg write $rbx -
342 // internally, however, we should be strict and not allow ourselves to
343 // call our registers $rbx in our own API
344 reg_name
.consume_front("$");
346 const RegisterInfo
*reg_info
= reg_ctx
->GetRegisterInfoByName(reg_name
);
349 RegisterValue reg_value
;
351 Status
error(reg_value
.SetValueFromString(reg_info
, value_str
));
352 if (error
.Success()) {
353 if (reg_ctx
->WriteRegister(reg_info
, reg_value
)) {
354 // Toss all frames and anything else in the thread after a register
356 m_exe_ctx
.GetThreadRef().Flush();
357 result
.SetStatus(eReturnStatusSuccessFinishNoResult
);
361 if (error
.AsCString()) {
362 result
.AppendErrorWithFormat(
363 "Failed to write register '%s' with value '%s': %s\n",
364 reg_name
.str().c_str(), value_str
.str().c_str(),
367 result
.AppendErrorWithFormat(
368 "Failed to write register '%s' with value '%s'",
369 reg_name
.str().c_str(), value_str
.str().c_str());
371 result
.SetStatus(eReturnStatusFailed
);
373 result
.AppendErrorWithFormat("Register not found for '%s'.\n",
374 reg_name
.str().c_str());
375 result
.SetStatus(eReturnStatusFailed
);
378 return result
.Succeeded();
382 // CommandObjectRegister constructor
383 CommandObjectRegister::CommandObjectRegister(CommandInterpreter
&interpreter
)
384 : CommandObjectMultiword(interpreter
, "register",
385 "Commands to access registers for the current "
386 "thread and stack frame.",
387 "register [read|write] ...") {
388 LoadSubCommand("read",
389 CommandObjectSP(new CommandObjectRegisterRead(interpreter
)));
390 LoadSubCommand("write",
391 CommandObjectSP(new CommandObjectRegisterWrite(interpreter
)));
394 CommandObjectRegister::~CommandObjectRegister() = default;