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:
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
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 
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;
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 
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:
164   bool 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     return result.Succeeded();
238   }
239 
240   class CommandOptions : public OptionGroup {
241   public:
242     CommandOptions()
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 {
254       set_indexes.Clear();
255       dump_all_sets.Clear();
256       alternate_name.Clear();
257     }
258 
259     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
260                           ExecutionContext *execution_context) override {
261       Status error;
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
274         dump_all_sets.SetCurrentValue(true);
275         dump_all_sets.SetOptionWasSet();
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
282         alternate_name.SetCurrentValue(true);
283         dump_all_sets.SetOptionWasSet();
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.
293     OptionValueArray set_indexes;
294     OptionValueBoolean dump_all_sets;
295     OptionValueBoolean alternate_name;
296   };
297 
298   OptionGroupOptions m_option_group;
299   OptionGroupFormat m_format_options;
300   CommandOptions m_command_options;
301 };
302 
303 // "register write"
304 class CommandObjectRegisterWrite : public CommandObjectParsed {
305 public:
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;
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;
327     value_arg.arg_repetition = eArgRepeatPlain;
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
341   HandleArgumentCompletion(CompletionRequest &request,
342                            OptionElementVector &opt_element_vector) override {
343     if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
344       return;
345 
346     lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
347         GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr);
348   }
349 
350 protected:
351   bool DoExecute(Args &command, CommandReturnObject &result) override {
352     DataExtractor reg_data;
353     RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
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.
379             m_exe_ctx.GetThreadRef().Flush();
380             result.SetStatus(eReturnStatusSuccessFinishNoResult);
381             return true;
382           }
383         }
384         if (error.AsCString()) {
385           result.AppendErrorWithFormat(
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 {
390           result.AppendErrorWithFormat(
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"
404 class CommandObjectRegisterInfo : public CommandObjectParsed {
405 public:
406   CommandObjectRegisterInfo(CommandInterpreter &interpreter)
407       : CommandObjectParsed(interpreter, "register info",
408                             "View information about a register.", nullptr,
409                             eCommandRequiresRegContext |
410                                 eCommandProcessMustBeLaunched) {
411     SetHelpLong(R"(
412 Name             The name lldb uses for the register, optionally with an alias.
413 Size             The size of the register in bytes and again in bits.
414 Invalidates (*)  The registers that would be changed if you wrote this
415                  register. For example, writing to a narrower alias of a wider
416                  register would change the value of the wider register.
417 Read from   (*)  The registers that the value of this register is constructed
418                  from. For example, a narrower alias of a wider register will be
419                  read from the wider register.
420 In sets     (*)  The register sets that contain this register. For example the
421                  PC will be in the "General Purpose Register" set.
422 Fields      (*)  A table of the names and bit positions of the values contained
423                  in this register.
424 
425 Fields marked with (*) may not always be present. Some information may be
426 different for the same register when connected to different debug servers.)");
427 
428     CommandArgumentData register_arg;
429     register_arg.arg_type = eArgTypeRegisterName;
430     register_arg.arg_repetition = eArgRepeatPlain;
431 
432     CommandArgumentEntry arg1;
433     arg1.push_back(register_arg);
434     m_arguments.push_back(arg1);
435   }
436 
437   ~CommandObjectRegisterInfo() override = default;
438 
439   void
440   HandleArgumentCompletion(CompletionRequest &request,
441                            OptionElementVector &opt_element_vector) override {
442     if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
443       return;
444     CommandCompletions::InvokeCommonCompletionCallbacks(
445         GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr);
446   }
447 
448 protected:
449   bool DoExecute(Args &command, CommandReturnObject &result) override {
450     if (command.GetArgumentCount() != 1) {
451       result.AppendError("register info takes exactly 1 argument: <reg-name>");
452       return result.Succeeded();
453     }
454 
455     llvm::StringRef reg_name = command[0].ref();
456     RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
457     const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
458     if (reg_info) {
459       DumpRegisterInfo(
460           result.GetOutputStream(), *reg_ctx, *reg_info,
461           GetCommandInterpreter().GetDebugger().GetTerminalWidth());
462       result.SetStatus(eReturnStatusSuccessFinishResult);
463     } else
464       result.AppendErrorWithFormat("No register found with name '%s'.\n",
465                                    reg_name.str().c_str());
466 
467     return result.Succeeded();
468   }
469 };
470 
471 // CommandObjectRegister constructor
472 CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter)
473     : CommandObjectMultiword(interpreter, "register",
474                              "Commands to access registers for the current "
475                              "thread and stack frame.",
476                              "register [read|write|info] ...") {
477   LoadSubCommand("read",
478                  CommandObjectSP(new CommandObjectRegisterRead(interpreter)));
479   LoadSubCommand("write",
480                  CommandObjectSP(new CommandObjectRegisterWrite(interpreter)));
481   LoadSubCommand("info",
482                  CommandObjectSP(new CommandObjectRegisterInfo(interpreter)));
483 }
484 
485 CommandObjectRegister::~CommandObjectRegister() = default;
486