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/CommandOptionArgumentTable.h" 14 #include "lldb/Interpreter/CommandReturnObject.h" 15 #include "lldb/Interpreter/OptionGroupFormat.h" 16 #include "lldb/Interpreter/OptionValueArray.h" 17 #include "lldb/Interpreter/OptionValueBoolean.h" 18 #include "lldb/Interpreter/OptionValueUInt64.h" 19 #include "lldb/Interpreter/Options.h" 20 #include "lldb/Target/ExecutionContext.h" 21 #include "lldb/Target/Process.h" 22 #include "lldb/Target/RegisterContext.h" 23 #include "lldb/Target/SectionLoadList.h" 24 #include "lldb/Target/Thread.h" 25 #include "lldb/Utility/Args.h" 26 #include "lldb/Utility/DataExtractor.h" 27 #include "lldb/Utility/RegisterValue.h" 28 #include "llvm/Support/Errno.h" 29 30 using namespace lldb; 31 using namespace lldb_private; 32 33 // "register read" 34 #define LLDB_OPTIONS_register_read 35 #include "CommandOptions.inc" 36 37 class CommandObjectRegisterRead : public CommandObjectParsed { 38 public: 39 CommandObjectRegisterRead(CommandInterpreter &interpreter) 40 : CommandObjectParsed( 41 interpreter, "register read", 42 "Dump the contents of one or more register values from the current " 43 "frame. If no register is specified, dumps them all.", 44 nullptr, 45 eCommandRequiresFrame | eCommandRequiresRegContext | 46 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused), 47 m_format_options(eFormatDefault) { 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 void 74 HandleArgumentCompletion(CompletionRequest &request, 75 OptionElementVector &opt_element_vector) override { 76 if (!m_exe_ctx.HasProcessScope()) 77 return; 78 79 CommandCompletions::InvokeCommonCompletionCallbacks( 80 GetCommandInterpreter(), CommandCompletions::eRegisterCompletion, 81 request, nullptr); 82 } 83 84 Options *GetOptions() override { return &m_option_group; } 85 86 bool DumpRegister(const ExecutionContext &exe_ctx, Stream &strm, 87 RegisterContext *reg_ctx, const RegisterInfo *reg_info, 88 bool print_flags) { 89 if (reg_info) { 90 RegisterValue reg_value; 91 92 if (reg_ctx->ReadRegister(reg_info, reg_value)) { 93 strm.Indent(); 94 95 bool prefix_with_altname = (bool)m_command_options.alternate_name; 96 bool prefix_with_name = !prefix_with_altname; 97 DumpRegisterValue(reg_value, &strm, reg_info, prefix_with_name, 98 prefix_with_altname, m_format_options.GetFormat(), 8, 99 exe_ctx.GetBestExecutionContextScope(), print_flags, 100 exe_ctx.GetTargetSP()); 101 if ((reg_info->encoding == eEncodingUint) || 102 (reg_info->encoding == eEncodingSint)) { 103 Process *process = exe_ctx.GetProcessPtr(); 104 if (process && reg_info->byte_size == process->GetAddressByteSize()) { 105 addr_t reg_addr = reg_value.GetAsUInt64(LLDB_INVALID_ADDRESS); 106 if (reg_addr != LLDB_INVALID_ADDRESS) { 107 Address so_reg_addr; 108 if (exe_ctx.GetTargetRef() 109 .GetSectionLoadList() 110 .ResolveLoadAddress(reg_addr, so_reg_addr)) { 111 strm.PutCString(" "); 112 so_reg_addr.Dump(&strm, exe_ctx.GetBestExecutionContextScope(), 113 Address::DumpStyleResolvedDescription); 114 } 115 } 116 } 117 } 118 strm.EOL(); 119 return true; 120 } 121 } 122 return false; 123 } 124 125 bool DumpRegisterSet(const ExecutionContext &exe_ctx, Stream &strm, 126 RegisterContext *reg_ctx, size_t set_idx, 127 bool primitive_only = false) { 128 uint32_t unavailable_count = 0; 129 uint32_t available_count = 0; 130 131 if (!reg_ctx) 132 return false; // thread has no registers (i.e. core files are corrupt, 133 // incomplete crash logs...) 134 135 const RegisterSet *const reg_set = reg_ctx->GetRegisterSet(set_idx); 136 if (reg_set) { 137 strm.Printf("%s:\n", (reg_set->name ? reg_set->name : "unknown")); 138 strm.IndentMore(); 139 const size_t num_registers = reg_set->num_registers; 140 for (size_t reg_idx = 0; reg_idx < num_registers; ++reg_idx) { 141 const uint32_t reg = reg_set->registers[reg_idx]; 142 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg); 143 // Skip the dumping of derived register if primitive_only is true. 144 if (primitive_only && reg_info && reg_info->value_regs) 145 continue; 146 147 if (DumpRegister(exe_ctx, strm, reg_ctx, reg_info, 148 /*print_flags=*/false)) 149 ++available_count; 150 else 151 ++unavailable_count; 152 } 153 strm.IndentLess(); 154 if (unavailable_count) { 155 strm.Indent(); 156 strm.Printf("%u registers were unavailable.\n", unavailable_count); 157 } 158 strm.EOL(); 159 } 160 return available_count > 0; 161 } 162 163 protected: 164 bool DoExecute(Args &command, CommandReturnObject &result) override { 165 Stream &strm = result.GetOutputStream(); 166 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext(); 167 168 const RegisterInfo *reg_info = nullptr; 169 if (command.GetArgumentCount() == 0) { 170 size_t set_idx; 171 172 size_t num_register_sets = 1; 173 const size_t set_array_size = m_command_options.set_indexes.GetSize(); 174 if (set_array_size > 0) { 175 for (size_t i = 0; i < set_array_size; ++i) { 176 set_idx = m_command_options.set_indexes[i]->GetUInt64Value(UINT32_MAX, 177 nullptr); 178 if (set_idx < reg_ctx->GetRegisterSetCount()) { 179 if (!DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx)) { 180 if (errno) 181 result.AppendErrorWithFormatv("register read failed: {0}\n", 182 llvm::sys::StrError()); 183 else 184 result.AppendError("unknown error while reading registers.\n"); 185 break; 186 } 187 } else { 188 result.AppendErrorWithFormat( 189 "invalid register set index: %" PRIu64 "\n", (uint64_t)set_idx); 190 break; 191 } 192 } 193 } else { 194 if (m_command_options.dump_all_sets) 195 num_register_sets = reg_ctx->GetRegisterSetCount(); 196 197 for (set_idx = 0; set_idx < num_register_sets; ++set_idx) { 198 // When dump_all_sets option is set, dump primitive as well as 199 // derived registers. 200 DumpRegisterSet(m_exe_ctx, strm, reg_ctx, set_idx, 201 !m_command_options.dump_all_sets.GetCurrentValue()); 202 } 203 } 204 } else { 205 if (m_command_options.dump_all_sets) { 206 result.AppendError("the --all option can't be used when registers " 207 "names are supplied as arguments\n"); 208 } else if (m_command_options.set_indexes.GetSize() > 0) { 209 result.AppendError("the --set <set> option can't be used when " 210 "registers names are supplied as arguments\n"); 211 } else { 212 for (auto &entry : command) { 213 // in most LLDB commands we accept $rbx as the name for register RBX 214 // - and here we would reject it and non-existant. we should be more 215 // consistent towards the user and allow them to say reg read $rbx - 216 // internally, however, we should be strict and not allow ourselves 217 // to call our registers $rbx in our own API 218 auto arg_str = entry.ref(); 219 arg_str.consume_front("$"); 220 221 reg_info = reg_ctx->GetRegisterInfoByName(arg_str); 222 223 if (reg_info) { 224 if (!DumpRegister(m_exe_ctx, strm, reg_ctx, reg_info, 225 /*print_flags=*/true)) 226 strm.Printf("%-12s = error: unavailable\n", reg_info->name); 227 } else { 228 result.AppendErrorWithFormat("Invalid register name '%s'.\n", 229 arg_str.str().c_str()); 230 } 231 } 232 } 233 } 234 return result.Succeeded(); 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 CommandCompletions::InvokeCommonCompletionCallbacks( 344 GetCommandInterpreter(), CommandCompletions::eRegisterCompletion, 345 request, nullptr); 346 } 347 348 protected: 349 bool DoExecute(Args &command, CommandReturnObject &result) override { 350 DataExtractor reg_data; 351 RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext(); 352 353 if (command.GetArgumentCount() != 2) { 354 result.AppendError( 355 "register write takes exactly 2 arguments: <reg-name> <value>"); 356 } else { 357 auto reg_name = command[0].ref(); 358 auto value_str = command[1].ref(); 359 360 // in most LLDB commands we accept $rbx as the name for register RBX - 361 // and here we would reject it and non-existant. we should be more 362 // consistent towards the user and allow them to say reg write $rbx - 363 // internally, however, we should be strict and not allow ourselves to 364 // call our registers $rbx in our own API 365 reg_name.consume_front("$"); 366 367 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name); 368 369 if (reg_info) { 370 RegisterValue reg_value; 371 372 Status error(reg_value.SetValueFromString(reg_info, value_str)); 373 if (error.Success()) { 374 if (reg_ctx->WriteRegister(reg_info, reg_value)) { 375 // Toss all frames and anything else in the thread after a register 376 // has been written. 377 m_exe_ctx.GetThreadRef().Flush(); 378 result.SetStatus(eReturnStatusSuccessFinishNoResult); 379 return true; 380 } 381 } 382 if (error.AsCString()) { 383 result.AppendErrorWithFormat( 384 "Failed to write register '%s' with value '%s': %s\n", 385 reg_name.str().c_str(), value_str.str().c_str(), 386 error.AsCString()); 387 } else { 388 result.AppendErrorWithFormat( 389 "Failed to write register '%s' with value '%s'", 390 reg_name.str().c_str(), value_str.str().c_str()); 391 } 392 } else { 393 result.AppendErrorWithFormat("Register not found for '%s'.\n", 394 reg_name.str().c_str()); 395 } 396 } 397 return result.Succeeded(); 398 } 399 }; 400 401 // CommandObjectRegister constructor 402 CommandObjectRegister::CommandObjectRegister(CommandInterpreter &interpreter) 403 : CommandObjectMultiword(interpreter, "register", 404 "Commands to access registers for the current " 405 "thread and stack frame.", 406 "register [read|write] ...") { 407 LoadSubCommand("read", 408 CommandObjectSP(new CommandObjectRegisterRead(interpreter))); 409 LoadSubCommand("write", 410 CommandObjectSP(new CommandObjectRegisterWrite(interpreter))); 411 } 412 413 CommandObjectRegister::~CommandObjectRegister() = default; 414