1 //===-- CommandObjectMemory.cpp ---------------------------------*- C++ -*-===// 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 "CommandObjectMemory.h" 10 #include "lldb/Core/Debugger.h" 11 #include "lldb/Core/DumpDataExtractor.h" 12 #include "lldb/Core/Module.h" 13 #include "lldb/Core/Section.h" 14 #include "lldb/Core/ValueObjectMemory.h" 15 #include "lldb/DataFormatters/ValueObjectPrinter.h" 16 #include "lldb/Expression/ExpressionVariable.h" 17 #include "lldb/Host/OptionParser.h" 18 #include "lldb/Interpreter/CommandInterpreter.h" 19 #include "lldb/Interpreter/CommandReturnObject.h" 20 #include "lldb/Interpreter/OptionArgParser.h" 21 #include "lldb/Interpreter/OptionGroupFormat.h" 22 #include "lldb/Interpreter/OptionGroupOutputFile.h" 23 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h" 24 #include "lldb/Interpreter/OptionValueLanguage.h" 25 #include "lldb/Interpreter/OptionValueString.h" 26 #include "lldb/Interpreter/Options.h" 27 #include "lldb/Symbol/SymbolFile.h" 28 #include "lldb/Symbol/TypeList.h" 29 #include "lldb/Target/Language.h" 30 #include "lldb/Target/MemoryHistory.h" 31 #include "lldb/Target/MemoryRegionInfo.h" 32 #include "lldb/Target/Process.h" 33 #include "lldb/Target/StackFrame.h" 34 #include "lldb/Target/Target.h" 35 #include "lldb/Target/Thread.h" 36 #include "lldb/Utility/Args.h" 37 #include "lldb/Utility/DataBufferHeap.h" 38 #include "lldb/Utility/DataBufferLLVM.h" 39 #include "lldb/Utility/StreamString.h" 40 41 #include "lldb/lldb-private.h" 42 43 #include <cinttypes> 44 #include <memory> 45 46 using namespace lldb; 47 using namespace lldb_private; 48 49 #define LLDB_OPTIONS_memory_read 50 #include "CommandOptions.inc" 51 52 class OptionGroupReadMemory : public OptionGroup { 53 public: 54 OptionGroupReadMemory() 55 : m_num_per_line(1, 1), m_output_as_binary(false), m_view_as_type(), 56 m_offset(0, 0), m_language_for_type(eLanguageTypeUnknown) {} 57 58 ~OptionGroupReadMemory() override = default; 59 60 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 61 return llvm::makeArrayRef(g_memory_read_options); 62 } 63 64 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, 65 ExecutionContext *execution_context) override { 66 Status error; 67 const int short_option = g_memory_read_options[option_idx].short_option; 68 69 switch (short_option) { 70 case 'l': 71 error = m_num_per_line.SetValueFromString(option_value); 72 if (m_num_per_line.GetCurrentValue() == 0) 73 error.SetErrorStringWithFormat( 74 "invalid value for --num-per-line option '%s'", 75 option_value.str().c_str()); 76 break; 77 78 case 'b': 79 m_output_as_binary = true; 80 break; 81 82 case 't': 83 error = m_view_as_type.SetValueFromString(option_value); 84 break; 85 86 case 'r': 87 m_force = true; 88 break; 89 90 case 'x': 91 error = m_language_for_type.SetValueFromString(option_value); 92 break; 93 94 case 'E': 95 error = m_offset.SetValueFromString(option_value); 96 break; 97 98 default: 99 llvm_unreachable("Unimplemented option"); 100 } 101 return error; 102 } 103 104 void OptionParsingStarting(ExecutionContext *execution_context) override { 105 m_num_per_line.Clear(); 106 m_output_as_binary = false; 107 m_view_as_type.Clear(); 108 m_force = false; 109 m_offset.Clear(); 110 m_language_for_type.Clear(); 111 } 112 113 Status FinalizeSettings(Target *target, OptionGroupFormat &format_options) { 114 Status error; 115 OptionValueUInt64 &byte_size_value = format_options.GetByteSizeValue(); 116 OptionValueUInt64 &count_value = format_options.GetCountValue(); 117 const bool byte_size_option_set = byte_size_value.OptionWasSet(); 118 const bool num_per_line_option_set = m_num_per_line.OptionWasSet(); 119 const bool count_option_set = format_options.GetCountValue().OptionWasSet(); 120 121 switch (format_options.GetFormat()) { 122 default: 123 break; 124 125 case eFormatBoolean: 126 if (!byte_size_option_set) 127 byte_size_value = 1; 128 if (!num_per_line_option_set) 129 m_num_per_line = 1; 130 if (!count_option_set) 131 format_options.GetCountValue() = 8; 132 break; 133 134 case eFormatCString: 135 break; 136 137 case eFormatInstruction: 138 if (count_option_set) 139 byte_size_value = target->GetArchitecture().GetMaximumOpcodeByteSize(); 140 m_num_per_line = 1; 141 break; 142 143 case eFormatAddressInfo: 144 if (!byte_size_option_set) 145 byte_size_value = target->GetArchitecture().GetAddressByteSize(); 146 m_num_per_line = 1; 147 if (!count_option_set) 148 format_options.GetCountValue() = 8; 149 break; 150 151 case eFormatPointer: 152 byte_size_value = target->GetArchitecture().GetAddressByteSize(); 153 if (!num_per_line_option_set) 154 m_num_per_line = 4; 155 if (!count_option_set) 156 format_options.GetCountValue() = 8; 157 break; 158 159 case eFormatBinary: 160 case eFormatFloat: 161 case eFormatOctal: 162 case eFormatDecimal: 163 case eFormatEnum: 164 case eFormatUnicode8: 165 case eFormatUnicode16: 166 case eFormatUnicode32: 167 case eFormatUnsigned: 168 case eFormatHexFloat: 169 if (!byte_size_option_set) 170 byte_size_value = 4; 171 if (!num_per_line_option_set) 172 m_num_per_line = 1; 173 if (!count_option_set) 174 format_options.GetCountValue() = 8; 175 break; 176 177 case eFormatBytes: 178 case eFormatBytesWithASCII: 179 if (byte_size_option_set) { 180 if (byte_size_value > 1) 181 error.SetErrorStringWithFormat( 182 "display format (bytes/bytes with ASCII) conflicts with the " 183 "specified byte size %" PRIu64 "\n" 184 "\tconsider using a different display format or don't specify " 185 "the byte size.", 186 byte_size_value.GetCurrentValue()); 187 } else 188 byte_size_value = 1; 189 if (!num_per_line_option_set) 190 m_num_per_line = 16; 191 if (!count_option_set) 192 format_options.GetCountValue() = 32; 193 break; 194 195 case eFormatCharArray: 196 case eFormatChar: 197 case eFormatCharPrintable: 198 if (!byte_size_option_set) 199 byte_size_value = 1; 200 if (!num_per_line_option_set) 201 m_num_per_line = 32; 202 if (!count_option_set) 203 format_options.GetCountValue() = 64; 204 break; 205 206 case eFormatComplex: 207 if (!byte_size_option_set) 208 byte_size_value = 8; 209 if (!num_per_line_option_set) 210 m_num_per_line = 1; 211 if (!count_option_set) 212 format_options.GetCountValue() = 8; 213 break; 214 215 case eFormatComplexInteger: 216 if (!byte_size_option_set) 217 byte_size_value = 8; 218 if (!num_per_line_option_set) 219 m_num_per_line = 1; 220 if (!count_option_set) 221 format_options.GetCountValue() = 8; 222 break; 223 224 case eFormatHex: 225 if (!byte_size_option_set) 226 byte_size_value = 4; 227 if (!num_per_line_option_set) { 228 switch (byte_size_value) { 229 case 1: 230 case 2: 231 m_num_per_line = 8; 232 break; 233 case 4: 234 m_num_per_line = 4; 235 break; 236 case 8: 237 m_num_per_line = 2; 238 break; 239 default: 240 m_num_per_line = 1; 241 break; 242 } 243 } 244 if (!count_option_set) 245 count_value = 8; 246 break; 247 248 case eFormatVectorOfChar: 249 case eFormatVectorOfSInt8: 250 case eFormatVectorOfUInt8: 251 case eFormatVectorOfSInt16: 252 case eFormatVectorOfUInt16: 253 case eFormatVectorOfSInt32: 254 case eFormatVectorOfUInt32: 255 case eFormatVectorOfSInt64: 256 case eFormatVectorOfUInt64: 257 case eFormatVectorOfFloat16: 258 case eFormatVectorOfFloat32: 259 case eFormatVectorOfFloat64: 260 case eFormatVectorOfUInt128: 261 if (!byte_size_option_set) 262 byte_size_value = 128; 263 if (!num_per_line_option_set) 264 m_num_per_line = 1; 265 if (!count_option_set) 266 count_value = 4; 267 break; 268 } 269 return error; 270 } 271 272 bool AnyOptionWasSet() const { 273 return m_num_per_line.OptionWasSet() || m_output_as_binary || 274 m_view_as_type.OptionWasSet() || m_offset.OptionWasSet() || 275 m_language_for_type.OptionWasSet(); 276 } 277 278 OptionValueUInt64 m_num_per_line; 279 bool m_output_as_binary; 280 OptionValueString m_view_as_type; 281 bool m_force; 282 OptionValueUInt64 m_offset; 283 OptionValueLanguage m_language_for_type; 284 }; 285 286 // Read memory from the inferior process 287 class CommandObjectMemoryRead : public CommandObjectParsed { 288 public: 289 CommandObjectMemoryRead(CommandInterpreter &interpreter) 290 : CommandObjectParsed( 291 interpreter, "memory read", 292 "Read from the memory of the current target process.", nullptr, 293 eCommandRequiresTarget | eCommandProcessMustBePaused), 294 m_option_group(), m_format_options(eFormatBytesWithASCII, 1, 8), 295 m_memory_options(), m_outfile_options(), m_varobj_options(), 296 m_next_addr(LLDB_INVALID_ADDRESS), m_prev_byte_size(0), 297 m_prev_format_options(eFormatBytesWithASCII, 1, 8), 298 m_prev_memory_options(), m_prev_outfile_options(), 299 m_prev_varobj_options() { 300 CommandArgumentEntry arg1; 301 CommandArgumentEntry arg2; 302 CommandArgumentData start_addr_arg; 303 CommandArgumentData end_addr_arg; 304 305 // Define the first (and only) variant of this arg. 306 start_addr_arg.arg_type = eArgTypeAddressOrExpression; 307 start_addr_arg.arg_repetition = eArgRepeatPlain; 308 309 // There is only one variant this argument could be; put it into the 310 // argument entry. 311 arg1.push_back(start_addr_arg); 312 313 // Define the first (and only) variant of this arg. 314 end_addr_arg.arg_type = eArgTypeAddressOrExpression; 315 end_addr_arg.arg_repetition = eArgRepeatOptional; 316 317 // There is only one variant this argument could be; put it into the 318 // argument entry. 319 arg2.push_back(end_addr_arg); 320 321 // Push the data for the first argument into the m_arguments vector. 322 m_arguments.push_back(arg1); 323 m_arguments.push_back(arg2); 324 325 // Add the "--format" and "--count" options to group 1 and 3 326 m_option_group.Append(&m_format_options, 327 OptionGroupFormat::OPTION_GROUP_FORMAT | 328 OptionGroupFormat::OPTION_GROUP_COUNT, 329 LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3); 330 m_option_group.Append(&m_format_options, 331 OptionGroupFormat::OPTION_GROUP_GDB_FMT, 332 LLDB_OPT_SET_1 | LLDB_OPT_SET_3); 333 // Add the "--size" option to group 1 and 2 334 m_option_group.Append(&m_format_options, 335 OptionGroupFormat::OPTION_GROUP_SIZE, 336 LLDB_OPT_SET_1 | LLDB_OPT_SET_2); 337 m_option_group.Append(&m_memory_options); 338 m_option_group.Append(&m_outfile_options, LLDB_OPT_SET_ALL, 339 LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3); 340 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3); 341 m_option_group.Finalize(); 342 } 343 344 ~CommandObjectMemoryRead() override = default; 345 346 Options *GetOptions() override { return &m_option_group; } 347 348 const char *GetRepeatCommand(Args ¤t_command_args, 349 uint32_t index) override { 350 return m_cmd_name.c_str(); 351 } 352 353 protected: 354 bool DoExecute(Args &command, CommandReturnObject &result) override { 355 // No need to check "target" for validity as eCommandRequiresTarget ensures 356 // it is valid 357 Target *target = m_exe_ctx.GetTargetPtr(); 358 359 const size_t argc = command.GetArgumentCount(); 360 361 if ((argc == 0 && m_next_addr == LLDB_INVALID_ADDRESS) || argc > 2) { 362 result.AppendErrorWithFormat("%s takes a start address expression with " 363 "an optional end address expression.\n", 364 m_cmd_name.c_str()); 365 result.AppendRawWarning("Expressions should be quoted if they contain " 366 "spaces or other special characters.\n"); 367 result.SetStatus(eReturnStatusFailed); 368 return false; 369 } 370 371 CompilerType compiler_type; 372 Status error; 373 374 const char *view_as_type_cstr = 375 m_memory_options.m_view_as_type.GetCurrentValue(); 376 if (view_as_type_cstr && view_as_type_cstr[0]) { 377 // We are viewing memory as a type 378 379 const bool exact_match = false; 380 TypeList type_list; 381 uint32_t reference_count = 0; 382 uint32_t pointer_count = 0; 383 size_t idx; 384 385 #define ALL_KEYWORDS \ 386 KEYWORD("const") \ 387 KEYWORD("volatile") \ 388 KEYWORD("restrict") \ 389 KEYWORD("struct") \ 390 KEYWORD("class") \ 391 KEYWORD("union") 392 393 #define KEYWORD(s) s, 394 static const char *g_keywords[] = {ALL_KEYWORDS}; 395 #undef KEYWORD 396 397 #define KEYWORD(s) (sizeof(s) - 1), 398 static const int g_keyword_lengths[] = {ALL_KEYWORDS}; 399 #undef KEYWORD 400 401 #undef ALL_KEYWORDS 402 403 static size_t g_num_keywords = sizeof(g_keywords) / sizeof(const char *); 404 std::string type_str(view_as_type_cstr); 405 406 // Remove all instances of g_keywords that are followed by spaces 407 for (size_t i = 0; i < g_num_keywords; ++i) { 408 const char *keyword = g_keywords[i]; 409 int keyword_len = g_keyword_lengths[i]; 410 411 idx = 0; 412 while ((idx = type_str.find(keyword, idx)) != std::string::npos) { 413 if (type_str[idx + keyword_len] == ' ' || 414 type_str[idx + keyword_len] == '\t') { 415 type_str.erase(idx, keyword_len + 1); 416 idx = 0; 417 } else { 418 idx += keyword_len; 419 } 420 } 421 } 422 bool done = type_str.empty(); 423 // 424 idx = type_str.find_first_not_of(" \t"); 425 if (idx > 0 && idx != std::string::npos) 426 type_str.erase(0, idx); 427 while (!done) { 428 // Strip trailing spaces 429 if (type_str.empty()) 430 done = true; 431 else { 432 switch (type_str[type_str.size() - 1]) { 433 case '*': 434 ++pointer_count; 435 LLVM_FALLTHROUGH; 436 case ' ': 437 case '\t': 438 type_str.erase(type_str.size() - 1); 439 break; 440 441 case '&': 442 if (reference_count == 0) { 443 reference_count = 1; 444 type_str.erase(type_str.size() - 1); 445 } else { 446 result.AppendErrorWithFormat("invalid type string: '%s'\n", 447 view_as_type_cstr); 448 result.SetStatus(eReturnStatusFailed); 449 return false; 450 } 451 break; 452 453 default: 454 done = true; 455 break; 456 } 457 } 458 } 459 460 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files; 461 ConstString lookup_type_name(type_str.c_str()); 462 StackFrame *frame = m_exe_ctx.GetFramePtr(); 463 ModuleSP search_first; 464 if (frame) { 465 search_first = frame->GetSymbolContext(eSymbolContextModule).module_sp; 466 } 467 target->GetImages().FindTypes(search_first.get(), lookup_type_name, 468 exact_match, 1, searched_symbol_files, 469 type_list); 470 471 if (type_list.GetSize() == 0 && lookup_type_name.GetCString()) { 472 LanguageType language_for_type = 473 m_memory_options.m_language_for_type.GetCurrentValue(); 474 std::set<LanguageType> languages_to_check; 475 if (language_for_type != eLanguageTypeUnknown) { 476 languages_to_check.insert(language_for_type); 477 } else { 478 languages_to_check = Language::GetSupportedLanguages(); 479 } 480 481 std::set<CompilerType> user_defined_types; 482 for (auto lang : languages_to_check) { 483 if (auto *persistent_vars = 484 target->GetPersistentExpressionStateForLanguage(lang)) { 485 if (llvm::Optional<CompilerType> type = 486 persistent_vars->GetCompilerTypeFromPersistentDecl( 487 lookup_type_name)) { 488 user_defined_types.emplace(*type); 489 } 490 } 491 } 492 493 if (user_defined_types.size() > 1) { 494 result.AppendErrorWithFormat( 495 "Mutiple types found matching raw type '%s', please disambiguate " 496 "by specifying the language with -x", 497 lookup_type_name.GetCString()); 498 result.SetStatus(eReturnStatusFailed); 499 return false; 500 } 501 502 if (user_defined_types.size() == 1) { 503 compiler_type = *user_defined_types.begin(); 504 } 505 } 506 507 if (!compiler_type.IsValid()) { 508 if (type_list.GetSize() == 0) { 509 result.AppendErrorWithFormat("unable to find any types that match " 510 "the raw type '%s' for full type '%s'\n", 511 lookup_type_name.GetCString(), 512 view_as_type_cstr); 513 result.SetStatus(eReturnStatusFailed); 514 return false; 515 } else { 516 TypeSP type_sp(type_list.GetTypeAtIndex(0)); 517 compiler_type = type_sp->GetFullCompilerType(); 518 } 519 } 520 521 while (pointer_count > 0) { 522 CompilerType pointer_type = compiler_type.GetPointerType(); 523 if (pointer_type.IsValid()) 524 compiler_type = pointer_type; 525 else { 526 result.AppendError("unable make a pointer type\n"); 527 result.SetStatus(eReturnStatusFailed); 528 return false; 529 } 530 --pointer_count; 531 } 532 533 llvm::Optional<uint64_t> size = compiler_type.GetByteSize(nullptr); 534 if (!size) { 535 result.AppendErrorWithFormat( 536 "unable to get the byte size of the type '%s'\n", 537 view_as_type_cstr); 538 result.SetStatus(eReturnStatusFailed); 539 return false; 540 } 541 m_format_options.GetByteSizeValue() = *size; 542 543 if (!m_format_options.GetCountValue().OptionWasSet()) 544 m_format_options.GetCountValue() = 1; 545 } else { 546 error = m_memory_options.FinalizeSettings(target, m_format_options); 547 } 548 549 // Look for invalid combinations of settings 550 if (error.Fail()) { 551 result.AppendError(error.AsCString()); 552 result.SetStatus(eReturnStatusFailed); 553 return false; 554 } 555 556 lldb::addr_t addr; 557 size_t total_byte_size = 0; 558 if (argc == 0) { 559 // Use the last address and byte size and all options as they were if no 560 // options have been set 561 addr = m_next_addr; 562 total_byte_size = m_prev_byte_size; 563 compiler_type = m_prev_compiler_type; 564 if (!m_format_options.AnyOptionWasSet() && 565 !m_memory_options.AnyOptionWasSet() && 566 !m_outfile_options.AnyOptionWasSet() && 567 !m_varobj_options.AnyOptionWasSet()) { 568 m_format_options = m_prev_format_options; 569 m_memory_options = m_prev_memory_options; 570 m_outfile_options = m_prev_outfile_options; 571 m_varobj_options = m_prev_varobj_options; 572 } 573 } 574 575 size_t item_count = m_format_options.GetCountValue().GetCurrentValue(); 576 577 // TODO For non-8-bit byte addressable architectures this needs to be 578 // revisited to fully support all lldb's range of formatting options. 579 // Furthermore code memory reads (for those architectures) will not be 580 // correctly formatted even w/o formatting options. 581 size_t item_byte_size = 582 target->GetArchitecture().GetDataByteSize() > 1 583 ? target->GetArchitecture().GetDataByteSize() 584 : m_format_options.GetByteSizeValue().GetCurrentValue(); 585 586 const size_t num_per_line = 587 m_memory_options.m_num_per_line.GetCurrentValue(); 588 589 if (total_byte_size == 0) { 590 total_byte_size = item_count * item_byte_size; 591 if (total_byte_size == 0) 592 total_byte_size = 32; 593 } 594 595 if (argc > 0) 596 addr = OptionArgParser::ToAddress(&m_exe_ctx, command[0].ref(), 597 LLDB_INVALID_ADDRESS, &error); 598 599 if (addr == LLDB_INVALID_ADDRESS) { 600 result.AppendError("invalid start address expression."); 601 result.AppendError(error.AsCString()); 602 result.SetStatus(eReturnStatusFailed); 603 return false; 604 } 605 606 if (argc == 2) { 607 lldb::addr_t end_addr = OptionArgParser::ToAddress( 608 &m_exe_ctx, command[1].ref(), LLDB_INVALID_ADDRESS, nullptr); 609 if (end_addr == LLDB_INVALID_ADDRESS) { 610 result.AppendError("invalid end address expression."); 611 result.AppendError(error.AsCString()); 612 result.SetStatus(eReturnStatusFailed); 613 return false; 614 } else if (end_addr <= addr) { 615 result.AppendErrorWithFormat( 616 "end address (0x%" PRIx64 617 ") must be greater that the start address (0x%" PRIx64 ").\n", 618 end_addr, addr); 619 result.SetStatus(eReturnStatusFailed); 620 return false; 621 } else if (m_format_options.GetCountValue().OptionWasSet()) { 622 result.AppendErrorWithFormat( 623 "specify either the end address (0x%" PRIx64 624 ") or the count (--count %" PRIu64 "), not both.\n", 625 end_addr, (uint64_t)item_count); 626 result.SetStatus(eReturnStatusFailed); 627 return false; 628 } 629 630 total_byte_size = end_addr - addr; 631 item_count = total_byte_size / item_byte_size; 632 } 633 634 uint32_t max_unforced_size = target->GetMaximumMemReadSize(); 635 636 if (total_byte_size > max_unforced_size && !m_memory_options.m_force) { 637 result.AppendErrorWithFormat( 638 "Normally, \'memory read\' will not read over %" PRIu32 639 " bytes of data.\n", 640 max_unforced_size); 641 result.AppendErrorWithFormat( 642 "Please use --force to override this restriction just once.\n"); 643 result.AppendErrorWithFormat("or set target.max-memory-read-size if you " 644 "will often need a larger limit.\n"); 645 return false; 646 } 647 648 DataBufferSP data_sp; 649 size_t bytes_read = 0; 650 if (compiler_type.GetOpaqueQualType()) { 651 // Make sure we don't display our type as ASCII bytes like the default 652 // memory read 653 if (!m_format_options.GetFormatValue().OptionWasSet()) 654 m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault); 655 656 llvm::Optional<uint64_t> size = compiler_type.GetByteSize(nullptr); 657 if (!size) { 658 result.AppendError("can't get size of type"); 659 return false; 660 } 661 bytes_read = *size * m_format_options.GetCountValue().GetCurrentValue(); 662 663 if (argc > 0) 664 addr = addr + (*size * m_memory_options.m_offset.GetCurrentValue()); 665 } else if (m_format_options.GetFormatValue().GetCurrentValue() != 666 eFormatCString) { 667 data_sp = std::make_shared<DataBufferHeap>(total_byte_size, '\0'); 668 if (data_sp->GetBytes() == nullptr) { 669 result.AppendErrorWithFormat( 670 "can't allocate 0x%" PRIx32 671 " bytes for the memory read buffer, specify a smaller size to read", 672 (uint32_t)total_byte_size); 673 result.SetStatus(eReturnStatusFailed); 674 return false; 675 } 676 677 Address address(addr, nullptr); 678 bytes_read = target->ReadMemory(address, false, data_sp->GetBytes(), 679 data_sp->GetByteSize(), error); 680 if (bytes_read == 0) { 681 const char *error_cstr = error.AsCString(); 682 if (error_cstr && error_cstr[0]) { 683 result.AppendError(error_cstr); 684 } else { 685 result.AppendErrorWithFormat( 686 "failed to read memory from 0x%" PRIx64 ".\n", addr); 687 } 688 result.SetStatus(eReturnStatusFailed); 689 return false; 690 } 691 692 if (bytes_read < total_byte_size) 693 result.AppendWarningWithFormat( 694 "Not all bytes (%" PRIu64 "/%" PRIu64 695 ") were able to be read from 0x%" PRIx64 ".\n", 696 (uint64_t)bytes_read, (uint64_t)total_byte_size, addr); 697 } else { 698 // we treat c-strings as a special case because they do not have a fixed 699 // size 700 if (m_format_options.GetByteSizeValue().OptionWasSet() && 701 !m_format_options.HasGDBFormat()) 702 item_byte_size = m_format_options.GetByteSizeValue().GetCurrentValue(); 703 else 704 item_byte_size = target->GetMaximumSizeOfStringSummary(); 705 if (!m_format_options.GetCountValue().OptionWasSet()) 706 item_count = 1; 707 data_sp = std::make_shared<DataBufferHeap>( 708 (item_byte_size + 1) * item_count, 709 '\0'); // account for NULLs as necessary 710 if (data_sp->GetBytes() == nullptr) { 711 result.AppendErrorWithFormat( 712 "can't allocate 0x%" PRIx64 713 " bytes for the memory read buffer, specify a smaller size to read", 714 (uint64_t)((item_byte_size + 1) * item_count)); 715 result.SetStatus(eReturnStatusFailed); 716 return false; 717 } 718 uint8_t *data_ptr = data_sp->GetBytes(); 719 auto data_addr = addr; 720 auto count = item_count; 721 item_count = 0; 722 bool break_on_no_NULL = false; 723 while (item_count < count) { 724 std::string buffer; 725 buffer.resize(item_byte_size + 1, 0); 726 Status error; 727 size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0], 728 item_byte_size + 1, error); 729 if (error.Fail()) { 730 result.AppendErrorWithFormat( 731 "failed to read memory from 0x%" PRIx64 ".\n", addr); 732 result.SetStatus(eReturnStatusFailed); 733 return false; 734 } 735 736 if (item_byte_size == read) { 737 result.AppendWarningWithFormat( 738 "unable to find a NULL terminated string at 0x%" PRIx64 739 ".Consider increasing the maximum read length.\n", 740 data_addr); 741 --read; 742 break_on_no_NULL = true; 743 } else 744 ++read; // account for final NULL byte 745 746 memcpy(data_ptr, &buffer[0], read); 747 data_ptr += read; 748 data_addr += read; 749 bytes_read += read; 750 item_count++; // if we break early we know we only read item_count 751 // strings 752 753 if (break_on_no_NULL) 754 break; 755 } 756 data_sp = 757 std::make_shared<DataBufferHeap>(data_sp->GetBytes(), bytes_read + 1); 758 } 759 760 m_next_addr = addr + bytes_read; 761 m_prev_byte_size = bytes_read; 762 m_prev_format_options = m_format_options; 763 m_prev_memory_options = m_memory_options; 764 m_prev_outfile_options = m_outfile_options; 765 m_prev_varobj_options = m_varobj_options; 766 m_prev_compiler_type = compiler_type; 767 768 std::unique_ptr<Stream> output_stream_storage; 769 Stream *output_stream_p = nullptr; 770 const FileSpec &outfile_spec = 771 m_outfile_options.GetFile().GetCurrentValue(); 772 773 std::string path = outfile_spec.GetPath(); 774 if (outfile_spec) { 775 776 uint32_t open_options = 777 File::eOpenOptionWrite | File::eOpenOptionCanCreate; 778 const bool append = m_outfile_options.GetAppend().GetCurrentValue(); 779 if (append) 780 open_options |= File::eOpenOptionAppend; 781 782 auto outfile = FileSystem::Instance().Open(outfile_spec, open_options); 783 784 if (outfile) { 785 auto outfile_stream_up = 786 std::make_unique<StreamFile>(std::move(outfile.get())); 787 if (m_memory_options.m_output_as_binary) { 788 const size_t bytes_written = 789 outfile_stream_up->Write(data_sp->GetBytes(), bytes_read); 790 if (bytes_written > 0) { 791 result.GetOutputStream().Printf( 792 "%zi bytes %s to '%s'\n", bytes_written, 793 append ? "appended" : "written", path.c_str()); 794 return true; 795 } else { 796 result.AppendErrorWithFormat("Failed to write %" PRIu64 797 " bytes to '%s'.\n", 798 (uint64_t)bytes_read, path.c_str()); 799 result.SetStatus(eReturnStatusFailed); 800 return false; 801 } 802 } else { 803 // We are going to write ASCII to the file just point the 804 // output_stream to our outfile_stream... 805 output_stream_storage = std::move(outfile_stream_up); 806 output_stream_p = output_stream_storage.get(); 807 } 808 } else { 809 result.AppendErrorWithFormat("Failed to open file '%s' for %s:\n", 810 path.c_str(), append ? "append" : "write"); 811 812 result.AppendError(llvm::toString(outfile.takeError())); 813 result.SetStatus(eReturnStatusFailed); 814 return false; 815 } 816 } else { 817 output_stream_p = &result.GetOutputStream(); 818 } 819 820 ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope(); 821 if (compiler_type.GetOpaqueQualType()) { 822 for (uint32_t i = 0; i < item_count; ++i) { 823 addr_t item_addr = addr + (i * item_byte_size); 824 Address address(item_addr); 825 StreamString name_strm; 826 name_strm.Printf("0x%" PRIx64, item_addr); 827 ValueObjectSP valobj_sp(ValueObjectMemory::Create( 828 exe_scope, name_strm.GetString(), address, compiler_type)); 829 if (valobj_sp) { 830 Format format = m_format_options.GetFormat(); 831 if (format != eFormatDefault) 832 valobj_sp->SetFormat(format); 833 834 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions( 835 eLanguageRuntimeDescriptionDisplayVerbosityFull, format)); 836 837 valobj_sp->Dump(*output_stream_p, options); 838 } else { 839 result.AppendErrorWithFormat( 840 "failed to create a value object for: (%s) %s\n", 841 view_as_type_cstr, name_strm.GetData()); 842 result.SetStatus(eReturnStatusFailed); 843 return false; 844 } 845 } 846 return true; 847 } 848 849 result.SetStatus(eReturnStatusSuccessFinishResult); 850 DataExtractor data(data_sp, target->GetArchitecture().GetByteOrder(), 851 target->GetArchitecture().GetAddressByteSize(), 852 target->GetArchitecture().GetDataByteSize()); 853 854 Format format = m_format_options.GetFormat(); 855 if (((format == eFormatChar) || (format == eFormatCharPrintable)) && 856 (item_byte_size != 1)) { 857 // if a count was not passed, or it is 1 858 if (!m_format_options.GetCountValue().OptionWasSet() || item_count == 1) { 859 // this turns requests such as 860 // memory read -fc -s10 -c1 *charPtrPtr 861 // which make no sense (what is a char of size 10?) into a request for 862 // fetching 10 chars of size 1 from the same memory location 863 format = eFormatCharArray; 864 item_count = item_byte_size; 865 item_byte_size = 1; 866 } else { 867 // here we passed a count, and it was not 1 so we have a byte_size and 868 // a count we could well multiply those, but instead let's just fail 869 result.AppendErrorWithFormat( 870 "reading memory as characters of size %" PRIu64 " is not supported", 871 (uint64_t)item_byte_size); 872 result.SetStatus(eReturnStatusFailed); 873 return false; 874 } 875 } 876 877 assert(output_stream_p); 878 size_t bytes_dumped = DumpDataExtractor( 879 data, output_stream_p, 0, format, item_byte_size, item_count, 880 num_per_line / target->GetArchitecture().GetDataByteSize(), addr, 0, 0, 881 exe_scope); 882 m_next_addr = addr + bytes_dumped; 883 output_stream_p->EOL(); 884 return true; 885 } 886 887 OptionGroupOptions m_option_group; 888 OptionGroupFormat m_format_options; 889 OptionGroupReadMemory m_memory_options; 890 OptionGroupOutputFile m_outfile_options; 891 OptionGroupValueObjectDisplay m_varobj_options; 892 lldb::addr_t m_next_addr; 893 lldb::addr_t m_prev_byte_size; 894 OptionGroupFormat m_prev_format_options; 895 OptionGroupReadMemory m_prev_memory_options; 896 OptionGroupOutputFile m_prev_outfile_options; 897 OptionGroupValueObjectDisplay m_prev_varobj_options; 898 CompilerType m_prev_compiler_type; 899 }; 900 901 #define LLDB_OPTIONS_memory_find 902 #include "CommandOptions.inc" 903 904 // Find the specified data in memory 905 class CommandObjectMemoryFind : public CommandObjectParsed { 906 public: 907 class OptionGroupFindMemory : public OptionGroup { 908 public: 909 OptionGroupFindMemory() : OptionGroup(), m_count(1), m_offset(0) {} 910 911 ~OptionGroupFindMemory() override = default; 912 913 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 914 return llvm::makeArrayRef(g_memory_find_options); 915 } 916 917 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, 918 ExecutionContext *execution_context) override { 919 Status error; 920 const int short_option = g_memory_find_options[option_idx].short_option; 921 922 switch (short_option) { 923 case 'e': 924 m_expr.SetValueFromString(option_value); 925 break; 926 927 case 's': 928 m_string.SetValueFromString(option_value); 929 break; 930 931 case 'c': 932 if (m_count.SetValueFromString(option_value).Fail()) 933 error.SetErrorString("unrecognized value for count"); 934 break; 935 936 case 'o': 937 if (m_offset.SetValueFromString(option_value).Fail()) 938 error.SetErrorString("unrecognized value for dump-offset"); 939 break; 940 941 default: 942 llvm_unreachable("Unimplemented option"); 943 } 944 return error; 945 } 946 947 void OptionParsingStarting(ExecutionContext *execution_context) override { 948 m_expr.Clear(); 949 m_string.Clear(); 950 m_count.Clear(); 951 } 952 953 OptionValueString m_expr; 954 OptionValueString m_string; 955 OptionValueUInt64 m_count; 956 OptionValueUInt64 m_offset; 957 }; 958 959 CommandObjectMemoryFind(CommandInterpreter &interpreter) 960 : CommandObjectParsed( 961 interpreter, "memory find", 962 "Find a value in the memory of the current target process.", 963 nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched), 964 m_option_group(), m_memory_options() { 965 CommandArgumentEntry arg1; 966 CommandArgumentEntry arg2; 967 CommandArgumentData addr_arg; 968 CommandArgumentData value_arg; 969 970 // Define the first (and only) variant of this arg. 971 addr_arg.arg_type = eArgTypeAddressOrExpression; 972 addr_arg.arg_repetition = eArgRepeatPlain; 973 974 // There is only one variant this argument could be; put it into the 975 // argument entry. 976 arg1.push_back(addr_arg); 977 978 // Define the first (and only) variant of this arg. 979 value_arg.arg_type = eArgTypeAddressOrExpression; 980 value_arg.arg_repetition = eArgRepeatPlain; 981 982 // There is only one variant this argument could be; put it into the 983 // argument entry. 984 arg2.push_back(value_arg); 985 986 // Push the data for the first argument into the m_arguments vector. 987 m_arguments.push_back(arg1); 988 m_arguments.push_back(arg2); 989 990 m_option_group.Append(&m_memory_options); 991 m_option_group.Finalize(); 992 } 993 994 ~CommandObjectMemoryFind() override = default; 995 996 Options *GetOptions() override { return &m_option_group; } 997 998 protected: 999 class ProcessMemoryIterator { 1000 public: 1001 ProcessMemoryIterator(ProcessSP process_sp, lldb::addr_t base) 1002 : m_process_sp(process_sp), m_base_addr(base), m_is_valid(true) { 1003 lldbassert(process_sp.get() != nullptr); 1004 } 1005 1006 bool IsValid() { return m_is_valid; } 1007 1008 uint8_t operator[](lldb::addr_t offset) { 1009 if (!IsValid()) 1010 return 0; 1011 1012 uint8_t retval = 0; 1013 Status error; 1014 if (0 == 1015 m_process_sp->ReadMemory(m_base_addr + offset, &retval, 1, error)) { 1016 m_is_valid = false; 1017 return 0; 1018 } 1019 1020 return retval; 1021 } 1022 1023 private: 1024 ProcessSP m_process_sp; 1025 lldb::addr_t m_base_addr; 1026 bool m_is_valid; 1027 }; 1028 bool DoExecute(Args &command, CommandReturnObject &result) override { 1029 // No need to check "process" for validity as eCommandRequiresProcess 1030 // ensures it is valid 1031 Process *process = m_exe_ctx.GetProcessPtr(); 1032 1033 const size_t argc = command.GetArgumentCount(); 1034 1035 if (argc != 2) { 1036 result.AppendError("two addresses needed for memory find"); 1037 return false; 1038 } 1039 1040 Status error; 1041 lldb::addr_t low_addr = OptionArgParser::ToAddress( 1042 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error); 1043 if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) { 1044 result.AppendError("invalid low address"); 1045 return false; 1046 } 1047 lldb::addr_t high_addr = OptionArgParser::ToAddress( 1048 &m_exe_ctx, command[1].ref(), LLDB_INVALID_ADDRESS, &error); 1049 if (high_addr == LLDB_INVALID_ADDRESS || error.Fail()) { 1050 result.AppendError("invalid high address"); 1051 return false; 1052 } 1053 1054 if (high_addr <= low_addr) { 1055 result.AppendError( 1056 "starting address must be smaller than ending address"); 1057 return false; 1058 } 1059 1060 lldb::addr_t found_location = LLDB_INVALID_ADDRESS; 1061 1062 DataBufferHeap buffer; 1063 1064 if (m_memory_options.m_string.OptionWasSet()) 1065 buffer.CopyData(m_memory_options.m_string.GetStringValue()); 1066 else if (m_memory_options.m_expr.OptionWasSet()) { 1067 StackFrame *frame = m_exe_ctx.GetFramePtr(); 1068 ValueObjectSP result_sp; 1069 if ((eExpressionCompleted == 1070 process->GetTarget().EvaluateExpression( 1071 m_memory_options.m_expr.GetStringValue(), frame, result_sp)) && 1072 result_sp) { 1073 uint64_t value = result_sp->GetValueAsUnsigned(0); 1074 llvm::Optional<uint64_t> size = 1075 result_sp->GetCompilerType().GetByteSize(nullptr); 1076 if (!size) 1077 return false; 1078 switch (*size) { 1079 case 1: { 1080 uint8_t byte = (uint8_t)value; 1081 buffer.CopyData(&byte, 1); 1082 } break; 1083 case 2: { 1084 uint16_t word = (uint16_t)value; 1085 buffer.CopyData(&word, 2); 1086 } break; 1087 case 4: { 1088 uint32_t lword = (uint32_t)value; 1089 buffer.CopyData(&lword, 4); 1090 } break; 1091 case 8: { 1092 buffer.CopyData(&value, 8); 1093 } break; 1094 case 3: 1095 case 5: 1096 case 6: 1097 case 7: 1098 result.AppendError("unknown type. pass a string instead"); 1099 return false; 1100 default: 1101 result.AppendError( 1102 "result size larger than 8 bytes. pass a string instead"); 1103 return false; 1104 } 1105 } else { 1106 result.AppendError( 1107 "expression evaluation failed. pass a string instead"); 1108 return false; 1109 } 1110 } else { 1111 result.AppendError( 1112 "please pass either a block of text, or an expression to evaluate."); 1113 return false; 1114 } 1115 1116 size_t count = m_memory_options.m_count.GetCurrentValue(); 1117 found_location = low_addr; 1118 bool ever_found = false; 1119 while (count) { 1120 found_location = FastSearch(found_location, high_addr, buffer.GetBytes(), 1121 buffer.GetByteSize()); 1122 if (found_location == LLDB_INVALID_ADDRESS) { 1123 if (!ever_found) { 1124 result.AppendMessage("data not found within the range.\n"); 1125 result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult); 1126 } else 1127 result.AppendMessage("no more matches within the range.\n"); 1128 break; 1129 } 1130 result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n", 1131 found_location); 1132 1133 DataBufferHeap dumpbuffer(32, 0); 1134 process->ReadMemory( 1135 found_location + m_memory_options.m_offset.GetCurrentValue(), 1136 dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error); 1137 if (!error.Fail()) { 1138 DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), 1139 process->GetByteOrder(), 1140 process->GetAddressByteSize()); 1141 DumpDataExtractor( 1142 data, &result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1, 1143 dumpbuffer.GetByteSize(), 16, 1144 found_location + m_memory_options.m_offset.GetCurrentValue(), 0, 0); 1145 result.GetOutputStream().EOL(); 1146 } 1147 1148 --count; 1149 found_location++; 1150 ever_found = true; 1151 } 1152 1153 result.SetStatus(lldb::eReturnStatusSuccessFinishResult); 1154 return true; 1155 } 1156 1157 lldb::addr_t FastSearch(lldb::addr_t low, lldb::addr_t high, uint8_t *buffer, 1158 size_t buffer_size) { 1159 const size_t region_size = high - low; 1160 1161 if (region_size < buffer_size) 1162 return LLDB_INVALID_ADDRESS; 1163 1164 std::vector<size_t> bad_char_heuristic(256, buffer_size); 1165 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1166 ProcessMemoryIterator iterator(process_sp, low); 1167 1168 for (size_t idx = 0; idx < buffer_size - 1; idx++) { 1169 decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx]; 1170 bad_char_heuristic[bcu_idx] = buffer_size - idx - 1; 1171 } 1172 for (size_t s = 0; s <= (region_size - buffer_size);) { 1173 int64_t j = buffer_size - 1; 1174 while (j >= 0 && buffer[j] == iterator[s + j]) 1175 j--; 1176 if (j < 0) 1177 return low + s; 1178 else 1179 s += bad_char_heuristic[iterator[s + buffer_size - 1]]; 1180 } 1181 1182 return LLDB_INVALID_ADDRESS; 1183 } 1184 1185 OptionGroupOptions m_option_group; 1186 OptionGroupFindMemory m_memory_options; 1187 }; 1188 1189 #define LLDB_OPTIONS_memory_write 1190 #include "CommandOptions.inc" 1191 1192 // Write memory to the inferior process 1193 class CommandObjectMemoryWrite : public CommandObjectParsed { 1194 public: 1195 class OptionGroupWriteMemory : public OptionGroup { 1196 public: 1197 OptionGroupWriteMemory() : OptionGroup() {} 1198 1199 ~OptionGroupWriteMemory() override = default; 1200 1201 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 1202 return llvm::makeArrayRef(g_memory_write_options); 1203 } 1204 1205 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, 1206 ExecutionContext *execution_context) override { 1207 Status error; 1208 const int short_option = g_memory_write_options[option_idx].short_option; 1209 1210 switch (short_option) { 1211 case 'i': 1212 m_infile.SetFile(option_value, FileSpec::Style::native); 1213 FileSystem::Instance().Resolve(m_infile); 1214 if (!FileSystem::Instance().Exists(m_infile)) { 1215 m_infile.Clear(); 1216 error.SetErrorStringWithFormat("input file does not exist: '%s'", 1217 option_value.str().c_str()); 1218 } 1219 break; 1220 1221 case 'o': { 1222 if (option_value.getAsInteger(0, m_infile_offset)) { 1223 m_infile_offset = 0; 1224 error.SetErrorStringWithFormat("invalid offset string '%s'", 1225 option_value.str().c_str()); 1226 } 1227 } break; 1228 1229 default: 1230 llvm_unreachable("Unimplemented option"); 1231 } 1232 return error; 1233 } 1234 1235 void OptionParsingStarting(ExecutionContext *execution_context) override { 1236 m_infile.Clear(); 1237 m_infile_offset = 0; 1238 } 1239 1240 FileSpec m_infile; 1241 off_t m_infile_offset; 1242 }; 1243 1244 CommandObjectMemoryWrite(CommandInterpreter &interpreter) 1245 : CommandObjectParsed( 1246 interpreter, "memory write", 1247 "Write to the memory of the current target process.", nullptr, 1248 eCommandRequiresProcess | eCommandProcessMustBeLaunched), 1249 m_option_group(), m_format_options(eFormatBytes, 1, UINT64_MAX), 1250 m_memory_options() { 1251 CommandArgumentEntry arg1; 1252 CommandArgumentEntry arg2; 1253 CommandArgumentData addr_arg; 1254 CommandArgumentData value_arg; 1255 1256 // Define the first (and only) variant of this arg. 1257 addr_arg.arg_type = eArgTypeAddress; 1258 addr_arg.arg_repetition = eArgRepeatPlain; 1259 1260 // There is only one variant this argument could be; put it into the 1261 // argument entry. 1262 arg1.push_back(addr_arg); 1263 1264 // Define the first (and only) variant of this arg. 1265 value_arg.arg_type = eArgTypeValue; 1266 value_arg.arg_repetition = eArgRepeatPlus; 1267 1268 // There is only one variant this argument could be; put it into the 1269 // argument entry. 1270 arg2.push_back(value_arg); 1271 1272 // Push the data for the first argument into the m_arguments vector. 1273 m_arguments.push_back(arg1); 1274 m_arguments.push_back(arg2); 1275 1276 m_option_group.Append(&m_format_options, 1277 OptionGroupFormat::OPTION_GROUP_FORMAT, 1278 LLDB_OPT_SET_1); 1279 m_option_group.Append(&m_format_options, 1280 OptionGroupFormat::OPTION_GROUP_SIZE, 1281 LLDB_OPT_SET_1 | LLDB_OPT_SET_2); 1282 m_option_group.Append(&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2); 1283 m_option_group.Finalize(); 1284 } 1285 1286 ~CommandObjectMemoryWrite() override = default; 1287 1288 Options *GetOptions() override { return &m_option_group; } 1289 1290 bool UIntValueIsValidForSize(uint64_t uval64, size_t total_byte_size) { 1291 if (total_byte_size > 8) 1292 return false; 1293 1294 if (total_byte_size == 8) 1295 return true; 1296 1297 const uint64_t max = ((uint64_t)1 << (uint64_t)(total_byte_size * 8)) - 1; 1298 return uval64 <= max; 1299 } 1300 1301 bool SIntValueIsValidForSize(int64_t sval64, size_t total_byte_size) { 1302 if (total_byte_size > 8) 1303 return false; 1304 1305 if (total_byte_size == 8) 1306 return true; 1307 1308 const int64_t max = ((int64_t)1 << (uint64_t)(total_byte_size * 8 - 1)) - 1; 1309 const int64_t min = ~(max); 1310 return min <= sval64 && sval64 <= max; 1311 } 1312 1313 protected: 1314 bool DoExecute(Args &command, CommandReturnObject &result) override { 1315 // No need to check "process" for validity as eCommandRequiresProcess 1316 // ensures it is valid 1317 Process *process = m_exe_ctx.GetProcessPtr(); 1318 1319 const size_t argc = command.GetArgumentCount(); 1320 1321 if (m_memory_options.m_infile) { 1322 if (argc < 1) { 1323 result.AppendErrorWithFormat( 1324 "%s takes a destination address when writing file contents.\n", 1325 m_cmd_name.c_str()); 1326 result.SetStatus(eReturnStatusFailed); 1327 return false; 1328 } 1329 } else if (argc < 2) { 1330 result.AppendErrorWithFormat( 1331 "%s takes a destination address and at least one value.\n", 1332 m_cmd_name.c_str()); 1333 result.SetStatus(eReturnStatusFailed); 1334 return false; 1335 } 1336 1337 StreamString buffer( 1338 Stream::eBinary, 1339 process->GetTarget().GetArchitecture().GetAddressByteSize(), 1340 process->GetTarget().GetArchitecture().GetByteOrder()); 1341 1342 OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue(); 1343 size_t item_byte_size = byte_size_value.GetCurrentValue(); 1344 1345 Status error; 1346 lldb::addr_t addr = OptionArgParser::ToAddress( 1347 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error); 1348 1349 if (addr == LLDB_INVALID_ADDRESS) { 1350 result.AppendError("invalid address expression\n"); 1351 result.AppendError(error.AsCString()); 1352 result.SetStatus(eReturnStatusFailed); 1353 return false; 1354 } 1355 1356 if (m_memory_options.m_infile) { 1357 size_t length = SIZE_MAX; 1358 if (item_byte_size > 1) 1359 length = item_byte_size; 1360 auto data_sp = FileSystem::Instance().CreateDataBuffer( 1361 m_memory_options.m_infile.GetPath(), length, 1362 m_memory_options.m_infile_offset); 1363 if (data_sp) { 1364 length = data_sp->GetByteSize(); 1365 if (length > 0) { 1366 Status error; 1367 size_t bytes_written = 1368 process->WriteMemory(addr, data_sp->GetBytes(), length, error); 1369 1370 if (bytes_written == length) { 1371 // All bytes written 1372 result.GetOutputStream().Printf( 1373 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n", 1374 (uint64_t)bytes_written, addr); 1375 result.SetStatus(eReturnStatusSuccessFinishResult); 1376 } else if (bytes_written > 0) { 1377 // Some byte written 1378 result.GetOutputStream().Printf( 1379 "%" PRIu64 " bytes of %" PRIu64 1380 " requested were written to 0x%" PRIx64 "\n", 1381 (uint64_t)bytes_written, (uint64_t)length, addr); 1382 result.SetStatus(eReturnStatusSuccessFinishResult); 1383 } else { 1384 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 1385 " failed: %s.\n", 1386 addr, error.AsCString()); 1387 result.SetStatus(eReturnStatusFailed); 1388 } 1389 } 1390 } else { 1391 result.AppendErrorWithFormat("Unable to read contents of file.\n"); 1392 result.SetStatus(eReturnStatusFailed); 1393 } 1394 return result.Succeeded(); 1395 } else if (item_byte_size == 0) { 1396 if (m_format_options.GetFormat() == eFormatPointer) 1397 item_byte_size = buffer.GetAddressByteSize(); 1398 else 1399 item_byte_size = 1; 1400 } 1401 1402 command.Shift(); // shift off the address argument 1403 uint64_t uval64; 1404 int64_t sval64; 1405 bool success = false; 1406 for (auto &entry : command) { 1407 switch (m_format_options.GetFormat()) { 1408 case kNumFormats: 1409 case eFormatFloat: // TODO: add support for floats soon 1410 case eFormatCharPrintable: 1411 case eFormatBytesWithASCII: 1412 case eFormatComplex: 1413 case eFormatEnum: 1414 case eFormatUnicode8: 1415 case eFormatUnicode16: 1416 case eFormatUnicode32: 1417 case eFormatVectorOfChar: 1418 case eFormatVectorOfSInt8: 1419 case eFormatVectorOfUInt8: 1420 case eFormatVectorOfSInt16: 1421 case eFormatVectorOfUInt16: 1422 case eFormatVectorOfSInt32: 1423 case eFormatVectorOfUInt32: 1424 case eFormatVectorOfSInt64: 1425 case eFormatVectorOfUInt64: 1426 case eFormatVectorOfFloat16: 1427 case eFormatVectorOfFloat32: 1428 case eFormatVectorOfFloat64: 1429 case eFormatVectorOfUInt128: 1430 case eFormatOSType: 1431 case eFormatComplexInteger: 1432 case eFormatAddressInfo: 1433 case eFormatHexFloat: 1434 case eFormatInstruction: 1435 case eFormatVoid: 1436 result.AppendError("unsupported format for writing memory"); 1437 result.SetStatus(eReturnStatusFailed); 1438 return false; 1439 1440 case eFormatDefault: 1441 case eFormatBytes: 1442 case eFormatHex: 1443 case eFormatHexUppercase: 1444 case eFormatPointer: 1445 { 1446 // Decode hex bytes 1447 // Be careful, getAsInteger with a radix of 16 rejects "0xab" so we 1448 // have to special case that: 1449 bool success = false; 1450 if (entry.ref().startswith("0x")) 1451 success = !entry.ref().getAsInteger(0, uval64); 1452 if (!success) 1453 success = !entry.ref().getAsInteger(16, uval64); 1454 if (!success) { 1455 result.AppendErrorWithFormat( 1456 "'%s' is not a valid hex string value.\n", entry.c_str()); 1457 result.SetStatus(eReturnStatusFailed); 1458 return false; 1459 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { 1460 result.AppendErrorWithFormat("Value 0x%" PRIx64 1461 " is too large to fit in a %" PRIu64 1462 " byte unsigned integer value.\n", 1463 uval64, (uint64_t)item_byte_size); 1464 result.SetStatus(eReturnStatusFailed); 1465 return false; 1466 } 1467 buffer.PutMaxHex64(uval64, item_byte_size); 1468 break; 1469 } 1470 case eFormatBoolean: 1471 uval64 = OptionArgParser::ToBoolean(entry.ref(), false, &success); 1472 if (!success) { 1473 result.AppendErrorWithFormat( 1474 "'%s' is not a valid boolean string value.\n", entry.c_str()); 1475 result.SetStatus(eReturnStatusFailed); 1476 return false; 1477 } 1478 buffer.PutMaxHex64(uval64, item_byte_size); 1479 break; 1480 1481 case eFormatBinary: 1482 if (entry.ref().getAsInteger(2, uval64)) { 1483 result.AppendErrorWithFormat( 1484 "'%s' is not a valid binary string value.\n", entry.c_str()); 1485 result.SetStatus(eReturnStatusFailed); 1486 return false; 1487 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { 1488 result.AppendErrorWithFormat("Value 0x%" PRIx64 1489 " is too large to fit in a %" PRIu64 1490 " byte unsigned integer value.\n", 1491 uval64, (uint64_t)item_byte_size); 1492 result.SetStatus(eReturnStatusFailed); 1493 return false; 1494 } 1495 buffer.PutMaxHex64(uval64, item_byte_size); 1496 break; 1497 1498 case eFormatCharArray: 1499 case eFormatChar: 1500 case eFormatCString: { 1501 if (entry.ref().empty()) 1502 break; 1503 1504 size_t len = entry.ref().size(); 1505 // Include the NULL for C strings... 1506 if (m_format_options.GetFormat() == eFormatCString) 1507 ++len; 1508 Status error; 1509 if (process->WriteMemory(addr, entry.c_str(), len, error) == len) { 1510 addr += len; 1511 } else { 1512 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 1513 " failed: %s.\n", 1514 addr, error.AsCString()); 1515 result.SetStatus(eReturnStatusFailed); 1516 return false; 1517 } 1518 break; 1519 } 1520 case eFormatDecimal: 1521 if (entry.ref().getAsInteger(0, sval64)) { 1522 result.AppendErrorWithFormat( 1523 "'%s' is not a valid signed decimal value.\n", entry.c_str()); 1524 result.SetStatus(eReturnStatusFailed); 1525 return false; 1526 } else if (!SIntValueIsValidForSize(sval64, item_byte_size)) { 1527 result.AppendErrorWithFormat( 1528 "Value %" PRIi64 " is too large or small to fit in a %" PRIu64 1529 " byte signed integer value.\n", 1530 sval64, (uint64_t)item_byte_size); 1531 result.SetStatus(eReturnStatusFailed); 1532 return false; 1533 } 1534 buffer.PutMaxHex64(sval64, item_byte_size); 1535 break; 1536 1537 case eFormatUnsigned: 1538 1539 if (!entry.ref().getAsInteger(0, uval64)) { 1540 result.AppendErrorWithFormat( 1541 "'%s' is not a valid unsigned decimal string value.\n", 1542 entry.c_str()); 1543 result.SetStatus(eReturnStatusFailed); 1544 return false; 1545 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { 1546 result.AppendErrorWithFormat("Value %" PRIu64 1547 " is too large to fit in a %" PRIu64 1548 " byte unsigned integer value.\n", 1549 uval64, (uint64_t)item_byte_size); 1550 result.SetStatus(eReturnStatusFailed); 1551 return false; 1552 } 1553 buffer.PutMaxHex64(uval64, item_byte_size); 1554 break; 1555 1556 case eFormatOctal: 1557 if (entry.ref().getAsInteger(8, uval64)) { 1558 result.AppendErrorWithFormat( 1559 "'%s' is not a valid octal string value.\n", entry.c_str()); 1560 result.SetStatus(eReturnStatusFailed); 1561 return false; 1562 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { 1563 result.AppendErrorWithFormat("Value %" PRIo64 1564 " is too large to fit in a %" PRIu64 1565 " byte unsigned integer value.\n", 1566 uval64, (uint64_t)item_byte_size); 1567 result.SetStatus(eReturnStatusFailed); 1568 return false; 1569 } 1570 buffer.PutMaxHex64(uval64, item_byte_size); 1571 break; 1572 } 1573 } 1574 1575 if (!buffer.GetString().empty()) { 1576 Status error; 1577 if (process->WriteMemory(addr, buffer.GetString().data(), 1578 buffer.GetString().size(), 1579 error) == buffer.GetString().size()) 1580 return true; 1581 else { 1582 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 1583 " failed: %s.\n", 1584 addr, error.AsCString()); 1585 result.SetStatus(eReturnStatusFailed); 1586 return false; 1587 } 1588 } 1589 return true; 1590 } 1591 1592 OptionGroupOptions m_option_group; 1593 OptionGroupFormat m_format_options; 1594 OptionGroupWriteMemory m_memory_options; 1595 }; 1596 1597 // Get malloc/free history of a memory address. 1598 class CommandObjectMemoryHistory : public CommandObjectParsed { 1599 public: 1600 CommandObjectMemoryHistory(CommandInterpreter &interpreter) 1601 : CommandObjectParsed( 1602 interpreter, "memory history", "Print recorded stack traces for " 1603 "allocation/deallocation events " 1604 "associated with an address.", 1605 nullptr, 1606 eCommandRequiresTarget | eCommandRequiresProcess | 1607 eCommandProcessMustBePaused | eCommandProcessMustBeLaunched) { 1608 CommandArgumentEntry arg1; 1609 CommandArgumentData addr_arg; 1610 1611 // Define the first (and only) variant of this arg. 1612 addr_arg.arg_type = eArgTypeAddress; 1613 addr_arg.arg_repetition = eArgRepeatPlain; 1614 1615 // There is only one variant this argument could be; put it into the 1616 // argument entry. 1617 arg1.push_back(addr_arg); 1618 1619 // Push the data for the first argument into the m_arguments vector. 1620 m_arguments.push_back(arg1); 1621 } 1622 1623 ~CommandObjectMemoryHistory() override = default; 1624 1625 const char *GetRepeatCommand(Args ¤t_command_args, 1626 uint32_t index) override { 1627 return m_cmd_name.c_str(); 1628 } 1629 1630 protected: 1631 bool DoExecute(Args &command, CommandReturnObject &result) override { 1632 const size_t argc = command.GetArgumentCount(); 1633 1634 if (argc == 0 || argc > 1) { 1635 result.AppendErrorWithFormat("%s takes an address expression", 1636 m_cmd_name.c_str()); 1637 result.SetStatus(eReturnStatusFailed); 1638 return false; 1639 } 1640 1641 Status error; 1642 lldb::addr_t addr = OptionArgParser::ToAddress( 1643 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error); 1644 1645 if (addr == LLDB_INVALID_ADDRESS) { 1646 result.AppendError("invalid address expression"); 1647 result.AppendError(error.AsCString()); 1648 result.SetStatus(eReturnStatusFailed); 1649 return false; 1650 } 1651 1652 Stream *output_stream = &result.GetOutputStream(); 1653 1654 const ProcessSP &process_sp = m_exe_ctx.GetProcessSP(); 1655 const MemoryHistorySP &memory_history = 1656 MemoryHistory::FindPlugin(process_sp); 1657 1658 if (!memory_history) { 1659 result.AppendError("no available memory history provider"); 1660 result.SetStatus(eReturnStatusFailed); 1661 return false; 1662 } 1663 1664 HistoryThreads thread_list = memory_history->GetHistoryThreads(addr); 1665 1666 const bool stop_format = false; 1667 for (auto thread : thread_list) { 1668 thread->GetStatus(*output_stream, 0, UINT32_MAX, 0, stop_format); 1669 } 1670 1671 result.SetStatus(eReturnStatusSuccessFinishResult); 1672 1673 return true; 1674 } 1675 }; 1676 1677 // CommandObjectMemoryRegion 1678 #pragma mark CommandObjectMemoryRegion 1679 1680 class CommandObjectMemoryRegion : public CommandObjectParsed { 1681 public: 1682 CommandObjectMemoryRegion(CommandInterpreter &interpreter) 1683 : CommandObjectParsed(interpreter, "memory region", 1684 "Get information on the memory region containing " 1685 "an address in the current target process.", 1686 "memory region ADDR", 1687 eCommandRequiresProcess | eCommandTryTargetAPILock | 1688 eCommandProcessMustBeLaunched), 1689 m_prev_end_addr(LLDB_INVALID_ADDRESS) {} 1690 1691 ~CommandObjectMemoryRegion() override = default; 1692 1693 protected: 1694 bool DoExecute(Args &command, CommandReturnObject &result) override { 1695 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1696 if (process_sp) { 1697 Status error; 1698 lldb::addr_t load_addr = m_prev_end_addr; 1699 m_prev_end_addr = LLDB_INVALID_ADDRESS; 1700 1701 const size_t argc = command.GetArgumentCount(); 1702 if (argc > 1 || (argc == 0 && load_addr == LLDB_INVALID_ADDRESS)) { 1703 result.AppendErrorWithFormat("'%s' takes one argument:\nUsage: %s\n", 1704 m_cmd_name.c_str(), m_cmd_syntax.c_str()); 1705 result.SetStatus(eReturnStatusFailed); 1706 } else { 1707 if (command.GetArgumentCount() == 1) { 1708 auto load_addr_str = command[0].ref(); 1709 load_addr = OptionArgParser::ToAddress(&m_exe_ctx, load_addr_str, 1710 LLDB_INVALID_ADDRESS, &error); 1711 if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) { 1712 result.AppendErrorWithFormat( 1713 "invalid address argument \"%s\": %s\n", command[0].c_str(), 1714 error.AsCString()); 1715 result.SetStatus(eReturnStatusFailed); 1716 } 1717 } 1718 1719 lldb_private::MemoryRegionInfo range_info; 1720 error = process_sp->GetMemoryRegionInfo(load_addr, range_info); 1721 if (error.Success()) { 1722 lldb_private::Address addr; 1723 ConstString name = range_info.GetName(); 1724 ConstString section_name; 1725 if (process_sp->GetTarget().ResolveLoadAddress(load_addr, addr)) { 1726 SectionSP section_sp(addr.GetSection()); 1727 if (section_sp) { 1728 // Got the top most section, not the deepest section 1729 while (section_sp->GetParent()) 1730 section_sp = section_sp->GetParent(); 1731 section_name = section_sp->GetName(); 1732 } 1733 } 1734 result.AppendMessageWithFormat( 1735 "[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") %c%c%c%s%s%s%s\n", 1736 range_info.GetRange().GetRangeBase(), 1737 range_info.GetRange().GetRangeEnd(), 1738 range_info.GetReadable() ? 'r' : '-', 1739 range_info.GetWritable() ? 'w' : '-', 1740 range_info.GetExecutable() ? 'x' : '-', 1741 name ? " " : "", name.AsCString(""), 1742 section_name ? " " : "", section_name.AsCString("")); 1743 m_prev_end_addr = range_info.GetRange().GetRangeEnd(); 1744 result.SetStatus(eReturnStatusSuccessFinishResult); 1745 } else { 1746 result.SetStatus(eReturnStatusFailed); 1747 result.AppendErrorWithFormat("%s\n", error.AsCString()); 1748 } 1749 } 1750 } else { 1751 m_prev_end_addr = LLDB_INVALID_ADDRESS; 1752 result.AppendError("invalid process"); 1753 result.SetStatus(eReturnStatusFailed); 1754 } 1755 return result.Succeeded(); 1756 } 1757 1758 const char *GetRepeatCommand(Args ¤t_command_args, 1759 uint32_t index) override { 1760 // If we repeat this command, repeat it without any arguments so we can 1761 // show the next memory range 1762 return m_cmd_name.c_str(); 1763 } 1764 1765 lldb::addr_t m_prev_end_addr; 1766 }; 1767 1768 // CommandObjectMemory 1769 1770 CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter) 1771 : CommandObjectMultiword( 1772 interpreter, "memory", 1773 "Commands for operating on memory in the current target process.", 1774 "memory <subcommand> [<subcommand-options>]") { 1775 LoadSubCommand("find", 1776 CommandObjectSP(new CommandObjectMemoryFind(interpreter))); 1777 LoadSubCommand("read", 1778 CommandObjectSP(new CommandObjectMemoryRead(interpreter))); 1779 LoadSubCommand("write", 1780 CommandObjectSP(new CommandObjectMemoryWrite(interpreter))); 1781 LoadSubCommand("history", 1782 CommandObjectSP(new CommandObjectMemoryHistory(interpreter))); 1783 LoadSubCommand("region", 1784 CommandObjectSP(new CommandObjectMemoryRegion(interpreter))); 1785 } 1786 1787 CommandObjectMemory::~CommandObjectMemory() = default; 1788