LLDB mainline
CommandObjectRegister.cpp
Go to the documentation of this file.
1//===-- CommandObjectRegister.cpp -----------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
10#include "lldb/Core/Debugger.h"
23#include "lldb/Target/Process.h"
26#include "lldb/Target/Thread.h"
27#include "lldb/Utility/Args.h"
30#include "llvm/Support/Errno.h"
31
32using namespace lldb;
33using namespace lldb_private;
34
35// "register read"
36#define LLDB_OPTIONS_register_read
37#include "CommandOptions.inc"
38
40public:
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.",
46 nullptr,
47 eCommandRequiresFrame | eCommandRequiresRegContext |
48 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
50 {{CommandArgumentType::eArgTypeFormat,
51 "Specify a format to be used for display. If this "
52 "is set, register fields will not be displayed."}}) {
54 CommandArgumentData register_arg;
55
56 // Define the first (and only) variant of this arg.
57 register_arg.arg_type = eArgTypeRegisterName;
58 register_arg.arg_repetition = eArgRepeatStar;
59
60 // There is only one variant this argument could be; put it into the
61 // argument entry.
62 arg.push_back(register_arg);
63
64 // Push the data for the first argument into the m_arguments vector.
65 m_arguments.push_back(arg);
66
67 // Add the "--format"
74 }
75
76 ~CommandObjectRegisterRead() override = default;
77
78 void
80 OptionElementVector &opt_element_vector) override {
82 return;
83
86 }
87
88 Options *GetOptions() override { return &m_option_group; }
89
90 bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm,
91 RegisterContext &reg_ctx, const RegisterInfo &reg_info,
92 bool print_flags) {
93 RegisterValue reg_value;
94 if (!reg_ctx.ReadRegister(&reg_info, reg_value))
95 return false;
96
97 strm.Indent();
98
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) {
111 Address so_reg_addr;
113 reg_addr, so_reg_addr)) {
114 strm.PutCString(" ");
115 so_reg_addr.Dump(&strm, exe_ctx.GetBestExecutionContextScope(),
117 }
118 }
119 }
120 }
121 strm.EOL();
122 return true;
123 }
124
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;
130
131 if (!reg_ctx)
132 return false; // thread has no registers (i.e. core files are corrupt,
133 // incomplete crash logs...)
134
135 const RegisterSet *const reg_set = reg_ctx->GetRegisterSet(set_idx);
136 if (reg_set) {
137 strm.Printf("%s:\n", (reg_set->name ? reg_set->name : "unknown"));
138 strm.IndentMore();
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)
145 continue;
146
147 if (reg_info && DumpRegister(exe_ctx, strm, *reg_ctx, *reg_info,
148 /*print_flags=*/false))
149 ++available_count;
150 else
151 ++unavailable_count;
152 }
153 strm.IndentLess();
154 if (unavailable_count) {
155 strm.Indent();
156 strm.Printf("%u registers were unavailable.\n", unavailable_count);
157 }
158 strm.EOL();
159 }
160 return available_count > 0;
161 }
162
163protected:
164 bool DoExecute(Args &command, CommandReturnObject &result) override {
165 Stream &strm = result.GetOutputStream();
167
168 if (command.GetArgumentCount() == 0) {
169 size_t set_idx;
170
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) {
175 set_idx =
176 m_command_options.set_indexes[i]->GetValueAs<uint64_t>().value_or(
177 UINT32_MAX);
178 if (set_idx < reg_ctx->GetRegisterSetCount()) {
179 if (!DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx)) {
180 if (errno)
181 result.AppendErrorWithFormatv("register read failed: {0}\n",
182 llvm::sys::StrError());
183 else
184 result.AppendError("unknown error while reading registers.\n");
185 break;
186 }
187 } else {
189 "invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx);
190 break;
191 }
192 }
193 } else {
195 num_register_sets = reg_ctx->GetRegisterSetCount();
196
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,
202 }
203 }
204 } else {
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");
211 } else {
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("$");
220
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.
225 bool print_flags =
227 if (!DumpRegister(m_exe_ctx, strm, *reg_ctx, *reg_info,
228 print_flags))
229 strm.Printf("%-12s = error: unavailable\n", reg_info->name);
230 } else {
231 result.AppendErrorWithFormat("Invalid register name '%s'.\n",
232 arg_str.str().c_str());
233 }
234 }
235 }
236 }
237 return result.Succeeded();
238 }
239
241 public:
243 : set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64)),
244 dump_all_sets(false, false), // Initial and default values are false
245 alternate_name(false, false) {}
246
247 ~CommandOptions() override = default;
248
249 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
250 return llvm::ArrayRef(g_register_read_options);
251 }
252
253 void OptionParsingStarting(ExecutionContext *execution_context) override {
257 }
258
259 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
260 ExecutionContext *execution_context) override {
262 const int short_option = GetDefinitions()[option_idx].short_option;
263 switch (short_option) {
264 case 's': {
265 OptionValueSP value_sp(OptionValueUInt64::Create(option_value, error));
266 if (value_sp)
267 set_indexes.AppendValue(value_sp);
268 } break;
269
270 case 'a':
271 // When we don't use OptionValue::SetValueFromCString(const char *) to
272 // set an option value, it won't be marked as being set in the options
273 // so we make a call to let users know the value was set via option
276 break;
277
278 case 'A':
279 // When we don't use OptionValue::SetValueFromCString(const char *) to
280 // set an option value, it won't be marked as being set in the options
281 // so we make a call to let users know the value was set via option
284 break;
285
286 default:
287 llvm_unreachable("Unimplemented option");
288 }
289 return error;
290 }
291
292 // Instance variables to hold the values for command options.
296 };
297
301};
302
303// "register write"
305public:
307 : CommandObjectParsed(interpreter, "register write",
308 "Modify a single register value.", nullptr,
309 eCommandRequiresFrame | eCommandRequiresRegContext |
310 eCommandProcessMustBeLaunched |
311 eCommandProcessMustBePaused) {
314 CommandArgumentData register_arg;
315 CommandArgumentData value_arg;
316
317 // Define the first (and only) variant of this arg.
318 register_arg.arg_type = eArgTypeRegisterName;
319 register_arg.arg_repetition = eArgRepeatPlain;
320
321 // There is only one variant this argument could be; put it into the
322 // argument entry.
323 arg1.push_back(register_arg);
324
325 // Define the first (and only) variant of this arg.
326 value_arg.arg_type = eArgTypeValue;
328
329 // There is only one variant this argument could be; put it into the
330 // argument entry.
331 arg2.push_back(value_arg);
332
333 // Push the data for the first argument into the m_arguments vector.
334 m_arguments.push_back(arg1);
335 m_arguments.push_back(arg2);
336 }
337
338 ~CommandObjectRegisterWrite() override = default;
339
340 void
342 OptionElementVector &opt_element_vector) override {
343 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
344 return;
345
348 }
349
350protected:
351 bool DoExecute(Args &command, CommandReturnObject &result) override {
352 DataExtractor reg_data;
354
355 if (command.GetArgumentCount() != 2) {
356 result.AppendError(
357 "register write takes exactly 2 arguments: <reg-name> <value>");
358 } else {
359 auto reg_name = command[0].ref();
360 auto value_str = command[1].ref();
361
362 // in most LLDB commands we accept $rbx as the name for register RBX -
363 // and here we would reject it and non-existant. we should be more
364 // consistent towards the user and allow them to say reg write $rbx -
365 // internally, however, we should be strict and not allow ourselves to
366 // call our registers $rbx in our own API
367 reg_name.consume_front("$");
368
369 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
370
371 if (reg_info) {
372 RegisterValue reg_value;
373
374 Status error(reg_value.SetValueFromString(reg_info, value_str));
375 if (error.Success()) {
376 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
377 // Toss all frames and anything else in the thread after a register
378 // has been written.
381 return true;
382 }
383 }
384 if (error.AsCString()) {
386 "Failed to write register '%s' with value '%s': %s\n",
387 reg_name.str().c_str(), value_str.str().c_str(),
388 error.AsCString());
389 } else {
391 "Failed to write register '%s' with value '%s'",
392 reg_name.str().c_str(), value_str.str().c_str());
393 }
394 } else {
395 result.AppendErrorWithFormat("Register not found for '%s'.\n",
396 reg_name.str().c_str());
397 }
398 }
399 return result.Succeeded();
400 }
401};
402
403// "register info"
405public:
407 : CommandObjectParsed(interpreter, "register info",
408 "View information about a register.", nullptr,
409 eCommandRequiresFrame | eCommandRequiresRegContext |
410 eCommandProcessMustBeLaunched |
411 eCommandProcessMustBePaused) {
412 SetHelpLong(R"(
413Name The name lldb uses for the register, optionally with an alias.
414Size The size of the register in bytes and again in bits.
415Invalidates (*) The registers that would be changed if you wrote this
416 register. For example, writing to a narrower alias of a wider
417 register would change the value of the wider register.
418Read from (*) The registers that the value of this register is constructed
419 from. For example, a narrower alias of a wider register will be
420 read from the wider register.
421In sets (*) The register sets that contain this register. For example the
422 PC will be in the "General Purpose Register" set.
423Fields (*) A table of the names and bit positions of the values contained
424 in this register.
425
426Fields marked with (*) may not always be present. Some information may be
427different for the same register when connected to different debug servers.)");
428
429 CommandArgumentData register_arg;
430 register_arg.arg_type = eArgTypeRegisterName;
431 register_arg.arg_repetition = eArgRepeatPlain;
432
434 arg1.push_back(register_arg);
435 m_arguments.push_back(arg1);
436 }
437
438 ~CommandObjectRegisterInfo() override = default;
439
440 void
442 OptionElementVector &opt_element_vector) override {
443 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
444 return;
447 }
448
449protected:
450 bool DoExecute(Args &command, CommandReturnObject &result) override {
451 if (command.GetArgumentCount() != 1) {
452 result.AppendError("register info takes exactly 1 argument: <reg-name>");
453 return result.Succeeded();
454 }
455
456 llvm::StringRef reg_name = command[0].ref();
458 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
459 if (reg_info) {
461 result.GetOutputStream(), *reg_ctx, *reg_info,
462 GetCommandInterpreter().GetDebugger().GetTerminalWidth());
464 } else
465 result.AppendErrorWithFormat("No register found with name '%s'.\n",
466 reg_name.str().c_str());
467
468 return result.Succeeded();
469 }
470};
471
472// CommandObjectRegister constructor
474 : CommandObjectMultiword(interpreter, "register",
475 "Commands to access registers for the current "
476 "thread and stack frame.",
477 "register [read|write|info] ...") {
478 LoadSubCommand("read",
480 LoadSubCommand("write",
482 LoadSubCommand("info",
484}
485
static llvm::raw_ostream & error(Stream &strm)
bool DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectRegisterInfo() override=default
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The input array contains a parsed version of the line.
CommandObjectRegisterInfo(CommandInterpreter &interpreter)
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
bool DumpRegisterSet(const ExecutionContext &exe_ctx, Stream &strm, RegisterContext *reg_ctx, size_t set_idx, bool primitive_only=false)
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The input array contains a parsed version of the line.
~CommandObjectRegisterRead() override=default
bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm, RegisterContext &reg_ctx, const RegisterInfo &reg_info, bool print_flags)
CommandObjectRegisterRead(CommandInterpreter &interpreter)
bool DoExecute(Args &command, CommandReturnObject &result) override
void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector) override
The input array contains a parsed version of the line.
~CommandObjectRegisterWrite() override=default
bool DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectRegisterWrite(CommandInterpreter &interpreter)
A section + offset based address class.
Definition: Address.h:59
@ DumpStyleResolvedDescription
Display the details about what an address resolves to.
Definition: Address.h:101
bool Dump(Stream *s, ExecutionContextScope *exe_scope, DumpStyle style, DumpStyle fallback_style=DumpStyleInvalid, uint32_t addr_byte_size=UINT32_MAX, bool all_ranges=false) const
Dump a description of this object to a Stream.
Definition: Address.cpp:406
A command line argument class.
Definition: Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.h:116
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
CommandObjectRegister(CommandInterpreter &interpreter)
std::vector< CommandArgumentData > CommandArgumentEntry
virtual void SetHelpLong(llvm::StringRef str)
ExecutionContext m_exe_ctx
std::vector< CommandArgumentEntry > m_arguments
CommandInterpreter & GetCommandInterpreter()
void AppendErrorWithFormatv(const char *format, Args &&... args)
void void AppendError(llvm::StringRef in_string)
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
"lldb/Utility/ArgCompletionRequest.h"
An data extractor class.
Definition: DataExtractor.h:48
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
bool HasProcessScope() const
Returns true the ExecutionContext object contains a valid target and process.
ExecutionContextScope * GetBestExecutionContextScope() const
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
Target & GetTargetRef() const
Returns a reference to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
Thread & GetThreadRef() const
Returns a reference to the thread object.
RegisterContext * GetRegisterContext() const
static const uint32_t OPTION_GROUP_GDB_FMT
static const uint32_t OPTION_GROUP_FORMAT
OptionValueFormat & GetFormatValue()
void Append(OptionGroup *group)
Append options from a OptionGroup class.
Definition: Options.cpp:755
bool AppendValue(const lldb::OptionValueSP &value_sp)
static lldb::OptionValueSP Create(llvm::StringRef value_str, Status &error)
std::optional< T > GetValueAs() const
Definition: OptionValue.h:273
A command line option parsing protocol class.
Definition: Options.h:58
A plug-in interface definition class for debugging a process.
Definition: Process.h:336
uint32_t GetAddressByteSize() const
Definition: Process.cpp:3403
virtual const RegisterSet * GetRegisterSet(size_t reg_set)=0
virtual const RegisterInfo * GetRegisterInfoAtIndex(size_t reg)=0
virtual bool WriteRegister(const RegisterInfo *reg_info, const RegisterValue &reg_value)=0
virtual size_t GetRegisterSetCount()=0
const RegisterInfo * GetRegisterInfoByName(llvm::StringRef reg_name, uint32_t start_idx=0)
virtual bool ReadRegister(const RegisterInfo *reg_info, RegisterValue &reg_value)=0
Status SetValueFromString(const RegisterInfo *reg_info, llvm::StringRef value_str)
uint64_t GetAsUInt64(uint64_t fail_value=UINT64_MAX, bool *success_ptr=nullptr) const
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, bool allow_section_end=false) const
An error handling class.
Definition: Status.h:44
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition: Stream.cpp:130
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:107
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:63
size_t EOL()
Output and End of Line character to the stream.
Definition: Stream.cpp:128
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition: Stream.cpp:171
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition: Stream.cpp:168
SectionLoadList & GetSectionLoadList()
Definition: Target.h:1122
#define UINT64_MAX
Definition: lldb-defines.h:23
#define LLDB_OPT_SET_ALL
Definition: lldb-defines.h:103
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:76
#define UINT32_MAX
Definition: lldb-defines.h:19
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
std::vector< OptionArgElement > OptionElementVector
Definition: Options.h:43
void DumpRegisterInfo(Stream &strm, RegisterContext &ctx, const RegisterInfo &info, uint32_t terminal_width)
void DumpRegisterValue(const RegisterValue &reg_val, Stream &s, const RegisterInfo &reg_info, bool prefix_with_name, bool prefix_with_alt_name, lldb::Format format, uint32_t reg_name_right_align_at=0, ExecutionContextScope *exe_scope=nullptr, bool print_flags=false, lldb::TargetSP target_sp=nullptr)
Definition: SBAddress.h:15
@ eRegisterCompletion
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
Definition: lldb-forward.h:315
@ eEncodingUint
unsigned integer
@ eEncodingSint
signed integer
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeRegisterName
uint64_t addr_t
Definition: lldb-types.h:79
std::shared_ptr< lldb_private::OptionValue > OptionValueSP
Definition: lldb-forward.h:363
Used to build individual command argument lists.
Definition: CommandObject.h:93
Every register is described in detail including its name, alternate name (optional),...
lldb::Encoding encoding
Encoding of the register bits.
uint32_t * value_regs
List of registers (terminated with LLDB_INVALID_REGNUM).
uint32_t byte_size
Size in bytes of the register.
Registers are grouped into register sets.
size_t num_registers
The number of registers in REGISTERS array below.
const uint32_t * registers
An array of register indices in this set.
const char * name
Name of this register set.