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/CommandOptionArgumentTable.h" 15 #include "lldb/Interpreter/CommandReturnObject.h" 16 #include "lldb/Interpreter/OptionGroupFormat.h" 17 #include "lldb/Interpreter/OptionValueArray.h" 18 #include "lldb/Interpreter/OptionValueBoolean.h" 19 #include "lldb/Interpreter/OptionValueUInt64.h" 20 #include "lldb/Interpreter/Options.h" 21 #include "lldb/Target/ExecutionContext.h" 22 #include "lldb/Target/Process.h" 23 #include "lldb/Target/RegisterContext.h" 24 #include "lldb/Target/SectionLoadList.h" 25 #include "lldb/Target/Thread.h" 26 #include "lldb/Utility/Args.h" 27 #include "lldb/Utility/DataExtractor.h" 28 #include "lldb/Utility/RegisterValue.h" 29 #include "llvm/Support/Errno.h" 30 31 using namespace lldb; 32 using namespace lldb_private; 33 34 // "register read" 35 #define LLDB_OPTIONS_register_read 36 #include "CommandOptions.inc" 37 38 class CommandObjectRegisterRead : public CommandObjectParsed { 39 public: 40 CommandObjectRegisterRead(CommandInterpreter &interpreter) 41 : CommandObjectParsed( 42 interpreter, "register read", 43 "Dump the contents of one or more register values from the current " 44 "frame. If no register is specified, dumps them all.", 45 nullptr, 46 eCommandRequiresFrame | eCommandRequiresRegContext | 47 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), 48 m_format_options(eFormatDefault, UINT64_MAX, UINT64_MAX, 49 {{CommandArgumentType::eArgTypeFormat, 50 "Specify a format to be used for display. If this " 51 "is set, register fields will not be displayed."}}) { 52 CommandArgumentEntry arg; 53 CommandArgumentData register_arg; 54 55 // Define the first (and only) variant of this arg. 56 register_arg.arg_type = eArgTypeRegisterName; 57 register_arg.arg_repetition = eArgRepeatStar; 58 59 // There is only one variant this argument could be; put it into the 60 // argument entry. 61 arg.push_back(register_arg); 62 63 // Push the data for the first argument into the m_arguments vector. 64 m_arguments.push_back(arg); 65 66 // Add the "--format" 67 m_option_group.Append(&m_format_options, 68 OptionGroupFormat::OPTION_GROUP_FORMAT | 69 OptionGroupFormat::OPTION_GROUP_GDB_FMT, 70 LLDB_OPT_SET_ALL); 71 m_option_group.Append(&m_command_options); 72 m_option_group.Finalize(); 73 } 74 75 ~CommandObjectRegisterRead() override = default; 76 77 void 78 HandleArgumentCompletion(CompletionRequest &request, 79 OptionElementVector &opt_element_vector) override { 80 if (!m_exe_ctx.HasProcessScope()) 81 return; 82 83 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks( 84 GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr); 85 } 86 87 Options *GetOptions() override { return &m_option_group; } 88 89 bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm, 90 RegisterContext ®_ctx, const RegisterInfo ®_info, 91 bool print_flags) { 92 RegisterValue reg_value; 93 if (!reg_ctx.ReadRegister(®_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 = 175 m_command_options.set_indexes[i]->GetValueAs<uint64_t>().value_or( 176 UINT32_MAX); 177 if (set_idx < reg_ctx->GetRegisterSetCount()) { 178 if (!DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx)) { 179 if (errno) 180 result.AppendErrorWithFormatv("register read failed: {0}\n", 181 llvm::sys::StrError()); 182 else 183 result.AppendError("unknown error while reading registers.\n"); 184 break; 185 } 186 } else { 187 result.AppendErrorWithFormat( 188 "invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx); 189 break; 190 } 191 } 192 } else { 193 if (m_command_options.dump_all_sets) 194 num_register_sets = reg_ctx->GetRegisterSetCount(); 195 196 for (set_idx = 0; set_idx < num_register_sets; ++set_idx) { 197 // When dump_all_sets option is set, dump primitive as well as 198 // derived registers. 199 DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx, 200 !m_command_options.dump_all_sets.GetCurrentValue()); 201 } 202 } 203 } else { 204 if (m_command_options.dump_all_sets) { 205 result.AppendError("the --all option can't be used when registers " 206 "names are supplied as arguments\n"); 207 } else if (m_command_options.set_indexes.GetSize() > 0) { 208 result.AppendError("the --set <set> option can't be used when " 209 "registers names are supplied as arguments\n"); 210 } else { 211 for (auto &entry : command) { 212 // in most LLDB commands we accept $rbx as the name for register RBX 213 // - and here we would reject it and non-existant. we should be more 214 // consistent towards the user and allow them to say reg read $rbx - 215 // internally, however, we should be strict and not allow ourselves 216 // to call our registers $rbx in our own API 217 auto arg_str = entry.ref(); 218 arg_str.consume_front("$"); 219 220 if (const RegisterInfo *reg_info = 221 reg_ctx->GetRegisterInfoByName(arg_str)) { 222 // If they have asked for a specific format don't obscure that by 223 // printing flags afterwards. 224 bool print_flags = 225 !m_format_options.GetFormatValue().OptionWasSet(); 226 if (!DumpRegister(m_exe_ctx, strm, *reg_ctx, *reg_info, 227 print_flags)) 228 strm.Printf("%-12s = error: unavailable\n", reg_info->name); 229 } else { 230 result.AppendErrorWithFormat("Invalid register name '%s'.\n", 231 arg_str.str().c_str()); 232 } 233 } 234 } 235 } 236 return result.Succeeded(); 237 } 238 239 class CommandOptions : public OptionGroup { 240 public: 241 CommandOptions() 242 : set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64)), 243 dump_all_sets(false, false), // Initial and default values are false 244 alternate_name(false, false) {} 245 246 ~CommandOptions() override = default; 247 248 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 249 return llvm::ArrayRef(g_register_read_options); 250 } 251 252 void OptionParsingStarting(ExecutionContext *execution_context) override { 253 set_indexes.Clear(); 254 dump_all_sets.Clear(); 255 alternate_name.Clear(); 256 } 257 258 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, 259 ExecutionContext *execution_context) override { 260 Status error; 261 const int short_option = GetDefinitions()[option_idx].short_option; 262 switch (short_option) { 263 case 's': { 264 OptionValueSP value_sp(OptionValueUInt64::Create(option_value, error)); 265 if (value_sp) 266 set_indexes.AppendValue(value_sp); 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 dump_all_sets.SetCurrentValue(true); 274 dump_all_sets.SetOptionWasSet(); 275 break; 276 277 case 'A': 278 // When we don't use OptionValue::SetValueFromCString(const char *) to 279 // set an option value, it won't be marked as being set in the options 280 // so we make a call to let users know the value was set via option 281 alternate_name.SetCurrentValue(true); 282 dump_all_sets.SetOptionWasSet(); 283 break; 284 285 default: 286 llvm_unreachable("Unimplemented option"); 287 } 288 return error; 289 } 290 291 // Instance variables to hold the values for command options. 292 OptionValueArray set_indexes; 293 OptionValueBoolean dump_all_sets; 294 OptionValueBoolean alternate_name; 295 }; 296 297 OptionGroupOptions m_option_group; 298 OptionGroupFormat m_format_options; 299 CommandOptions m_command_options; 300 }; 301 302 // "register write" 303 class CommandObjectRegisterWrite : public CommandObjectParsed { 304 public: 305 CommandObjectRegisterWrite(CommandInterpreter &interpreter) 306 : CommandObjectParsed(interpreter, "register write", 307 "Modify a single register value.", nullptr, 308 eCommandRequiresFrame | eCommandRequiresRegContext | 309 eCommandProcessMustBeLaunched | 310 eCommandProcessMustBePaused) { 311 CommandArgumentEntry arg1; 312 CommandArgumentEntry arg2; 313 CommandArgumentData register_arg; 314 CommandArgumentData value_arg; 315 316 // Define the first (and only) variant of this arg. 317 register_arg.arg_type = eArgTypeRegisterName; 318 register_arg.arg_repetition = eArgRepeatPlain; 319 320 // There is only one variant this argument could be; put it into the 321 // argument entry. 322 arg1.push_back(register_arg); 323 324 // Define the first (and only) variant of this arg. 325 value_arg.arg_type = eArgTypeValue; 326 value_arg.arg_repetition = eArgRepeatPlain; 327 328 // There is only one variant this argument could be; put it into the 329 // argument entry. 330 arg2.push_back(value_arg); 331 332 // Push the data for the first argument into the m_arguments vector. 333 m_arguments.push_back(arg1); 334 m_arguments.push_back(arg2); 335 } 336 337 ~CommandObjectRegisterWrite() override = default; 338 339 void 340 HandleArgumentCompletion(CompletionRequest &request, 341 OptionElementVector &opt_element_vector) override { 342 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0) 343 return; 344 345 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks( 346 GetCommandInterpreter(), lldb::eRegisterCompletion, 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 // "register info" 403 class CommandObjectRegisterInfo : public CommandObjectParsed { 404 public: 405 CommandObjectRegisterInfo(CommandInterpreter &interpreter) 406 : CommandObjectParsed(interpreter, "register info", 407 "View information about a register.", nullptr, 408 eCommandRequiresRegContext | 409 eCommandProcessMustBeLaunched) { 410 SetHelpLong(R"( 411 Name The name lldb uses for the register, optionally with an alias. 412 Size The size of the register in bytes and again in bits. 413 Invalidates (*) The registers that would be changed if you wrote this 414 register. For example, writing to a narrower alias of a wider 415 register would change the value of the wider register. 416 Read from (*) The registers that the value of this register is constructed 417 from. For example, a narrower alias of a wider register will be 418 read from the wider register. 419 In sets (*) The register sets that contain this register. For example the 420 PC will be in the "General Purpose Register" set. 421 422 Fields marked with (*) may not always be present. Some information may be 423 different for the same register when connected to different debug servers.)"); 424 425 CommandArgumentData register_arg; 426 register_arg.arg_type = eArgTypeRegisterName; 427 register_arg.arg_repetition = eArgRepeatPlain; 428 429 CommandArgumentEntry arg1; 430 arg1.push_back(register_arg); 431 m_arguments.push_back(arg1); 432 } 433 434 ~CommandObjectRegisterInfo() override = default; 435 436 void 437 HandleArgumentCompletion(CompletionRequest &request, 438 OptionElementVector &opt_element_vector) override { 439 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0) 440 return; 441 CommandCompletions::InvokeCommonCompletionCallbacks( 442 GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr); 443 } 444 445 protected: 446 bool DoExecute(Args &command, CommandReturnObject &result) override { 447 if (command.GetArgumentCount() != 1) { 448 result.AppendError("register info takes exactly 1 argument: <reg-name>"); 449 return result.Succeeded(); 450 } 451 452 llvm::StringRef reg_name = command[0].ref(); 453 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext(); 454 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name); 455 if (reg_info) { 456 DumpRegisterInfo(result.GetOutputStream(), *reg_ctx, *reg_info); 457 result.SetStatus(eReturnStatusSuccessFinishResult); 458 } else 459 result.AppendErrorWithFormat("No register found with name '%s'.\n", 460 reg_name.str().c_str()); 461 462 return result.Succeeded(); 463 } 464 }; 465 466 // CommandObjectRegister constructor 467 CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter) 468 : CommandObjectMultiword(interpreter, "register", 469 "Commands to access registers for the current " 470 "thread and stack frame.", 471 "register [read|write|info] ...") { 472 LoadSubCommand("read", 473 CommandObjectSP(new CommandObjectRegisterRead(interpreter))); 474 LoadSubCommand("write", 475 CommandObjectSP(new CommandObjectRegisterWrite(interpreter))); 476 LoadSubCommand("info", 477 CommandObjectSP(new CommandObjectRegisterInfo(interpreter))); 478 } 479 480 CommandObjectRegister::~CommandObjectRegister() = default; 481