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