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/CommandInterpreter.h"
14 #include "lldb/Interpreter/CommandReturnObject.h"
15 #include "lldb/Interpreter/OptionGroupFormat.h"
16 #include "lldb/Interpreter/OptionValueArray.h"
17 #include "lldb/Interpreter/OptionValueBoolean.h"
18 #include "lldb/Interpreter/OptionValueUInt64.h"
19 #include "lldb/Interpreter/Options.h"
20 #include "lldb/Target/ExecutionContext.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Target/RegisterContext.h"
23 #include "lldb/Target/SectionLoadList.h"
24 #include "lldb/Target/Thread.h"
25 #include "lldb/Utility/Args.h"
26 #include "lldb/Utility/DataExtractor.h"
27 #include "lldb/Utility/RegisterValue.h"
28 #include "lldb/Utility/Scalar.h"
29 #include "llvm/Support/Errno.h"
32 using namespace lldb_private;
36 static constexpr OptionDefinition g_register_read_options[] = {
38 { LLDB_OPT_SET_ALL, false, "alternate", 'A', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Display register names using the alternate register name if there is one." },
39 { LLDB_OPT_SET_1, false, "set", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeIndex, "Specify which register sets to dump by index." },
40 { LLDB_OPT_SET_2, false, "all", 'a', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Show all register sets." },
44 class CommandObjectRegisterRead : public CommandObjectParsed {
46 CommandObjectRegisterRead(CommandInterpreter &interpreter)
47 : CommandObjectParsed(
48 interpreter, "register read",
49 "Dump the contents of one or more register values from the current "
50 "frame. If no register is specified, dumps them all.",
52 eCommandRequiresFrame | eCommandRequiresRegContext |
53 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
54 m_option_group(), m_format_options(eFormatDefault),
56 CommandArgumentEntry arg;
57 CommandArgumentData register_arg;
59 // Define the first (and only) variant of this arg.
60 register_arg.arg_type = eArgTypeRegisterName;
61 register_arg.arg_repetition = eArgRepeatStar;
63 // There is only one variant this argument could be; put it into the
65 arg.push_back(register_arg);
67 // Push the data for the first argument into the m_arguments vector.
68 m_arguments.push_back(arg);
71 m_option_group.Append(&m_format_options,
72 OptionGroupFormat::OPTION_GROUP_FORMAT |
73 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
75 m_option_group.Append(&m_command_options);
76 m_option_group.Finalize();
79 ~CommandObjectRegisterRead() override = default;
81 Options *GetOptions() override { return &m_option_group; }
83 bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm,
84 RegisterContext *reg_ctx, const RegisterInfo *reg_info) {
86 RegisterValue reg_value;
88 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
91 bool prefix_with_altname = (bool)m_command_options.alternate_name;
92 bool prefix_with_name = !prefix_with_altname;
93 DumpRegisterValue(reg_value, &strm, reg_info, prefix_with_name,
94 prefix_with_altname, m_format_options.GetFormat(), 8);
95 if ((reg_info->encoding == eEncodingUint) ||
96 (reg_info->encoding == eEncodingSint)) {
97 Process *process = exe_ctx.GetProcessPtr();
98 if (process && reg_info->byte_size == process->GetAddressByteSize()) {
99 addr_t reg_addr = reg_value.GetAsUInt64(LLDB_INVALID_ADDRESS);
100 if (reg_addr != LLDB_INVALID_ADDRESS) {
102 if (exe_ctx.GetTargetRef()
103 .GetSectionLoadList()
104 .ResolveLoadAddress(reg_addr, so_reg_addr)) {
105 strm.PutCString(" ");
106 so_reg_addr.Dump(&strm, exe_ctx.GetBestExecutionContextScope(),
107 Address::DumpStyleResolvedDescription);
119 bool DumpRegisterSet(const ExecutionContext &exe_ctx, Stream &strm,
120 RegisterContext *reg_ctx, size_t set_idx,
121 bool primitive_only = false) {
122 uint32_t unavailable_count = 0;
123 uint32_t available_count = 0;
126 return false; // thread has no registers (i.e. core files are corrupt,
127 // incomplete crash logs...)
129 const RegisterSet *const reg_set = reg_ctx->GetRegisterSet(set_idx);
131 strm.Printf("%s:\n", (reg_set->name ? reg_set->name : "unknown"));
133 const size_t num_registers = reg_set->num_registers;
134 for (size_t reg_idx = 0; reg_idx < num_registers; ++reg_idx) {
135 const uint32_t reg = reg_set->registers[reg_idx];
136 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg);
137 // Skip the dumping of derived register if primitive_only is true.
138 if (primitive_only && reg_info && reg_info->value_regs)
141 if (DumpRegister(exe_ctx, strm, reg_ctx, reg_info))
147 if (unavailable_count) {
149 strm.Printf("%u registers were unavailable.\n", unavailable_count);
153 return available_count > 0;
157 bool DoExecute(Args &command, CommandReturnObject &result) override {
158 Stream &strm = result.GetOutputStream();
159 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
161 const RegisterInfo *reg_info = nullptr;
162 if (command.GetArgumentCount() == 0) {
165 size_t num_register_sets = 1;
166 const size_t set_array_size = m_command_options.set_indexes.GetSize();
167 if (set_array_size > 0) {
168 for (size_t i = 0; i < set_array_size; ++i) {
169 set_idx = m_command_options.set_indexes[i]->GetUInt64Value(UINT32_MAX,
171 if (set_idx < reg_ctx->GetRegisterSetCount()) {
172 if (!DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx)) {
174 result.AppendErrorWithFormatv("register read failed: {0}\n",
175 llvm::sys::StrError());
177 result.AppendError("unknown error while reading registers.\n");
178 result.SetStatus(eReturnStatusFailed);
182 result.AppendErrorWithFormat(
183 "invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx);
184 result.SetStatus(eReturnStatusFailed);
189 if (m_command_options.dump_all_sets)
190 num_register_sets = reg_ctx->GetRegisterSetCount();
192 for (set_idx = 0; set_idx < num_register_sets; ++set_idx) {
193 // When dump_all_sets option is set, dump primitive as well as
194 // derived registers.
195 DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx,
196 !m_command_options.dump_all_sets.GetCurrentValue());
200 if (m_command_options.dump_all_sets) {
201 result.AppendError("the --all option can't be used when registers "
202 "names are supplied as arguments\n");
203 result.SetStatus(eReturnStatusFailed);
204 } else if (m_command_options.set_indexes.GetSize() > 0) {
205 result.AppendError("the --set <set> option can't be used when "
206 "registers names are supplied as arguments\n");
207 result.SetStatus(eReturnStatusFailed);
209 for (auto &entry : command) {
210 // in most LLDB commands we accept $rbx as the name for register RBX
211 // - and here we would reject it and non-existant. we should be more
212 // consistent towards the user and allow them to say reg read $rbx -
213 // internally, however, we should be strict and not allow ourselves
214 // to call our registers $rbx in our own API
215 auto arg_str = entry.ref;
216 arg_str.consume_front("$");
218 reg_info = reg_ctx->GetRegisterInfoByName(arg_str);
221 if (!DumpRegister(m_exe_ctx, strm, reg_ctx, reg_info))
222 strm.Printf("%-12s = error: unavailable\n", reg_info->name);
224 result.AppendErrorWithFormat("Invalid register name '%s'.\n",
225 arg_str.str().c_str());
230 return result.Succeeded();
233 class CommandOptions : public OptionGroup {
237 set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64)),
238 dump_all_sets(false, false), // Initial and default values are false
239 alternate_name(false, false) {}
241 ~CommandOptions() override = default;
243 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
244 return llvm::makeArrayRef(g_register_read_options);
247 void OptionParsingStarting(ExecutionContext *execution_context) override {
249 dump_all_sets.Clear();
250 alternate_name.Clear();
253 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
254 ExecutionContext *execution_context) override {
256 const int short_option = GetDefinitions()[option_idx].short_option;
257 switch (short_option) {
259 OptionValueSP value_sp(OptionValueUInt64::Create(option_value, error));
261 set_indexes.AppendValue(value_sp);
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 dump_all_sets.SetCurrentValue(true);
269 dump_all_sets.SetOptionWasSet();
273 // When we don't use OptionValue::SetValueFromCString(const char *) to
274 // set an option value, it won't be marked as being set in the options
275 // so we make a call to let users know the value was set via option
276 alternate_name.SetCurrentValue(true);
277 dump_all_sets.SetOptionWasSet();
281 error.SetErrorStringWithFormat("unrecognized short option '%c'",
288 // Instance variables to hold the values for command options.
289 OptionValueArray set_indexes;
290 OptionValueBoolean dump_all_sets;
291 OptionValueBoolean alternate_name;
294 OptionGroupOptions m_option_group;
295 OptionGroupFormat m_format_options;
296 CommandOptions m_command_options;
300 class CommandObjectRegisterWrite : public CommandObjectParsed {
302 CommandObjectRegisterWrite(CommandInterpreter &interpreter)
303 : CommandObjectParsed(interpreter, "register write",
304 "Modify a single register value.", nullptr,
305 eCommandRequiresFrame | eCommandRequiresRegContext |
306 eCommandProcessMustBeLaunched |
307 eCommandProcessMustBePaused) {
308 CommandArgumentEntry arg1;
309 CommandArgumentEntry arg2;
310 CommandArgumentData register_arg;
311 CommandArgumentData value_arg;
313 // Define the first (and only) variant of this arg.
314 register_arg.arg_type = eArgTypeRegisterName;
315 register_arg.arg_repetition = eArgRepeatPlain;
317 // There is only one variant this argument could be; put it into the
319 arg1.push_back(register_arg);
321 // Define the first (and only) variant of this arg.
322 value_arg.arg_type = eArgTypeValue;
323 value_arg.arg_repetition = eArgRepeatPlain;
325 // There is only one variant this argument could be; put it into the
327 arg2.push_back(value_arg);
329 // Push the data for the first argument into the m_arguments vector.
330 m_arguments.push_back(arg1);
331 m_arguments.push_back(arg2);
334 ~CommandObjectRegisterWrite() override = default;
337 bool DoExecute(Args &command, CommandReturnObject &result) override {
338 DataExtractor reg_data;
339 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
341 if (command.GetArgumentCount() != 2) {
343 "register write takes exactly 2 arguments: <reg-name> <value>");
344 result.SetStatus(eReturnStatusFailed);
346 auto reg_name = command[0].ref;
347 auto value_str = command[1].ref;
349 // in most LLDB commands we accept $rbx as the name for register RBX -
350 // and here we would reject it and non-existant. we should be more
351 // consistent towards the user and allow them to say reg write $rbx -
352 // internally, however, we should be strict and not allow ourselves to
353 // call our registers $rbx in our own API
354 reg_name.consume_front("$");
356 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
359 RegisterValue reg_value;
361 Status error(reg_value.SetValueFromString(reg_info, value_str));
362 if (error.Success()) {
363 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
364 // Toss all frames and anything else in the thread after a register
366 m_exe_ctx.GetThreadRef().Flush();
367 result.SetStatus(eReturnStatusSuccessFinishNoResult);
371 if (error.AsCString()) {
372 result.AppendErrorWithFormat(
373 "Failed to write register '%s' with value '%s': %s\n",
374 reg_name.str().c_str(), value_str.str().c_str(),
377 result.AppendErrorWithFormat(
378 "Failed to write register '%s' with value '%s'",
379 reg_name.str().c_str(), value_str.str().c_str());
381 result.SetStatus(eReturnStatusFailed);
383 result.AppendErrorWithFormat("Register not found for '%s'.\n",
384 reg_name.str().c_str());
385 result.SetStatus(eReturnStatusFailed);
388 return result.Succeeded();
392 // CommandObjectRegister constructor
393 CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter)
394 : CommandObjectMultiword(interpreter, "register",
395 "Commands to access registers for the current "
396 "thread and stack frame.",
397 "register [read|write] ...") {
398 LoadSubCommand("read",
399 CommandObjectSP(new CommandObjectRegisterRead(interpreter)));
400 LoadSubCommand("write",
401 CommandObjectSP(new CommandObjectRegisterWrite(interpreter)));
404 CommandObjectRegister::~CommandObjectRegister() = default;