1 //===-- CommandObjectRegister.cpp -----------------------------------------===//
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/DumpRegisterInfo.h"
12 #include "lldb/Core/DumpRegisterValue.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/OptionGroupFormat.h"
18 #include "lldb/Interpreter/OptionValueArray.h"
19 #include "lldb/Interpreter/OptionValueBoolean.h"
20 #include "lldb/Interpreter/OptionValueUInt64.h"
21 #include "lldb/Interpreter/Options.h"
22 #include "lldb/Target/ExecutionContext.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Target/RegisterContext.h"
25 #include "lldb/Target/SectionLoadList.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Utility/Args.h"
28 #include "lldb/Utility/DataExtractor.h"
29 #include "lldb/Utility/RegisterValue.h"
30 #include "llvm/Support/Errno.h"
33 using namespace lldb_private
;
36 #define LLDB_OPTIONS_register_read
37 #include "CommandOptions.inc"
39 class CommandObjectRegisterRead
: public CommandObjectParsed
{
41 CommandObjectRegisterRead(CommandInterpreter
&interpreter
)
42 : CommandObjectParsed(
43 interpreter
, "register read",
44 "Dump the contents of one or more register values from the current "
45 "frame. If no register is specified, dumps them all.",
47 eCommandRequiresFrame
| eCommandRequiresRegContext
|
48 eCommandProcessMustBeLaunched
| eCommandProcessMustBePaused
),
49 m_format_options(eFormatDefault
, UINT64_MAX
, UINT64_MAX
,
50 {{CommandArgumentType::eArgTypeFormat
,
51 "Specify a format to be used for display. If this "
52 "is set, register fields will not be displayed."}}) {
53 CommandArgumentEntry arg
;
54 CommandArgumentData register_arg
;
56 // Define the first (and only) variant of this arg.
57 register_arg
.arg_type
= eArgTypeRegisterName
;
58 register_arg
.arg_repetition
= eArgRepeatStar
;
60 // There is only one variant this argument could be; put it into the
62 arg
.push_back(register_arg
);
64 // Push the data for the first argument into the m_arguments vector.
65 m_arguments
.push_back(arg
);
68 m_option_group
.Append(&m_format_options
,
69 OptionGroupFormat::OPTION_GROUP_FORMAT
|
70 OptionGroupFormat::OPTION_GROUP_GDB_FMT
,
72 m_option_group
.Append(&m_command_options
);
73 m_option_group
.Finalize();
76 ~CommandObjectRegisterRead() override
= default;
79 HandleArgumentCompletion(CompletionRequest
&request
,
80 OptionElementVector
&opt_element_vector
) override
{
81 if (!m_exe_ctx
.HasProcessScope())
84 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
85 GetCommandInterpreter(), lldb::eRegisterCompletion
, request
, nullptr);
88 Options
*GetOptions() override
{ return &m_option_group
; }
90 bool DumpRegister(const ExecutionContext
&exe_ctx
, Stream
&strm
,
91 RegisterContext
®_ctx
, const RegisterInfo
®_info
,
93 RegisterValue reg_value
;
94 if (!reg_ctx
.ReadRegister(®_info
, reg_value
))
99 bool prefix_with_altname
= (bool)m_command_options
.alternate_name
;
100 bool prefix_with_name
= !prefix_with_altname
;
101 DumpRegisterValue(reg_value
, strm
, reg_info
, prefix_with_name
,
102 prefix_with_altname
, m_format_options
.GetFormat(), 8,
103 exe_ctx
.GetBestExecutionContextScope(), print_flags
,
104 exe_ctx
.GetTargetSP());
105 if ((reg_info
.encoding
== eEncodingUint
) ||
106 (reg_info
.encoding
== eEncodingSint
)) {
107 Process
*process
= exe_ctx
.GetProcessPtr();
108 if (process
&& reg_info
.byte_size
== process
->GetAddressByteSize()) {
109 addr_t reg_addr
= reg_value
.GetAsUInt64(LLDB_INVALID_ADDRESS
);
110 if (reg_addr
!= LLDB_INVALID_ADDRESS
) {
112 if (exe_ctx
.GetTargetRef().GetSectionLoadList().ResolveLoadAddress(
113 reg_addr
, so_reg_addr
)) {
114 strm
.PutCString(" ");
115 so_reg_addr
.Dump(&strm
, exe_ctx
.GetBestExecutionContextScope(),
116 Address::DumpStyleResolvedDescription
);
125 bool DumpRegisterSet(const ExecutionContext
&exe_ctx
, Stream
&strm
,
126 RegisterContext
*reg_ctx
, size_t set_idx
,
127 bool primitive_only
= false) {
128 uint32_t unavailable_count
= 0;
129 uint32_t available_count
= 0;
132 return false; // thread has no registers (i.e. core files are corrupt,
133 // incomplete crash logs...)
135 const RegisterSet
*const reg_set
= reg_ctx
->GetRegisterSet(set_idx
);
137 strm
.Printf("%s:\n", (reg_set
->name
? reg_set
->name
: "unknown"));
139 const size_t num_registers
= reg_set
->num_registers
;
140 for (size_t reg_idx
= 0; reg_idx
< num_registers
; ++reg_idx
) {
141 const uint32_t reg
= reg_set
->registers
[reg_idx
];
142 const RegisterInfo
*reg_info
= reg_ctx
->GetRegisterInfoAtIndex(reg
);
143 // Skip the dumping of derived register if primitive_only is true.
144 if (primitive_only
&& reg_info
&& reg_info
->value_regs
)
147 if (reg_info
&& DumpRegister(exe_ctx
, strm
, *reg_ctx
, *reg_info
,
148 /*print_flags=*/false))
154 if (unavailable_count
) {
156 strm
.Printf("%u registers were unavailable.\n", unavailable_count
);
160 return available_count
> 0;
164 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
165 Stream
&strm
= result
.GetOutputStream();
166 RegisterContext
*reg_ctx
= m_exe_ctx
.GetRegisterContext();
168 if (command
.GetArgumentCount() == 0) {
171 size_t num_register_sets
= 1;
172 const size_t set_array_size
= m_command_options
.set_indexes
.GetSize();
173 if (set_array_size
> 0) {
174 for (size_t i
= 0; i
< set_array_size
; ++i
) {
176 m_command_options
.set_indexes
[i
]->GetValueAs
<uint64_t>().value_or(
178 if (set_idx
< reg_ctx
->GetRegisterSetCount()) {
179 if (!DumpRegisterSet(m_exe_ctx
, strm
, reg_ctx
, set_idx
)) {
181 result
.AppendErrorWithFormatv("register read failed: {0}\n",
182 llvm::sys::StrError());
184 result
.AppendError("unknown error while reading registers.\n");
188 result
.AppendErrorWithFormat(
189 "invalid register set index: %" PRIu64
"\n", (uint64_t)set_idx
);
194 if (m_command_options
.dump_all_sets
)
195 num_register_sets
= reg_ctx
->GetRegisterSetCount();
197 for (set_idx
= 0; set_idx
< num_register_sets
; ++set_idx
) {
198 // When dump_all_sets option is set, dump primitive as well as
199 // derived registers.
200 DumpRegisterSet(m_exe_ctx
, strm
, reg_ctx
, set_idx
,
201 !m_command_options
.dump_all_sets
.GetCurrentValue());
205 if (m_command_options
.dump_all_sets
) {
206 result
.AppendError("the --all option can't be used when registers "
207 "names are supplied as arguments\n");
208 } else if (m_command_options
.set_indexes
.GetSize() > 0) {
209 result
.AppendError("the --set <set> option can't be used when "
210 "registers names are supplied as arguments\n");
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 if (const RegisterInfo
*reg_info
=
222 reg_ctx
->GetRegisterInfoByName(arg_str
)) {
223 // If they have asked for a specific format don't obscure that by
224 // printing flags afterwards.
226 !m_format_options
.GetFormatValue().OptionWasSet();
227 if (!DumpRegister(m_exe_ctx
, strm
, *reg_ctx
, *reg_info
,
229 strm
.Printf("%-12s = error: unavailable\n", reg_info
->name
);
231 result
.AppendErrorWithFormat("Invalid register name '%s'.\n",
232 arg_str
.str().c_str());
239 class CommandOptions
: public OptionGroup
{
242 : set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64
)),
243 dump_all_sets(false, false), // Initial and default values are false
244 alternate_name(false, false) {}
246 ~CommandOptions() override
= default;
248 llvm::ArrayRef
<OptionDefinition
> GetDefinitions() override
{
249 return llvm::ArrayRef(g_register_read_options
);
252 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
254 dump_all_sets
.Clear();
255 alternate_name
.Clear();
258 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_value
,
259 ExecutionContext
*execution_context
) override
{
261 const int short_option
= GetDefinitions()[option_idx
].short_option
;
262 switch (short_option
) {
264 OptionValueSP
value_sp(OptionValueUInt64::Create(option_value
, error
));
266 set_indexes
.AppendValue(value_sp
);
270 // When we don't use OptionValue::SetValueFromCString(const char *) to
271 // set an option value, it won't be marked as being set in the options
272 // so we make a call to let users know the value was set via option
273 dump_all_sets
.SetCurrentValue(true);
274 dump_all_sets
.SetOptionWasSet();
278 // When we don't use OptionValue::SetValueFromCString(const char *) to
279 // set an option value, it won't be marked as being set in the options
280 // so we make a call to let users know the value was set via option
281 alternate_name
.SetCurrentValue(true);
282 dump_all_sets
.SetOptionWasSet();
286 llvm_unreachable("Unimplemented option");
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
;
303 class CommandObjectRegisterWrite
: public CommandObjectParsed
{
305 CommandObjectRegisterWrite(CommandInterpreter
&interpreter
)
306 : CommandObjectParsed(interpreter
, "register write",
307 "Modify a single register value.", nullptr,
308 eCommandRequiresFrame
| eCommandRequiresRegContext
|
309 eCommandProcessMustBeLaunched
|
310 eCommandProcessMustBePaused
) {
311 CommandArgumentEntry arg1
;
312 CommandArgumentEntry arg2
;
313 CommandArgumentData register_arg
;
314 CommandArgumentData value_arg
;
316 // Define the first (and only) variant of this arg.
317 register_arg
.arg_type
= eArgTypeRegisterName
;
318 register_arg
.arg_repetition
= eArgRepeatPlain
;
320 // There is only one variant this argument could be; put it into the
322 arg1
.push_back(register_arg
);
324 // Define the first (and only) variant of this arg.
325 value_arg
.arg_type
= eArgTypeValue
;
326 value_arg
.arg_repetition
= eArgRepeatPlain
;
328 // There is only one variant this argument could be; put it into the
330 arg2
.push_back(value_arg
);
332 // Push the data for the first argument into the m_arguments vector.
333 m_arguments
.push_back(arg1
);
334 m_arguments
.push_back(arg2
);
337 ~CommandObjectRegisterWrite() override
= default;
340 HandleArgumentCompletion(CompletionRequest
&request
,
341 OptionElementVector
&opt_element_vector
) override
{
342 if (!m_exe_ctx
.HasProcessScope() || request
.GetCursorIndex() != 0)
345 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
346 GetCommandInterpreter(), lldb::eRegisterCompletion
, request
, nullptr);
350 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
351 DataExtractor reg_data
;
352 RegisterContext
*reg_ctx
= m_exe_ctx
.GetRegisterContext();
354 if (command
.GetArgumentCount() != 2) {
356 "register write takes exactly 2 arguments: <reg-name> <value>");
358 auto reg_name
= command
[0].ref();
359 auto value_str
= command
[1].ref();
361 // in most LLDB commands we accept $rbx as the name for register RBX -
362 // and here we would reject it and non-existant. we should be more
363 // consistent towards the user and allow them to say reg write $rbx -
364 // internally, however, we should be strict and not allow ourselves to
365 // call our registers $rbx in our own API
366 reg_name
.consume_front("$");
368 const RegisterInfo
*reg_info
= reg_ctx
->GetRegisterInfoByName(reg_name
);
371 RegisterValue reg_value
;
373 Status
error(reg_value
.SetValueFromString(reg_info
, value_str
));
374 if (error
.Success()) {
375 if (reg_ctx
->WriteRegister(reg_info
, reg_value
)) {
376 // Toss all frames and anything else in the thread after a register
378 m_exe_ctx
.GetThreadRef().Flush();
379 result
.SetStatus(eReturnStatusSuccessFinishNoResult
);
383 if (error
.AsCString()) {
384 result
.AppendErrorWithFormat(
385 "Failed to write register '%s' with value '%s': %s\n",
386 reg_name
.str().c_str(), value_str
.str().c_str(),
389 result
.AppendErrorWithFormat(
390 "Failed to write register '%s' with value '%s'",
391 reg_name
.str().c_str(), value_str
.str().c_str());
394 result
.AppendErrorWithFormat("Register not found for '%s'.\n",
395 reg_name
.str().c_str());
402 class CommandObjectRegisterInfo
: public CommandObjectParsed
{
404 CommandObjectRegisterInfo(CommandInterpreter
&interpreter
)
405 : CommandObjectParsed(interpreter
, "register info",
406 "View information about a register.", nullptr,
407 eCommandRequiresFrame
| eCommandRequiresRegContext
|
408 eCommandProcessMustBeLaunched
|
409 eCommandProcessMustBePaused
) {
411 Name The name lldb uses for the register, optionally with an alias.
412 Size The size of the register in bytes and again in bits.
413 Invalidates (*) The registers that would be changed if you wrote this
414 register. For example, writing to a narrower alias of a wider
415 register would change the value of the wider register.
416 Read from (*) The registers that the value of this register is constructed
417 from. For example, a narrower alias of a wider register will be
418 read from the wider register.
419 In sets (*) The register sets that contain this register. For example the
420 PC will be in the "General Purpose Register
" set.
421 Fields (*) A table of the names and bit positions of the values contained
424 Fields marked with (*) may not always be present. Some information may be
425 different for the same register when connected to different debug servers.)");
427 CommandArgumentData register_arg
;
428 register_arg
.arg_type
= eArgTypeRegisterName
;
429 register_arg
.arg_repetition
= eArgRepeatPlain
;
431 CommandArgumentEntry arg1
;
432 arg1
.push_back(register_arg
);
433 m_arguments
.push_back(arg1
);
436 ~CommandObjectRegisterInfo() override
= default;
439 HandleArgumentCompletion(CompletionRequest
&request
,
440 OptionElementVector
&opt_element_vector
) override
{
441 if (!m_exe_ctx
.HasProcessScope() || request
.GetCursorIndex() != 0)
443 CommandCompletions::InvokeCommonCompletionCallbacks(
444 GetCommandInterpreter(), lldb::eRegisterCompletion
, request
, nullptr);
448 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
449 if (command
.GetArgumentCount() != 1) {
450 result
.AppendError("register info takes exactly 1 argument: <reg-name>");
454 llvm::StringRef reg_name
= command
[0].ref();
455 RegisterContext
*reg_ctx
= m_exe_ctx
.GetRegisterContext();
456 const RegisterInfo
*reg_info
= reg_ctx
->GetRegisterInfoByName(reg_name
);
459 result
.GetOutputStream(), *reg_ctx
, *reg_info
,
460 GetCommandInterpreter().GetDebugger().GetTerminalWidth());
461 result
.SetStatus(eReturnStatusSuccessFinishResult
);
463 result
.AppendErrorWithFormat("No register found with name '%s'.\n",
464 reg_name
.str().c_str());
468 // CommandObjectRegister constructor
469 CommandObjectRegister::CommandObjectRegister(CommandInterpreter
&interpreter
)
470 : CommandObjectMultiword(interpreter
, "register",
471 "Commands to access registers for the current "
472 "thread and stack frame.",
473 "register [read|write|info] ...") {
474 LoadSubCommand("read",
475 CommandObjectSP(new CommandObjectRegisterRead(interpreter
)));
476 LoadSubCommand("write",
477 CommandObjectSP(new CommandObjectRegisterWrite(interpreter
)));
478 LoadSubCommand("info",
479 CommandObjectSP(new CommandObjectRegisterInfo(interpreter
)));
482 CommandObjectRegister::~CommandObjectRegister() = default;