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