xref: /llvm-project/lldb/source/Commands/CommandObjectRegister.cpp (revision fdbe7c7faa547b16bf6da0fedbb7234b6ee3adef)
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     CommandCompletions::InvokeCommonCompletionCallbacks(
83         GetCommandInterpreter(), CommandCompletions::eRegisterCompletion,
84         request, nullptr);
85   }
86 
87   Options *GetOptions() override { return &m_option_group; }
88 
89   bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm,
90                     RegisterContext &reg_ctx, const RegisterInfo &reg_info,
91                     bool print_flags) {
92     RegisterValue reg_value;
93     if (!reg_ctx.ReadRegister(&reg_info, reg_value))
94       return false;
95 
96     strm.Indent();
97 
98     bool prefix_with_altname = (bool)m_command_options.alternate_name;
99     bool prefix_with_name = !prefix_with_altname;
100     DumpRegisterValue(reg_value, strm, reg_info, prefix_with_name,
101                       prefix_with_altname, m_format_options.GetFormat(), 8,
102                       exe_ctx.GetBestExecutionContextScope(), print_flags,
103                       exe_ctx.GetTargetSP());
104     if ((reg_info.encoding == eEncodingUint) ||
105         (reg_info.encoding == eEncodingSint)) {
106       Process *process = exe_ctx.GetProcessPtr();
107       if (process && reg_info.byte_size == process->GetAddressByteSize()) {
108         addr_t reg_addr = reg_value.GetAsUInt64(LLDB_INVALID_ADDRESS);
109         if (reg_addr != LLDB_INVALID_ADDRESS) {
110           Address so_reg_addr;
111           if (exe_ctx.GetTargetRef().GetSectionLoadList().ResolveLoadAddress(
112                   reg_addr, so_reg_addr)) {
113             strm.PutCString("  ");
114             so_reg_addr.Dump(&strm, exe_ctx.GetBestExecutionContextScope(),
115                              Address::DumpStyleResolvedDescription);
116           }
117         }
118       }
119     }
120     strm.EOL();
121     return true;
122   }
123 
124   bool DumpRegisterSet(const ExecutionContext &exe_ctx, Stream &strm,
125                        RegisterContext *reg_ctx, size_t set_idx,
126                        bool primitive_only = false) {
127     uint32_t unavailable_count = 0;
128     uint32_t available_count = 0;
129 
130     if (!reg_ctx)
131       return false; // thread has no registers (i.e. core files are corrupt,
132                     // incomplete crash logs...)
133 
134     const RegisterSet *const reg_set = reg_ctx->GetRegisterSet(set_idx);
135     if (reg_set) {
136       strm.Printf("%s:\n", (reg_set->name ? reg_set->name : "unknown"));
137       strm.IndentMore();
138       const size_t num_registers = reg_set->num_registers;
139       for (size_t reg_idx = 0; reg_idx < num_registers; ++reg_idx) {
140         const uint32_t reg = reg_set->registers[reg_idx];
141         const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg);
142         // Skip the dumping of derived register if primitive_only is true.
143         if (primitive_only && reg_info && reg_info->value_regs)
144           continue;
145 
146         if (reg_info && DumpRegister(exe_ctx, strm, *reg_ctx, *reg_info,
147                                      /*print_flags=*/false))
148           ++available_count;
149         else
150           ++unavailable_count;
151       }
152       strm.IndentLess();
153       if (unavailable_count) {
154         strm.Indent();
155         strm.Printf("%u registers were unavailable.\n", unavailable_count);
156       }
157       strm.EOL();
158     }
159     return available_count > 0;
160   }
161 
162 protected:
163   bool DoExecute(Args &command, CommandReturnObject &result) override {
164     Stream &strm = result.GetOutputStream();
165     RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
166 
167     if (command.GetArgumentCount() == 0) {
168       size_t set_idx;
169 
170       size_t num_register_sets = 1;
171       const size_t set_array_size = m_command_options.set_indexes.GetSize();
172       if (set_array_size > 0) {
173         for (size_t i = 0; i < set_array_size; ++i) {
174           set_idx = m_command_options.set_indexes[i]->GetUInt64Value().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     CommandCompletions::InvokeCommonCompletionCallbacks(
345         GetCommandInterpreter(), CommandCompletions::eRegisterCompletion,
346         request, nullptr);
347   }
348 
349 protected:
350   bool 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 true;
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     return result.Succeeded();
399   }
400 };
401 
402 // CommandObjectRegister constructor
403 CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter)
404     : CommandObjectMultiword(interpreter, "register",
405                              "Commands to access registers for the current "
406                              "thread and stack frame.",
407                              "register [read|write] ...") {
408   LoadSubCommand("read",
409                  CommandObjectSP(new CommandObjectRegisterRead(interpreter)));
410   LoadSubCommand("write",
411                  CommandObjectSP(new CommandObjectRegisterWrite(interpreter)));
412 }
413 
414 CommandObjectRegister::~CommandObjectRegister() = default;
415