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/CommandInterpreter.h" 15 #include "lldb/Interpreter/CommandOptionArgumentTable.h" 16 #include "lldb/Interpreter/CommandReturnObject.h" 17 #include "lldb/Interpreter/OptionGroupFormat.h" 18 #include "lldb/Interpreter/OptionValueArray.h" 19 #include "lldb/Interpreter/OptionValueBoolean.h" 20 #include "lldb/Interpreter/OptionValueUInt64.h" 21 #include "lldb/Interpreter/Options.h" 22 #include "lldb/Target/ExecutionContext.h" 23 #include "lldb/Target/Process.h" 24 #include "lldb/Target/RegisterContext.h" 25 #include "lldb/Target/SectionLoadList.h" 26 #include "lldb/Target/Thread.h" 27 #include "lldb/Utility/Args.h" 28 #include "lldb/Utility/DataExtractor.h" 29 #include "lldb/Utility/RegisterValue.h" 30 #include "llvm/Support/Errno.h" 31 32 using namespace lldb; 33 using namespace lldb_private; 34 35 // "register read" 36 #define LLDB_OPTIONS_register_read 37 #include "CommandOptions.inc" 38 39 class CommandObjectRegisterRead : public CommandObjectParsed { 40 public: 41 CommandObjectRegisterRead(CommandInterpreter &interpreter) 42 : CommandObjectParsed( 43 interpreter, "register read", 44 "Dump the contents of one or more register values from the current " 45 "frame. If no register is specified, dumps them all.", 46 nullptr, 47 eCommandRequiresFrame | eCommandRequiresRegContext | 48 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), 49 m_format_options(eFormatDefault, UINT64_MAX, UINT64_MAX, 50 {{CommandArgumentType::eArgTypeFormat, 51 "Specify a format to be used for display. If this " 52 "is set, register fields will not be displayed."}}) { 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 void 79 HandleArgumentCompletion(CompletionRequest &request, 80 OptionElementVector &opt_element_vector) override { 81 if (!m_exe_ctx.HasProcessScope()) 82 return; 83 CommandObject::HandleArgumentCompletion(request, opt_element_vector); 84 } 85 86 Options *GetOptions() override { return &m_option_group; } 87 88 bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm, 89 RegisterContext ®_ctx, const RegisterInfo ®_info, 90 bool print_flags) { 91 RegisterValue reg_value; 92 if (!reg_ctx.ReadRegister(®_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 void 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 } 236 237 class CommandOptions : public OptionGroup { 238 public: 239 CommandOptions() 240 : set_indexes(OptionValue::ConvertTypeToMask(OptionValue::eTypeUInt64)), 241 dump_all_sets(false, false), // Initial and default values are false 242 alternate_name(false, false) {} 243 244 ~CommandOptions() override = default; 245 246 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 247 return llvm::ArrayRef(g_register_read_options); 248 } 249 250 void OptionParsingStarting(ExecutionContext *execution_context) override { 251 set_indexes.Clear(); 252 dump_all_sets.Clear(); 253 alternate_name.Clear(); 254 } 255 256 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, 257 ExecutionContext *execution_context) override { 258 Status error; 259 const int short_option = GetDefinitions()[option_idx].short_option; 260 switch (short_option) { 261 case 's': { 262 OptionValueSP value_sp(OptionValueUInt64::Create(option_value, error)); 263 if (value_sp) 264 set_indexes.AppendValue(value_sp); 265 } break; 266 267 case 'a': 268 // When we don't use OptionValue::SetValueFromCString(const char *) to 269 // set an option value, it won't be marked as being set in the options 270 // so we make a call to let users know the value was set via option 271 dump_all_sets.SetCurrentValue(true); 272 dump_all_sets.SetOptionWasSet(); 273 break; 274 275 case 'A': 276 // When we don't use OptionValue::SetValueFromCString(const char *) to 277 // set an option value, it won't be marked as being set in the options 278 // so we make a call to let users know the value was set via option 279 alternate_name.SetCurrentValue(true); 280 dump_all_sets.SetOptionWasSet(); 281 break; 282 283 default: 284 llvm_unreachable("Unimplemented option"); 285 } 286 return error; 287 } 288 289 // Instance variables to hold the values for command options. 290 OptionValueArray set_indexes; 291 OptionValueBoolean dump_all_sets; 292 OptionValueBoolean alternate_name; 293 }; 294 295 OptionGroupOptions m_option_group; 296 OptionGroupFormat m_format_options; 297 CommandOptions m_command_options; 298 }; 299 300 // "register write" 301 class CommandObjectRegisterWrite : public CommandObjectParsed { 302 public: 303 CommandObjectRegisterWrite(CommandInterpreter &interpreter) 304 : CommandObjectParsed(interpreter, "register write", 305 "Modify a single register value.", nullptr, 306 eCommandRequiresFrame | eCommandRequiresRegContext | 307 eCommandProcessMustBeLaunched | 308 eCommandProcessMustBePaused) { 309 CommandArgumentEntry arg1; 310 CommandArgumentEntry arg2; 311 CommandArgumentData register_arg; 312 CommandArgumentData value_arg; 313 314 // Define the first (and only) variant of this arg. 315 register_arg.arg_type = eArgTypeRegisterName; 316 register_arg.arg_repetition = eArgRepeatPlain; 317 318 // There is only one variant this argument could be; put it into the 319 // argument entry. 320 arg1.push_back(register_arg); 321 322 // Define the first (and only) variant of this arg. 323 value_arg.arg_type = eArgTypeValue; 324 value_arg.arg_repetition = eArgRepeatPlain; 325 326 // There is only one variant this argument could be; put it into the 327 // argument entry. 328 arg2.push_back(value_arg); 329 330 // Push the data for the first argument into the m_arguments vector. 331 m_arguments.push_back(arg1); 332 m_arguments.push_back(arg2); 333 } 334 335 ~CommandObjectRegisterWrite() override = default; 336 337 void 338 HandleArgumentCompletion(CompletionRequest &request, 339 OptionElementVector &opt_element_vector) override { 340 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0) 341 return; 342 343 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks( 344 GetCommandInterpreter(), lldb::eRegisterCompletion, request, nullptr); 345 } 346 347 protected: 348 void DoExecute(Args &command, CommandReturnObject &result) override { 349 DataExtractor reg_data; 350 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext(); 351 352 if (command.GetArgumentCount() != 2) { 353 result.AppendError( 354 "register write takes exactly 2 arguments: <reg-name> <value>"); 355 } else { 356 auto reg_name = command[0].ref(); 357 auto value_str = command[1].ref(); 358 359 // in most LLDB commands we accept $rbx as the name for register RBX - 360 // and here we would reject it and non-existant. we should be more 361 // consistent towards the user and allow them to say reg write $rbx - 362 // internally, however, we should be strict and not allow ourselves to 363 // call our registers $rbx in our own API 364 reg_name.consume_front("$"); 365 366 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name); 367 368 if (reg_info) { 369 RegisterValue reg_value; 370 371 Status error(reg_value.SetValueFromString(reg_info, value_str)); 372 if (error.Success()) { 373 if (reg_ctx->WriteRegister(reg_info, reg_value)) { 374 // Toss all frames and anything else in the thread after a register 375 // has been written. 376 m_exe_ctx.GetThreadRef().Flush(); 377 result.SetStatus(eReturnStatusSuccessFinishNoResult); 378 return; 379 } 380 } 381 if (error.AsCString()) { 382 result.AppendErrorWithFormat( 383 "Failed to write register '%s' with value '%s': %s\n", 384 reg_name.str().c_str(), value_str.str().c_str(), 385 error.AsCString()); 386 } else { 387 result.AppendErrorWithFormat( 388 "Failed to write register '%s' with value '%s'", 389 reg_name.str().c_str(), value_str.str().c_str()); 390 } 391 } else { 392 result.AppendErrorWithFormat("Register not found for '%s'.\n", 393 reg_name.str().c_str()); 394 } 395 } 396 } 397 }; 398 399 // "register info" 400 class CommandObjectRegisterInfo : public CommandObjectParsed { 401 public: 402 CommandObjectRegisterInfo(CommandInterpreter &interpreter) 403 : CommandObjectParsed(interpreter, "register info", 404 "View information about a register.", nullptr, 405 eCommandRequiresFrame | eCommandRequiresRegContext | 406 eCommandProcessMustBeLaunched | 407 eCommandProcessMustBePaused) { 408 SetHelpLong(R"( 409 Name The name lldb uses for the register, optionally with an alias. 410 Size The size of the register in bytes and again in bits. 411 Invalidates (*) The registers that would be changed if you wrote this 412 register. For example, writing to a narrower alias of a wider 413 register would change the value of the wider register. 414 Read from (*) The registers that the value of this register is constructed 415 from. For example, a narrower alias of a wider register will be 416 read from the wider register. 417 In sets (*) The register sets that contain this register. For example the 418 PC will be in the "General Purpose Register" set. 419 Fields (*) A table of the names and bit positions of the values contained 420 in this register. 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 CommandObject::HandleArgumentCompletion(request, opt_element_vector); 442 } 443 444 protected: 445 void DoExecute(Args &command, CommandReturnObject &result) override { 446 if (command.GetArgumentCount() != 1) { 447 result.AppendError("register info takes exactly 1 argument: <reg-name>"); 448 return; 449 } 450 451 llvm::StringRef reg_name = command[0].ref(); 452 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext(); 453 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name); 454 if (reg_info) { 455 DumpRegisterInfo( 456 result.GetOutputStream(), *reg_ctx, *reg_info, 457 GetCommandInterpreter().GetDebugger().GetTerminalWidth()); 458 result.SetStatus(eReturnStatusSuccessFinishResult); 459 } else 460 result.AppendErrorWithFormat("No register found with name '%s'.\n", 461 reg_name.str().c_str()); 462 } 463 }; 464 465 // CommandObjectRegister constructor 466 CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter) 467 : CommandObjectMultiword(interpreter, "register", 468 "Commands to access registers for the current " 469 "thread and stack frame.", 470 "register [read|write|info] ...") { 471 LoadSubCommand("read", 472 CommandObjectSP(new CommandObjectRegisterRead(interpreter))); 473 LoadSubCommand("write", 474 CommandObjectSP(new CommandObjectRegisterWrite(interpreter))); 475 LoadSubCommand("info", 476 CommandObjectSP(new CommandObjectRegisterInfo(interpreter))); 477 } 478 479 CommandObjectRegister::~CommandObjectRegister() = default; 480