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