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/RegisterValue.h"
13 #include "lldb/Core/Scalar.h"
14 #include "lldb/Host/OptionParser.h"
15 #include "lldb/Interpreter/Args.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/DataExtractor.h"
29 #include "llvm/Support/Errno.h"
32 using namespace lldb_private;
34 //----------------------------------------------------------------------
36 //----------------------------------------------------------------------
38 static OptionDefinition g_register_read_options[] = {
40 { 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." },
41 { LLDB_OPT_SET_1, false, "set", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex, "Specify which register sets to dump by index." },
42 { LLDB_OPT_SET_2, false, "all", 'a', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Show all register sets." },
46 class CommandObjectRegisterRead : public CommandObjectParsed {
48 CommandObjectRegisterRead(CommandInterpreter &interpreter)
49 : CommandObjectParsed(
50 interpreter, "register read",
51 "Dump the contents of one or more register values from the current "
52 "frame. If no register is specified, dumps them all.",
54 eCommandRequiresFrame | eCommandRequiresRegContext |
55 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
56 m_option_group(), m_format_options(eFormatDefault),
58 CommandArgumentEntry arg;
59 CommandArgumentData register_arg;
61 // Define the first (and only) variant of this arg.
62 register_arg.arg_type = eArgTypeRegisterName;
63 register_arg.arg_repetition = eArgRepeatStar;
65 // There is only one variant this argument could be; put it into the
67 arg.push_back(register_arg);
69 // Push the data for the first argument into the m_arguments vector.
70 m_arguments.push_back(arg);
73 m_option_group.Append(&m_format_options,
74 OptionGroupFormat::OPTION_GROUP_FORMAT |
75 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
77 m_option_group.Append(&m_command_options);
78 m_option_group.Finalize();
81 ~CommandObjectRegisterRead() override = default;
83 Options *GetOptions() override { return &m_option_group; }
85 bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm,
86 RegisterContext *reg_ctx, const RegisterInfo *reg_info) {
88 RegisterValue reg_value;
90 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
93 bool prefix_with_altname = (bool)m_command_options.alternate_name;
94 bool prefix_with_name = !prefix_with_altname;
95 reg_value.Dump(&strm, reg_info, prefix_with_name, prefix_with_altname,
96 m_format_options.GetFormat(), 8);
97 if ((reg_info->encoding == eEncodingUint) ||
98 (reg_info->encoding == eEncodingSint)) {
99 Process *process = exe_ctx.GetProcessPtr();
100 if (process && reg_info->byte_size == process->GetAddressByteSize()) {
101 addr_t reg_addr = reg_value.GetAsUInt64(LLDB_INVALID_ADDRESS);
102 if (reg_addr != LLDB_INVALID_ADDRESS) {
104 if (exe_ctx.GetTargetRef()
105 .GetSectionLoadList()
106 .ResolveLoadAddress(reg_addr, so_reg_addr)) {
107 strm.PutCString(" ");
108 so_reg_addr.Dump(&strm, exe_ctx.GetBestExecutionContextScope(),
109 Address::DumpStyleResolvedDescription);
121 bool DumpRegisterSet(const ExecutionContext &exe_ctx, Stream &strm,
122 RegisterContext *reg_ctx, size_t set_idx,
123 bool primitive_only = false) {
124 uint32_t unavailable_count = 0;
125 uint32_t available_count = 0;
128 return false; // thread has no registers (i.e. core files are corrupt,
129 // incomplete crash logs...)
131 const RegisterSet *const reg_set = reg_ctx->GetRegisterSet(set_idx);
133 strm.Printf("%s:\n", (reg_set->name ? reg_set->name : "unknown"));
135 const size_t num_registers = reg_set->num_registers;
136 for (size_t reg_idx = 0; reg_idx < num_registers; ++reg_idx) {
137 const uint32_t reg = reg_set->registers[reg_idx];
138 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg);
139 // Skip the dumping of derived register if primitive_only is true.
140 if (primitive_only && reg_info && reg_info->value_regs)
143 if (DumpRegister(exe_ctx, strm, reg_ctx, reg_info))
149 if (unavailable_count) {
151 strm.Printf("%u registers were unavailable.\n", unavailable_count);
155 return available_count > 0;
159 bool DoExecute(Args &command, CommandReturnObject &result) override {
160 Stream &strm = result.GetOutputStream();
161 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
163 const RegisterInfo *reg_info = nullptr;
164 if (command.GetArgumentCount() == 0) {
167 size_t num_register_sets = 1;
168 const size_t set_array_size = m_command_options.set_indexes.GetSize();
169 if (set_array_size > 0) {
170 for (size_t i = 0; i < set_array_size; ++i) {
171 set_idx = m_command_options.set_indexes[i]->GetUInt64Value(UINT32_MAX,
173 if (set_idx < reg_ctx->GetRegisterSetCount()) {
174 if (!DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx)) {
176 result.AppendErrorWithFormatv("register read failed: {0}\n",
177 llvm::sys::StrError());
179 result.AppendError("unknown error while reading registers.\n");
180 result.SetStatus(eReturnStatusFailed);
184 result.AppendErrorWithFormat(
185 "invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx);
186 result.SetStatus(eReturnStatusFailed);
191 if (m_command_options.dump_all_sets)
192 num_register_sets = reg_ctx->GetRegisterSetCount();
194 for (set_idx = 0; set_idx < num_register_sets; ++set_idx) {
195 // When dump_all_sets option is set, dump primitive as well as derived
197 DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx,
198 !m_command_options.dump_all_sets.GetCurrentValue());
202 if (m_command_options.dump_all_sets) {
203 result.AppendError("the --all option can't be used when registers "
204 "names are supplied as arguments\n");
205 result.SetStatus(eReturnStatusFailed);
206 } else if (m_command_options.set_indexes.GetSize() > 0) {
207 result.AppendError("the --set <set> option can't be used when "
208 "registers names are supplied as arguments\n");
209 result.SetStatus(eReturnStatusFailed);
211 for (auto &entry : command) {
212 // in most LLDB commands we accept $rbx as the name for register RBX -
213 // and here we would reject it and non-existant. we should be more
214 // consistent towards the user and allow them to say reg read $rbx -
215 // internally, however, we should be strict and not allow ourselves
216 // to call our registers $rbx in our own API
217 auto arg_str = entry.ref;
218 arg_str.consume_front("$");
220 reg_info = reg_ctx->GetRegisterInfoByName(arg_str);
223 if (!DumpRegister(m_exe_ctx, strm, reg_ctx, reg_info))
224 strm.Printf("%-12s = error: unavailable\n", reg_info->name);
226 result.AppendErrorWithFormat("Invalid register name '%s'.\n",
227 arg_str.str().c_str());
232 return result.Succeeded();
235 class CommandOptions : public OptionGroup {
239 set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64)),
240 dump_all_sets(false, false), // Initial and default values are false
241 alternate_name(false, false) {}
243 ~CommandOptions() override = default;
245 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
246 return llvm::makeArrayRef(g_register_read_options);
249 void OptionParsingStarting(ExecutionContext *execution_context) override {
251 dump_all_sets.Clear();
252 alternate_name.Clear();
255 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
256 ExecutionContext *execution_context) override {
258 const int short_option = GetDefinitions()[option_idx].short_option;
259 switch (short_option) {
261 OptionValueSP value_sp(OptionValueUInt64::Create(option_value, error));
263 set_indexes.AppendValue(value_sp);
267 // When we don't use OptionValue::SetValueFromCString(const char *) to
268 // set an option value, it won't be marked as being set in the options
269 // so we make a call to let users know the value was set via option
270 dump_all_sets.SetCurrentValue(true);
271 dump_all_sets.SetOptionWasSet();
275 // When we don't use OptionValue::SetValueFromCString(const char *) to
276 // set an option value, it won't be marked as being set in the options
277 // so we make a call to let users know the value was set via option
278 alternate_name.SetCurrentValue(true);
279 dump_all_sets.SetOptionWasSet();
283 error.SetErrorStringWithFormat("unrecognized short option '%c'",
290 // Instance variables to hold the values for command options.
291 OptionValueArray set_indexes;
292 OptionValueBoolean dump_all_sets;
293 OptionValueBoolean alternate_name;
296 OptionGroupOptions m_option_group;
297 OptionGroupFormat m_format_options;
298 CommandOptions m_command_options;
301 //----------------------------------------------------------------------
303 //----------------------------------------------------------------------
304 class CommandObjectRegisterWrite : public CommandObjectParsed {
306 CommandObjectRegisterWrite(CommandInterpreter &interpreter)
307 : CommandObjectParsed(interpreter, "register write",
308 "Modify a single register value.", nullptr,
309 eCommandRequiresFrame | eCommandRequiresRegContext |
310 eCommandProcessMustBeLaunched |
311 eCommandProcessMustBePaused) {
312 CommandArgumentEntry arg1;
313 CommandArgumentEntry arg2;
314 CommandArgumentData register_arg;
315 CommandArgumentData value_arg;
317 // Define the first (and only) variant of this arg.
318 register_arg.arg_type = eArgTypeRegisterName;
319 register_arg.arg_repetition = eArgRepeatPlain;
321 // There is only one variant this argument could be; put it into the
323 arg1.push_back(register_arg);
325 // Define the first (and only) variant of this arg.
326 value_arg.arg_type = eArgTypeValue;
327 value_arg.arg_repetition = eArgRepeatPlain;
329 // There is only one variant this argument could be; put it into the
331 arg2.push_back(value_arg);
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);
338 ~CommandObjectRegisterWrite() override = default;
341 bool DoExecute(Args &command, CommandReturnObject &result) override {
342 DataExtractor reg_data;
343 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
345 if (command.GetArgumentCount() != 2) {
347 "register write takes exactly 2 arguments: <reg-name> <value>");
348 result.SetStatus(eReturnStatusFailed);
350 auto reg_name = command[0].ref;
351 auto value_str = command[1].ref;
353 // in most LLDB commands we accept $rbx as the name for register RBX - and
354 // here we would reject it and non-existant. we should be more consistent
355 // towards the user and allow them to say reg write $rbx - internally,
356 // however, we should be strict and not allow ourselves to call our
357 // registers $rbx in our own API
358 reg_name.consume_front("$");
360 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
363 RegisterValue reg_value;
365 Status error(reg_value.SetValueFromString(reg_info, value_str));
366 if (error.Success()) {
367 if (reg_ctx->WriteRegister(reg_info, reg_value)) {
368 // Toss all frames and anything else in the thread
369 // after a register has been written.
370 m_exe_ctx.GetThreadRef().Flush();
371 result.SetStatus(eReturnStatusSuccessFinishNoResult);
375 if (error.AsCString()) {
376 result.AppendErrorWithFormat(
377 "Failed to write register '%s' with value '%s': %s\n",
378 reg_name.str().c_str(), value_str.str().c_str(),
381 result.AppendErrorWithFormat(
382 "Failed to write register '%s' with value '%s'",
383 reg_name.str().c_str(), value_str.str().c_str());
385 result.SetStatus(eReturnStatusFailed);
387 result.AppendErrorWithFormat("Register not found for '%s'.\n",
388 reg_name.str().c_str());
389 result.SetStatus(eReturnStatusFailed);
392 return result.Succeeded();
396 //----------------------------------------------------------------------
397 // CommandObjectRegister constructor
398 //----------------------------------------------------------------------
399 CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter)
400 : CommandObjectMultiword(interpreter, "register",
401 "Commands to access registers for the current "
402 "thread and stack frame.",
403 "register [read|write] ...") {
404 LoadSubCommand("read",
405 CommandObjectSP(new CommandObjectRegisterRead(interpreter)));
406 LoadSubCommand("write",
407 CommandObjectSP(new CommandObjectRegisterWrite(interpreter)));
410 CommandObjectRegister::~CommandObjectRegister() = default;