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