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/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_format_options(eFormatDefault) { 47 CommandArgumentEntry arg; 48 CommandArgumentData register_arg; 49 50 // Define the first (and only) variant of this arg. 51 register_arg.arg_type = eArgTypeRegisterName; 52 register_arg.arg_repetition = eArgRepeatStar; 53 54 // There is only one variant this argument could be; put it into the 55 // argument entry. 56 arg.push_back(register_arg); 57 58 // Push the data for the first argument into the m_arguments vector. 59 m_arguments.push_back(arg); 60 61 // Add the "--format" 62 m_option_group.Append(&m_format_options, 63 OptionGroupFormat::OPTION_GROUP_FORMAT | 64 OptionGroupFormat::OPTION_GROUP_GDB_FMT, 65 LLDB_OPT_SET_ALL); 66 m_option_group.Append(&m_command_options); 67 m_option_group.Finalize(); 68 } 69 70 ~CommandObjectRegisterRead() override = default; 71 72 void 73 HandleArgumentCompletion(CompletionRequest &request, 74 OptionElementVector &opt_element_vector) override { 75 if (!m_exe_ctx.HasProcessScope()) 76 return; 77 78 CommandCompletions::InvokeCommonCompletionCallbacks( 79 GetCommandInterpreter(), CommandCompletions::eRegisterCompletion, 80 request, nullptr); 81 } 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 DumpRegisterValue(reg_value, &strm, reg_info, prefix_with_name, 96 prefix_with_altname, 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 break; 181 } 182 } else { 183 result.AppendErrorWithFormat( 184 "invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx); 185 break; 186 } 187 } 188 } else { 189 if (m_command_options.dump_all_sets) 190 num_register_sets = reg_ctx->GetRegisterSetCount(); 191 192 for (set_idx = 0; set_idx < num_register_sets; ++set_idx) { 193 // When dump_all_sets option is set, dump primitive as well as 194 // derived registers. 195 DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx, 196 !m_command_options.dump_all_sets.GetCurrentValue()); 197 } 198 } 199 } else { 200 if (m_command_options.dump_all_sets) { 201 result.AppendError("the --all option can't be used when registers " 202 "names are supplied as arguments\n"); 203 } else if (m_command_options.set_indexes.GetSize() > 0) { 204 result.AppendError("the --set <set> option can't be used when " 205 "registers names are supplied as arguments\n"); 206 } else { 207 for (auto &entry : command) { 208 // in most LLDB commands we accept $rbx as the name for register RBX 209 // - and here we would reject it and non-existant. we should be more 210 // consistent towards the user and allow them to say reg read $rbx - 211 // internally, however, we should be strict and not allow ourselves 212 // to call our registers $rbx in our own API 213 auto arg_str = entry.ref(); 214 arg_str.consume_front("$"); 215 216 reg_info = reg_ctx->GetRegisterInfoByName(arg_str); 217 218 if (reg_info) { 219 if (!DumpRegister(m_exe_ctx, strm, reg_ctx, reg_info)) 220 strm.Printf("%-12s = error: unavailable\n", reg_info->name); 221 } else { 222 result.AppendErrorWithFormat("Invalid register name '%s'.\n", 223 arg_str.str().c_str()); 224 } 225 } 226 } 227 } 228 return result.Succeeded(); 229 } 230 231 class CommandOptions : public OptionGroup { 232 public: 233 CommandOptions() 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 llvm_unreachable("Unimplemented option"); 279 } 280 return error; 281 } 282 283 // Instance variables to hold the values for command options. 284 OptionValueArray set_indexes; 285 OptionValueBoolean dump_all_sets; 286 OptionValueBoolean alternate_name; 287 }; 288 289 OptionGroupOptions m_option_group; 290 OptionGroupFormat m_format_options; 291 CommandOptions m_command_options; 292 }; 293 294 // "register write" 295 class CommandObjectRegisterWrite : public CommandObjectParsed { 296 public: 297 CommandObjectRegisterWrite(CommandInterpreter &interpreter) 298 : CommandObjectParsed(interpreter, "register write", 299 "Modify a single register value.", nullptr, 300 eCommandRequiresFrame | eCommandRequiresRegContext | 301 eCommandProcessMustBeLaunched | 302 eCommandProcessMustBePaused) { 303 CommandArgumentEntry arg1; 304 CommandArgumentEntry arg2; 305 CommandArgumentData register_arg; 306 CommandArgumentData value_arg; 307 308 // Define the first (and only) variant of this arg. 309 register_arg.arg_type = eArgTypeRegisterName; 310 register_arg.arg_repetition = eArgRepeatPlain; 311 312 // There is only one variant this argument could be; put it into the 313 // argument entry. 314 arg1.push_back(register_arg); 315 316 // Define the first (and only) variant of this arg. 317 value_arg.arg_type = eArgTypeValue; 318 value_arg.arg_repetition = eArgRepeatPlain; 319 320 // There is only one variant this argument could be; put it into the 321 // argument entry. 322 arg2.push_back(value_arg); 323 324 // Push the data for the first argument into the m_arguments vector. 325 m_arguments.push_back(arg1); 326 m_arguments.push_back(arg2); 327 } 328 329 ~CommandObjectRegisterWrite() override = default; 330 331 void 332 HandleArgumentCompletion(CompletionRequest &request, 333 OptionElementVector &opt_element_vector) override { 334 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0) 335 return; 336 337 CommandCompletions::InvokeCommonCompletionCallbacks( 338 GetCommandInterpreter(), CommandCompletions::eRegisterCompletion, 339 request, nullptr); 340 } 341 342 protected: 343 bool DoExecute(Args &command, CommandReturnObject &result) override { 344 DataExtractor reg_data; 345 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext(); 346 347 if (command.GetArgumentCount() != 2) { 348 result.AppendError( 349 "register write takes exactly 2 arguments: <reg-name> <value>"); 350 } else { 351 auto reg_name = command[0].ref(); 352 auto value_str = command[1].ref(); 353 354 // in most LLDB commands we accept $rbx as the name for register RBX - 355 // and here we would reject it and non-existant. we should be more 356 // consistent towards the user and allow them to say reg write $rbx - 357 // internally, however, we should be strict and not allow ourselves to 358 // call our registers $rbx in our own API 359 reg_name.consume_front("$"); 360 361 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name); 362 363 if (reg_info) { 364 RegisterValue reg_value; 365 366 Status error(reg_value.SetValueFromString(reg_info, value_str)); 367 if (error.Success()) { 368 if (reg_ctx->WriteRegister(reg_info, reg_value)) { 369 // Toss all frames and anything else in the thread after a register 370 // has been written. 371 m_exe_ctx.GetThreadRef().Flush(); 372 result.SetStatus(eReturnStatusSuccessFinishNoResult); 373 return true; 374 } 375 } 376 if (error.AsCString()) { 377 result.AppendErrorWithFormat( 378 "Failed to write register '%s' with value '%s': %s\n", 379 reg_name.str().c_str(), value_str.str().c_str(), 380 error.AsCString()); 381 } else { 382 result.AppendErrorWithFormat( 383 "Failed to write register '%s' with value '%s'", 384 reg_name.str().c_str(), value_str.str().c_str()); 385 } 386 } else { 387 result.AppendErrorWithFormat("Register not found for '%s'.\n", 388 reg_name.str().c_str()); 389 } 390 } 391 return result.Succeeded(); 392 } 393 }; 394 395 // CommandObjectRegister constructor 396 CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter) 397 : CommandObjectMultiword(interpreter, "register", 398 "Commands to access registers for the current " 399 "thread and stack frame.", 400 "register [read|write] ...") { 401 LoadSubCommand("read", 402 CommandObjectSP(new CommandObjectRegisterRead(interpreter))); 403 LoadSubCommand("write", 404 CommandObjectSP(new CommandObjectRegisterWrite(interpreter))); 405 } 406 407 CommandObjectRegister::~CommandObjectRegister() = default; 408