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