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
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"
31
32 using namespace lldb;
33 using namespace lldb_private;
34
35 // "register read"
36 #define LLDB_OPTIONS_register_read
37 #include "CommandOptions.inc"
38
39 class CommandObjectRegisterRead : public CommandObjectParsed {
40 public:
CommandObjectRegisterRead(CommandInterpreter & interpreter)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.",
46 nullptr,
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;
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"
68 m_option_group.Append(&m_format_options,
69 OptionGroupFormat::OPTION_GROUP_FORMAT |
70 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
71 LLDB_OPT_SET_ALL);
72 m_option_group.Append(&m_command_options);
73 m_option_group.Finalize();
74 }
75
76 ~CommandObjectRegisterRead() override = default;
77
78 void
HandleArgumentCompletion(CompletionRequest & request,OptionElementVector & opt_element_vector)79 HandleArgumentCompletion(CompletionRequest &request,
80 OptionElementVector &opt_element_vector) override {
81 if (!m_exe_ctx.HasProcessScope())
82 return;
83
84 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
85 GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr);
86 }
87
GetOptions()88 Options *GetOptions() override { return &m_option_group; }
89
DumpRegister(const ExecutionContext & exe_ctx,Stream & strm,RegisterContext & reg_ctx,const RegisterInfo & reg_info,bool print_flags)90 bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm,
91 RegisterContext ®_ctx, const RegisterInfo ®_info,
92 bool print_flags) {
93 RegisterValue reg_value;
94 if (!reg_ctx.ReadRegister(®_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;
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);
117 }
118 }
119 }
120 }
121 strm.EOL();
122 return true;
123 }
124
DumpRegisterSet(const ExecutionContext & exe_ctx,Stream & strm,RegisterContext * reg_ctx,size_t set_idx,bool primitive_only=false)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
163 protected:
DoExecute(Args & command,CommandReturnObject & result)164 void DoExecute(Args &command, CommandReturnObject &result) override {
165 Stream &strm = result.GetOutputStream();
166 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
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 {
188 result.AppendErrorWithFormat(
189 "invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx);
190 break;
191 }
192 }
193 } else {
194 if (m_command_options.dump_all_sets)
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,
201 !m_command_options.dump_all_sets.GetCurrentValue());
202 }
203 }
204 } else {
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");
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 =
226 !m_format_options.GetFormatValue().OptionWasSet();
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 }
238
239 class CommandOptions : public OptionGroup {
240 public:
CommandOptions()241 CommandOptions()
242 : set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64)),
243 dump_all_sets(false, false), // Initial and default values are false
244 alternate_name(false, false) {}
245
246 ~CommandOptions() override = default;
247
GetDefinitions()248 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
249 return llvm::ArrayRef(g_register_read_options);
250 }
251
OptionParsingStarting(ExecutionContext * execution_context)252 void OptionParsingStarting(ExecutionContext *execution_context) override {
253 set_indexes.Clear();
254 dump_all_sets.Clear();
255 alternate_name.Clear();
256 }
257
SetOptionValue(uint32_t option_idx,llvm::StringRef option_value,ExecutionContext * execution_context)258 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
259 ExecutionContext *execution_context) override {
260 Status error;
261 const int short_option = GetDefinitions()[option_idx].short_option;
262 switch (short_option) {
263 case 's': {
264 OptionValueSP value_sp(OptionValueUInt64::Create(option_value, error));
265 if (value_sp)
266 set_indexes.AppendValue(value_sp);
267 } break;
268
269 case 'a':
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();
275 break;
276
277 case 'A':
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();
283 break;
284
285 default:
286 llvm_unreachable("Unimplemented option");
287 }
288 return error;
289 }
290
291 // Instance variables to hold the values for command options.
292 OptionValueArray set_indexes;
293 OptionValueBoolean dump_all_sets;
294 OptionValueBoolean alternate_name;
295 };
296
297 OptionGroupOptions m_option_group;
298 OptionGroupFormat m_format_options;
299 CommandOptions m_command_options;
300 };
301
302 // "register write"
303 class CommandObjectRegisterWrite : public CommandObjectParsed {
304 public:
CommandObjectRegisterWrite(CommandInterpreter & interpreter)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;
315
316 // Define the first (and only) variant of this arg.
317 register_arg.arg_type = eArgTypeRegisterName;
318 register_arg.arg_repetition = eArgRepeatPlain;
319
320 // There is only one variant this argument could be; put it into the
321 // argument entry.
322 arg1.push_back(register_arg);
323
324 // Define the first (and only) variant of this arg.
325 value_arg.arg_type = eArgTypeValue;
326 value_arg.arg_repetition = eArgRepeatPlain;
327
328 // There is only one variant this argument could be; put it into the
329 // argument entry.
330 arg2.push_back(value_arg);
331
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);
335 }
336
337 ~CommandObjectRegisterWrite() override = default;
338
339 void
HandleArgumentCompletion(CompletionRequest & request,OptionElementVector & opt_element_vector)340 HandleArgumentCompletion(CompletionRequest &request,
341 OptionElementVector &opt_element_vector) override {
342 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
343 return;
344
345 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
346 GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr);
347 }
348
349 protected:
DoExecute(Args & command,CommandReturnObject & result)350 void DoExecute(Args &command, CommandReturnObject &result) override {
351 DataExtractor reg_data;
352 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
353
354 if (command.GetArgumentCount() != 2) {
355 result.AppendError(
356 "register write takes exactly 2 arguments: <reg-name> <value>");
357 } else {
358 auto reg_name = command[0].ref();
359 auto value_str = command[1].ref();
360
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("$");
367
368 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
369
370 if (reg_info) {
371 RegisterValue reg_value;
372
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
377 // has been written.
378 m_exe_ctx.GetThreadRef().Flush();
379 result.SetStatus(eReturnStatusSuccessFinishNoResult);
380 return;
381 }
382 }
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(),
387 error.AsCString());
388 } else {
389 result.AppendErrorWithFormat(
390 "Failed to write register '%s' with value '%s'",
391 reg_name.str().c_str(), value_str.str().c_str());
392 }
393 } else {
394 result.AppendErrorWithFormat("Register not found for '%s'.\n",
395 reg_name.str().c_str());
396 }
397 }
398 }
399 };
400
401 // "register info"
402 class CommandObjectRegisterInfo : public CommandObjectParsed {
403 public:
CommandObjectRegisterInfo(CommandInterpreter & interpreter)404 CommandObjectRegisterInfo(CommandInterpreter &interpreter)
405 : CommandObjectParsed(interpreter, "register info",
406 "View information about a register.", nullptr,
407 eCommandRequiresFrame | eCommandRequiresRegContext |
408 eCommandProcessMustBeLaunched |
409 eCommandProcessMustBePaused) {
410 SetHelpLong(R"(
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
422 in this register.
423
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.)");
426
427 CommandArgumentData register_arg;
428 register_arg.arg_type = eArgTypeRegisterName;
429 register_arg.arg_repetition = eArgRepeatPlain;
430
431 CommandArgumentEntry arg1;
432 arg1.push_back(register_arg);
433 m_arguments.push_back(arg1);
434 }
435
436 ~CommandObjectRegisterInfo() override = default;
437
438 void
HandleArgumentCompletion(CompletionRequest & request,OptionElementVector & opt_element_vector)439 HandleArgumentCompletion(CompletionRequest &request,
440 OptionElementVector &opt_element_vector) override {
441 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
442 return;
443 CommandCompletions::InvokeCommonCompletionCallbacks(
444 GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr);
445 }
446
447 protected:
DoExecute(Args & command,CommandReturnObject & result)448 void DoExecute(Args &command, CommandReturnObject &result) override {
449 if (command.GetArgumentCount() != 1) {
450 result.AppendError("register info takes exactly 1 argument: <reg-name>");
451 return;
452 }
453
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);
457 if (reg_info) {
458 DumpRegisterInfo(
459 result.GetOutputStream(), *reg_ctx, *reg_info,
460 GetCommandInterpreter().GetDebugger().GetTerminalWidth());
461 result.SetStatus(eReturnStatusSuccessFinishResult);
462 } else
463 result.AppendErrorWithFormat("No register found with name '%s'.\n",
464 reg_name.str().c_str());
465 }
466 };
467
468 // CommandObjectRegister constructor
CommandObjectRegister(CommandInterpreter & interpreter)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)));
480 }
481
482 CommandObjectRegister::~CommandObjectRegister() = default;
483