xref: /llvm-project/lldb/source/Commands/CommandObjectRegister.cpp (revision 6a9c3e611505b7637b46fbaacaf50362c97a263d)
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/DumpRegisterValue.h"
12 #include "lldb/Host/OptionParser.h"
13 #include "lldb/Interpreter/CommandOptionArgumentTable.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 "llvm/Support/Errno.h"
29 
30 using namespace lldb;
31 using namespace lldb_private;
32 
33 // "register read"
34 #define LLDB_OPTIONS_register_read
35 #include "CommandOptions.inc"
36 
37 class CommandObjectRegisterRead : public CommandObjectParsed {
38 public:
39   CommandObjectRegisterRead(CommandInterpreter &interpreter)
40       : CommandObjectParsed(
41             interpreter, "register read",
42             "Dump the contents of one or more register values from the current "
43             "frame.  If no register is specified, dumps them all.",
44             nullptr,
45             eCommandRequiresFrame | eCommandRequiresRegContext |
46                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
47         m_format_options(eFormatDefault, UINT64_MAX, UINT64_MAX,
48                          {{CommandArgumentType::eArgTypeFormat,
49                            "Specify a format to be used for display. If this "
50                            "is set, register fields will not be displayed."}}) {
51     CommandArgumentEntry arg;
52     CommandArgumentData register_arg;
53 
54     // Define the first (and only) variant of this arg.
55     register_arg.arg_type = eArgTypeRegisterName;
56     register_arg.arg_repetition = eArgRepeatStar;
57 
58     // There is only one variant this argument could be; put it into the
59     // argument entry.
60     arg.push_back(register_arg);
61 
62     // Push the data for the first argument into the m_arguments vector.
63     m_arguments.push_back(arg);
64 
65     // Add the "--format"
66     m_option_group.Append(&m_format_options,
67                           OptionGroupFormat::OPTION_GROUP_FORMAT |
68                               OptionGroupFormat::OPTION_GROUP_GDB_FMT,
69                           LLDB_OPT_SET_ALL);
70     m_option_group.Append(&m_command_options);
71     m_option_group.Finalize();
72   }
73 
74   ~CommandObjectRegisterRead() override = default;
75 
76   void
77   HandleArgumentCompletion(CompletionRequest &request,
78                            OptionElementVector &opt_element_vector) override {
79     if (!m_exe_ctx.HasProcessScope())
80       return;
81 
82     lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
83         GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr);
84   }
85 
86   Options *GetOptions() override { return &m_option_group; }
87 
88   bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm,
89                     RegisterContext &reg_ctx, const RegisterInfo &reg_info,
90                     bool print_flags) {
91     RegisterValue reg_value;
92     if (!reg_ctx.ReadRegister(&reg_info, reg_value))
93       return false;
94 
95     strm.Indent();
96 
97     bool prefix_with_altname = (bool)m_command_options.alternate_name;
98     bool prefix_with_name = !prefix_with_altname;
99     DumpRegisterValue(reg_value, strm, reg_info, prefix_with_name,
100                       prefix_with_altname, m_format_options.GetFormat(), 8,
101                       exe_ctx.GetBestExecutionContextScope(), print_flags,
102                       exe_ctx.GetTargetSP());
103     if ((reg_info.encoding == eEncodingUint) ||
104         (reg_info.encoding == eEncodingSint)) {
105       Process *process = exe_ctx.GetProcessPtr();
106       if (process && reg_info.byte_size == process->GetAddressByteSize()) {
107         addr_t reg_addr = reg_value.GetAsUInt64(LLDB_INVALID_ADDRESS);
108         if (reg_addr != LLDB_INVALID_ADDRESS) {
109           Address so_reg_addr;
110           if (exe_ctx.GetTargetRef().GetSectionLoadList().ResolveLoadAddress(
111                   reg_addr, so_reg_addr)) {
112             strm.PutCString("  ");
113             so_reg_addr.Dump(&strm, exe_ctx.GetBestExecutionContextScope(),
114                              Address::DumpStyleResolvedDescription);
115           }
116         }
117       }
118     }
119     strm.EOL();
120     return true;
121   }
122 
123   bool DumpRegisterSet(const ExecutionContext &exe_ctx, Stream &strm,
124                        RegisterContext *reg_ctx, size_t set_idx,
125                        bool primitive_only = false) {
126     uint32_t unavailable_count = 0;
127     uint32_t available_count = 0;
128 
129     if (!reg_ctx)
130       return false; // thread has no registers (i.e. core files are corrupt,
131                     // incomplete crash logs...)
132 
133     const RegisterSet *const reg_set = reg_ctx->GetRegisterSet(set_idx);
134     if (reg_set) {
135       strm.Printf("%s:\n", (reg_set->name ? reg_set->name : "unknown"));
136       strm.IndentMore();
137       const size_t num_registers = reg_set->num_registers;
138       for (size_t reg_idx = 0; reg_idx < num_registers; ++reg_idx) {
139         const uint32_t reg = reg_set->registers[reg_idx];
140         const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg);
141         // Skip the dumping of derived register if primitive_only is true.
142         if (primitive_only && reg_info && reg_info->value_regs)
143           continue;
144 
145         if (reg_info && DumpRegister(exe_ctx, strm, *reg_ctx, *reg_info,
146                                      /*print_flags=*/false))
147           ++available_count;
148         else
149           ++unavailable_count;
150       }
151       strm.IndentLess();
152       if (unavailable_count) {
153         strm.Indent();
154         strm.Printf("%u registers were unavailable.\n", unavailable_count);
155       }
156       strm.EOL();
157     }
158     return available_count > 0;
159   }
160 
161 protected:
162   bool DoExecute(Args &command, CommandReturnObject &result) override {
163     Stream &strm = result.GetOutputStream();
164     RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
165 
166     if (command.GetArgumentCount() == 0) {
167       size_t set_idx;
168 
169       size_t num_register_sets = 1;
170       const size_t set_array_size = m_command_options.set_indexes.GetSize();
171       if (set_array_size > 0) {
172         for (size_t i = 0; i < set_array_size; ++i) {
173           set_idx =
174               m_command_options.set_indexes[i]->GetValueAs<uint64_t>().value_or(
175                   UINT32_MAX);
176           if (set_idx < reg_ctx->GetRegisterSetCount()) {
177             if (!DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx)) {
178               if (errno)
179                 result.AppendErrorWithFormatv("register read failed: {0}\n",
180                                               llvm::sys::StrError());
181               else
182                 result.AppendError("unknown error while reading registers.\n");
183               break;
184             }
185           } else {
186             result.AppendErrorWithFormat(
187                 "invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx);
188             break;
189           }
190         }
191       } else {
192         if (m_command_options.dump_all_sets)
193           num_register_sets = reg_ctx->GetRegisterSetCount();
194 
195         for (set_idx = 0; set_idx < num_register_sets; ++set_idx) {
196           // When dump_all_sets option is set, dump primitive as well as
197           // derived registers.
198           DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx,
199                           !m_command_options.dump_all_sets.GetCurrentValue());
200         }
201       }
202     } else {
203       if (m_command_options.dump_all_sets) {
204         result.AppendError("the --all option can't be used when registers "
205                            "names are supplied as arguments\n");
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       } else {
210         for (auto &entry : command) {
211           // in most LLDB commands we accept $rbx as the name for register RBX
212           // - and here we would reject it and non-existant. we should be more
213           // consistent towards the user and allow them to say reg read $rbx -
214           // internally, however, we should be strict and not allow ourselves
215           // to call our registers $rbx in our own API
216           auto arg_str = entry.ref();
217           arg_str.consume_front("$");
218 
219           if (const RegisterInfo *reg_info =
220                   reg_ctx->GetRegisterInfoByName(arg_str)) {
221             // If they have asked for a specific format don't obscure that by
222             // printing flags afterwards.
223             bool print_flags =
224                 !m_format_options.GetFormatValue().OptionWasSet();
225             if (!DumpRegister(m_exe_ctx, strm, *reg_ctx, *reg_info,
226                               print_flags))
227               strm.Printf("%-12s = error: unavailable\n", reg_info->name);
228           } else {
229             result.AppendErrorWithFormat("Invalid register name '%s'.\n",
230                                          arg_str.str().c_str());
231           }
232         }
233       }
234     }
235     return result.Succeeded();
236   }
237 
238   class CommandOptions : public OptionGroup {
239   public:
240     CommandOptions()
241         : set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64)),
242           dump_all_sets(false, false), // Initial and default values are false
243           alternate_name(false, false) {}
244 
245     ~CommandOptions() override = default;
246 
247     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
248       return llvm::ArrayRef(g_register_read_options);
249     }
250 
251     void OptionParsingStarting(ExecutionContext *execution_context) override {
252       set_indexes.Clear();
253       dump_all_sets.Clear();
254       alternate_name.Clear();
255     }
256 
257     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
258                           ExecutionContext *execution_context) override {
259       Status error;
260       const int short_option = GetDefinitions()[option_idx].short_option;
261       switch (short_option) {
262       case 's': {
263         OptionValueSP value_sp(OptionValueUInt64::Create(option_value, error));
264         if (value_sp)
265           set_indexes.AppendValue(value_sp);
266       } break;
267 
268       case 'a':
269         // When we don't use OptionValue::SetValueFromCString(const char *) to
270         // set an option value, it won't be marked as being set in the options
271         // so we make a call to let users know the value was set via option
272         dump_all_sets.SetCurrentValue(true);
273         dump_all_sets.SetOptionWasSet();
274         break;
275 
276       case 'A':
277         // When we don't use OptionValue::SetValueFromCString(const char *) to
278         // set an option value, it won't be marked as being set in the options
279         // so we make a call to let users know the value was set via option
280         alternate_name.SetCurrentValue(true);
281         dump_all_sets.SetOptionWasSet();
282         break;
283 
284       default:
285         llvm_unreachable("Unimplemented option");
286       }
287       return error;
288     }
289 
290     // Instance variables to hold the values for command options.
291     OptionValueArray set_indexes;
292     OptionValueBoolean dump_all_sets;
293     OptionValueBoolean alternate_name;
294   };
295 
296   OptionGroupOptions m_option_group;
297   OptionGroupFormat m_format_options;
298   CommandOptions m_command_options;
299 };
300 
301 // "register write"
302 class CommandObjectRegisterWrite : public CommandObjectParsed {
303 public:
304   CommandObjectRegisterWrite(CommandInterpreter &interpreter)
305       : CommandObjectParsed(interpreter, "register write",
306                             "Modify a single register value.", nullptr,
307                             eCommandRequiresFrame | eCommandRequiresRegContext |
308                                 eCommandProcessMustBeLaunched |
309                                 eCommandProcessMustBePaused) {
310     CommandArgumentEntry arg1;
311     CommandArgumentEntry arg2;
312     CommandArgumentData register_arg;
313     CommandArgumentData value_arg;
314 
315     // Define the first (and only) variant of this arg.
316     register_arg.arg_type = eArgTypeRegisterName;
317     register_arg.arg_repetition = eArgRepeatPlain;
318 
319     // There is only one variant this argument could be; put it into the
320     // argument entry.
321     arg1.push_back(register_arg);
322 
323     // Define the first (and only) variant of this arg.
324     value_arg.arg_type = eArgTypeValue;
325     value_arg.arg_repetition = eArgRepeatPlain;
326 
327     // There is only one variant this argument could be; put it into the
328     // argument entry.
329     arg2.push_back(value_arg);
330 
331     // Push the data for the first argument into the m_arguments vector.
332     m_arguments.push_back(arg1);
333     m_arguments.push_back(arg2);
334   }
335 
336   ~CommandObjectRegisterWrite() override = default;
337 
338   void
339   HandleArgumentCompletion(CompletionRequest &request,
340                            OptionElementVector &opt_element_vector) override {
341     if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
342       return;
343 
344     lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
345         GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr);
346   }
347 
348 protected:
349   bool DoExecute(Args &command, CommandReturnObject &result) override {
350     DataExtractor reg_data;
351     RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
352 
353     if (command.GetArgumentCount() != 2) {
354       result.AppendError(
355           "register write takes exactly 2 arguments: <reg-name> <value>");
356     } else {
357       auto reg_name = command[0].ref();
358       auto value_str = command[1].ref();
359 
360       // in most LLDB commands we accept $rbx as the name for register RBX -
361       // and here we would reject it and non-existant. we should be more
362       // consistent towards the user and allow them to say reg write $rbx -
363       // internally, however, we should be strict and not allow ourselves to
364       // call our registers $rbx in our own API
365       reg_name.consume_front("$");
366 
367       const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
368 
369       if (reg_info) {
370         RegisterValue reg_value;
371 
372         Status error(reg_value.SetValueFromString(reg_info, value_str));
373         if (error.Success()) {
374           if (reg_ctx->WriteRegister(reg_info, reg_value)) {
375             // Toss all frames and anything else in the thread after a register
376             // has been written.
377             m_exe_ctx.GetThreadRef().Flush();
378             result.SetStatus(eReturnStatusSuccessFinishNoResult);
379             return true;
380           }
381         }
382         if (error.AsCString()) {
383           result.AppendErrorWithFormat(
384               "Failed to write register '%s' with value '%s': %s\n",
385               reg_name.str().c_str(), value_str.str().c_str(),
386               error.AsCString());
387         } else {
388           result.AppendErrorWithFormat(
389               "Failed to write register '%s' with value '%s'",
390               reg_name.str().c_str(), value_str.str().c_str());
391         }
392       } else {
393         result.AppendErrorWithFormat("Register not found for '%s'.\n",
394                                      reg_name.str().c_str());
395       }
396     }
397     return result.Succeeded();
398   }
399 };
400 
401 // CommandObjectRegister constructor
402 CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter)
403     : CommandObjectMultiword(interpreter, "register",
404                              "Commands to access registers for the current "
405                              "thread and stack frame.",
406                              "register [read|write] ...") {
407   LoadSubCommand("read",
408                  CommandObjectSP(new CommandObjectRegisterRead(interpreter)));
409   LoadSubCommand("write",
410                  CommandObjectSP(new CommandObjectRegisterWrite(interpreter)));
411 }
412 
413 CommandObjectRegister::~CommandObjectRegister() = default;
414