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 ABISP abi = m_exe_ctx.GetProcessPtr()->GetABI(); 1036 if (abi) { 1037 low_addr = abi->FixDataAddress(low_addr); 1038 high_addr = abi->FixDataAddress(high_addr); 1039 } 1040 1041 if (high_addr <= low_addr) { 1042 result.AppendError( 1043 "starting address must be smaller than ending address"); 1044 return false; 1045 } 1046 1047 lldb::addr_t found_location = LLDB_INVALID_ADDRESS; 1048 1049 DataBufferHeap buffer; 1050 1051 if (m_memory_options.m_string.OptionWasSet()) 1052 buffer.CopyData(m_memory_options.m_string.GetStringValue()); 1053 else if (m_memory_options.m_expr.OptionWasSet()) { 1054 StackFrame *frame = m_exe_ctx.GetFramePtr(); 1055 ValueObjectSP result_sp; 1056 if ((eExpressionCompleted == 1057 process->GetTarget().EvaluateExpression( 1058 m_memory_options.m_expr.GetStringValue(), frame, result_sp)) && 1059 result_sp) { 1060 uint64_t value = result_sp->GetValueAsUnsigned(0); 1061 llvm::Optional<uint64_t> size = 1062 result_sp->GetCompilerType().GetByteSize(nullptr); 1063 if (!size) 1064 return false; 1065 switch (*size) { 1066 case 1: { 1067 uint8_t byte = (uint8_t)value; 1068 buffer.CopyData(&byte, 1); 1069 } break; 1070 case 2: { 1071 uint16_t word = (uint16_t)value; 1072 buffer.CopyData(&word, 2); 1073 } break; 1074 case 4: { 1075 uint32_t lword = (uint32_t)value; 1076 buffer.CopyData(&lword, 4); 1077 } break; 1078 case 8: { 1079 buffer.CopyData(&value, 8); 1080 } break; 1081 case 3: 1082 case 5: 1083 case 6: 1084 case 7: 1085 result.AppendError("unknown type. pass a string instead"); 1086 return false; 1087 default: 1088 result.AppendError( 1089 "result size larger than 8 bytes. pass a string instead"); 1090 return false; 1091 } 1092 } else { 1093 result.AppendError( 1094 "expression evaluation failed. pass a string instead"); 1095 return false; 1096 } 1097 } else { 1098 result.AppendError( 1099 "please pass either a block of text, or an expression to evaluate."); 1100 return false; 1101 } 1102 1103 size_t count = m_memory_options.m_count.GetCurrentValue(); 1104 found_location = low_addr; 1105 bool ever_found = false; 1106 while (count) { 1107 found_location = FastSearch(found_location, high_addr, buffer.GetBytes(), 1108 buffer.GetByteSize()); 1109 if (found_location == LLDB_INVALID_ADDRESS) { 1110 if (!ever_found) { 1111 result.AppendMessage("data not found within the range.\n"); 1112 result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult); 1113 } else 1114 result.AppendMessage("no more matches within the range.\n"); 1115 break; 1116 } 1117 result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n", 1118 found_location); 1119 1120 DataBufferHeap dumpbuffer(32, 0); 1121 process->ReadMemory( 1122 found_location + m_memory_options.m_offset.GetCurrentValue(), 1123 dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error); 1124 if (!error.Fail()) { 1125 DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), 1126 process->GetByteOrder(), 1127 process->GetAddressByteSize()); 1128 DumpDataExtractor( 1129 data, &result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1, 1130 dumpbuffer.GetByteSize(), 16, 1131 found_location + m_memory_options.m_offset.GetCurrentValue(), 0, 0); 1132 result.GetOutputStream().EOL(); 1133 } 1134 1135 --count; 1136 found_location++; 1137 ever_found = true; 1138 } 1139 1140 result.SetStatus(lldb::eReturnStatusSuccessFinishResult); 1141 return true; 1142 } 1143 1144 lldb::addr_t FastSearch(lldb::addr_t low, lldb::addr_t high, uint8_t *buffer, 1145 size_t buffer_size) { 1146 const size_t region_size = high - low; 1147 1148 if (region_size < buffer_size) 1149 return LLDB_INVALID_ADDRESS; 1150 1151 std::vector<size_t> bad_char_heuristic(256, buffer_size); 1152 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1153 ProcessMemoryIterator iterator(process_sp, low); 1154 1155 for (size_t idx = 0; idx < buffer_size - 1; idx++) { 1156 decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx]; 1157 bad_char_heuristic[bcu_idx] = buffer_size - idx - 1; 1158 } 1159 for (size_t s = 0; s <= (region_size - buffer_size);) { 1160 int64_t j = buffer_size - 1; 1161 while (j >= 0 && buffer[j] == iterator[s + j]) 1162 j--; 1163 if (j < 0) 1164 return low + s; 1165 else 1166 s += bad_char_heuristic[iterator[s + buffer_size - 1]]; 1167 } 1168 1169 return LLDB_INVALID_ADDRESS; 1170 } 1171 1172 OptionGroupOptions m_option_group; 1173 OptionGroupFindMemory m_memory_options; 1174 }; 1175 1176 #define LLDB_OPTIONS_memory_write 1177 #include "CommandOptions.inc" 1178 1179 // Write memory to the inferior process 1180 class CommandObjectMemoryWrite : public CommandObjectParsed { 1181 public: 1182 class OptionGroupWriteMemory : public OptionGroup { 1183 public: 1184 OptionGroupWriteMemory() {} 1185 1186 ~OptionGroupWriteMemory() override = default; 1187 1188 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 1189 return llvm::makeArrayRef(g_memory_write_options); 1190 } 1191 1192 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, 1193 ExecutionContext *execution_context) override { 1194 Status error; 1195 const int short_option = g_memory_write_options[option_idx].short_option; 1196 1197 switch (short_option) { 1198 case 'i': 1199 m_infile.SetFile(option_value, FileSpec::Style::native); 1200 FileSystem::Instance().Resolve(m_infile); 1201 if (!FileSystem::Instance().Exists(m_infile)) { 1202 m_infile.Clear(); 1203 error.SetErrorStringWithFormat("input file does not exist: '%s'", 1204 option_value.str().c_str()); 1205 } 1206 break; 1207 1208 case 'o': { 1209 if (option_value.getAsInteger(0, m_infile_offset)) { 1210 m_infile_offset = 0; 1211 error.SetErrorStringWithFormat("invalid offset string '%s'", 1212 option_value.str().c_str()); 1213 } 1214 } break; 1215 1216 default: 1217 llvm_unreachable("Unimplemented option"); 1218 } 1219 return error; 1220 } 1221 1222 void OptionParsingStarting(ExecutionContext *execution_context) override { 1223 m_infile.Clear(); 1224 m_infile_offset = 0; 1225 } 1226 1227 FileSpec m_infile; 1228 off_t m_infile_offset; 1229 }; 1230 1231 CommandObjectMemoryWrite(CommandInterpreter &interpreter) 1232 : CommandObjectParsed( 1233 interpreter, "memory write", 1234 "Write to the memory of the current target process.", nullptr, 1235 eCommandRequiresProcess | eCommandProcessMustBeLaunched), 1236 m_format_options( 1237 eFormatBytes, 1, UINT64_MAX, 1238 {std::make_tuple( 1239 eArgTypeFormat, 1240 "The format to use for each of the value to be written."), 1241 std::make_tuple(eArgTypeByteSize, 1242 "The size in bytes to write from input file or " 1243 "each value.")}) { 1244 CommandArgumentEntry arg1; 1245 CommandArgumentEntry arg2; 1246 CommandArgumentData addr_arg; 1247 CommandArgumentData value_arg; 1248 1249 // Define the first (and only) variant of this arg. 1250 addr_arg.arg_type = eArgTypeAddress; 1251 addr_arg.arg_repetition = eArgRepeatPlain; 1252 1253 // There is only one variant this argument could be; put it into the 1254 // argument entry. 1255 arg1.push_back(addr_arg); 1256 1257 // Define the first (and only) variant of this arg. 1258 value_arg.arg_type = eArgTypeValue; 1259 value_arg.arg_repetition = eArgRepeatPlus; 1260 value_arg.arg_opt_set_association = LLDB_OPT_SET_1; 1261 1262 // There is only one variant this argument could be; put it into the 1263 // argument entry. 1264 arg2.push_back(value_arg); 1265 1266 // Push the data for the first argument into the m_arguments vector. 1267 m_arguments.push_back(arg1); 1268 m_arguments.push_back(arg2); 1269 1270 m_option_group.Append(&m_format_options, 1271 OptionGroupFormat::OPTION_GROUP_FORMAT, 1272 LLDB_OPT_SET_1); 1273 m_option_group.Append(&m_format_options, 1274 OptionGroupFormat::OPTION_GROUP_SIZE, 1275 LLDB_OPT_SET_1 | LLDB_OPT_SET_2); 1276 m_option_group.Append(&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2); 1277 m_option_group.Finalize(); 1278 } 1279 1280 ~CommandObjectMemoryWrite() override = default; 1281 1282 Options *GetOptions() override { return &m_option_group; } 1283 1284 protected: 1285 bool DoExecute(Args &command, CommandReturnObject &result) override { 1286 // No need to check "process" for validity as eCommandRequiresProcess 1287 // ensures it is valid 1288 Process *process = m_exe_ctx.GetProcessPtr(); 1289 1290 const size_t argc = command.GetArgumentCount(); 1291 1292 if (m_memory_options.m_infile) { 1293 if (argc < 1) { 1294 result.AppendErrorWithFormat( 1295 "%s takes a destination address when writing file contents.\n", 1296 m_cmd_name.c_str()); 1297 return false; 1298 } 1299 if (argc > 1) { 1300 result.AppendErrorWithFormat( 1301 "%s takes only a destination address when writing file contents.\n", 1302 m_cmd_name.c_str()); 1303 return false; 1304 } 1305 } else if (argc < 2) { 1306 result.AppendErrorWithFormat( 1307 "%s takes a destination address and at least one value.\n", 1308 m_cmd_name.c_str()); 1309 return false; 1310 } 1311 1312 StreamString buffer( 1313 Stream::eBinary, 1314 process->GetTarget().GetArchitecture().GetAddressByteSize(), 1315 process->GetTarget().GetArchitecture().GetByteOrder()); 1316 1317 OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue(); 1318 size_t item_byte_size = byte_size_value.GetCurrentValue(); 1319 1320 Status error; 1321 lldb::addr_t addr = OptionArgParser::ToAddress( 1322 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error); 1323 1324 if (addr == LLDB_INVALID_ADDRESS) { 1325 result.AppendError("invalid address expression\n"); 1326 result.AppendError(error.AsCString()); 1327 return false; 1328 } 1329 1330 if (m_memory_options.m_infile) { 1331 size_t length = SIZE_MAX; 1332 if (item_byte_size > 1) 1333 length = item_byte_size; 1334 auto data_sp = FileSystem::Instance().CreateDataBuffer( 1335 m_memory_options.m_infile.GetPath(), length, 1336 m_memory_options.m_infile_offset); 1337 if (data_sp) { 1338 length = data_sp->GetByteSize(); 1339 if (length > 0) { 1340 Status error; 1341 size_t bytes_written = 1342 process->WriteMemory(addr, data_sp->GetBytes(), length, error); 1343 1344 if (bytes_written == length) { 1345 // All bytes written 1346 result.GetOutputStream().Printf( 1347 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n", 1348 (uint64_t)bytes_written, addr); 1349 result.SetStatus(eReturnStatusSuccessFinishResult); 1350 } else if (bytes_written > 0) { 1351 // Some byte written 1352 result.GetOutputStream().Printf( 1353 "%" PRIu64 " bytes of %" PRIu64 1354 " requested were written to 0x%" PRIx64 "\n", 1355 (uint64_t)bytes_written, (uint64_t)length, addr); 1356 result.SetStatus(eReturnStatusSuccessFinishResult); 1357 } else { 1358 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 1359 " failed: %s.\n", 1360 addr, error.AsCString()); 1361 } 1362 } 1363 } else { 1364 result.AppendErrorWithFormat("Unable to read contents of file.\n"); 1365 } 1366 return result.Succeeded(); 1367 } else if (item_byte_size == 0) { 1368 if (m_format_options.GetFormat() == eFormatPointer) 1369 item_byte_size = buffer.GetAddressByteSize(); 1370 else 1371 item_byte_size = 1; 1372 } 1373 1374 command.Shift(); // shift off the address argument 1375 uint64_t uval64; 1376 int64_t sval64; 1377 bool success = false; 1378 for (auto &entry : command) { 1379 switch (m_format_options.GetFormat()) { 1380 case kNumFormats: 1381 case eFormatFloat: // TODO: add support for floats soon 1382 case eFormatCharPrintable: 1383 case eFormatBytesWithASCII: 1384 case eFormatComplex: 1385 case eFormatEnum: 1386 case eFormatUnicode8: 1387 case eFormatUnicode16: 1388 case eFormatUnicode32: 1389 case eFormatVectorOfChar: 1390 case eFormatVectorOfSInt8: 1391 case eFormatVectorOfUInt8: 1392 case eFormatVectorOfSInt16: 1393 case eFormatVectorOfUInt16: 1394 case eFormatVectorOfSInt32: 1395 case eFormatVectorOfUInt32: 1396 case eFormatVectorOfSInt64: 1397 case eFormatVectorOfUInt64: 1398 case eFormatVectorOfFloat16: 1399 case eFormatVectorOfFloat32: 1400 case eFormatVectorOfFloat64: 1401 case eFormatVectorOfUInt128: 1402 case eFormatOSType: 1403 case eFormatComplexInteger: 1404 case eFormatAddressInfo: 1405 case eFormatHexFloat: 1406 case eFormatInstruction: 1407 case eFormatVoid: 1408 result.AppendError("unsupported format for writing memory"); 1409 return false; 1410 1411 case eFormatDefault: 1412 case eFormatBytes: 1413 case eFormatHex: 1414 case eFormatHexUppercase: 1415 case eFormatPointer: { 1416 // Decode hex bytes 1417 // Be careful, getAsInteger with a radix of 16 rejects "0xab" so we 1418 // have to special case that: 1419 bool success = false; 1420 if (entry.ref().startswith("0x")) 1421 success = !entry.ref().getAsInteger(0, uval64); 1422 if (!success) 1423 success = !entry.ref().getAsInteger(16, uval64); 1424 if (!success) { 1425 result.AppendErrorWithFormat( 1426 "'%s' is not a valid hex string value.\n", entry.c_str()); 1427 return false; 1428 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) { 1429 result.AppendErrorWithFormat("Value 0x%" PRIx64 1430 " is too large to fit in a %" PRIu64 1431 " byte unsigned integer value.\n", 1432 uval64, (uint64_t)item_byte_size); 1433 return false; 1434 } 1435 buffer.PutMaxHex64(uval64, item_byte_size); 1436 break; 1437 } 1438 case eFormatBoolean: 1439 uval64 = OptionArgParser::ToBoolean(entry.ref(), false, &success); 1440 if (!success) { 1441 result.AppendErrorWithFormat( 1442 "'%s' is not a valid boolean string value.\n", entry.c_str()); 1443 return false; 1444 } 1445 buffer.PutMaxHex64(uval64, item_byte_size); 1446 break; 1447 1448 case eFormatBinary: 1449 if (entry.ref().getAsInteger(2, uval64)) { 1450 result.AppendErrorWithFormat( 1451 "'%s' is not a valid binary string value.\n", entry.c_str()); 1452 return false; 1453 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) { 1454 result.AppendErrorWithFormat("Value 0x%" PRIx64 1455 " is too large to fit in a %" PRIu64 1456 " byte unsigned integer value.\n", 1457 uval64, (uint64_t)item_byte_size); 1458 return false; 1459 } 1460 buffer.PutMaxHex64(uval64, item_byte_size); 1461 break; 1462 1463 case eFormatCharArray: 1464 case eFormatChar: 1465 case eFormatCString: { 1466 if (entry.ref().empty()) 1467 break; 1468 1469 size_t len = entry.ref().size(); 1470 // Include the NULL for C strings... 1471 if (m_format_options.GetFormat() == eFormatCString) 1472 ++len; 1473 Status error; 1474 if (process->WriteMemory(addr, entry.c_str(), len, error) == len) { 1475 addr += len; 1476 } else { 1477 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 1478 " failed: %s.\n", 1479 addr, error.AsCString()); 1480 return false; 1481 } 1482 break; 1483 } 1484 case eFormatDecimal: 1485 if (entry.ref().getAsInteger(0, sval64)) { 1486 result.AppendErrorWithFormat( 1487 "'%s' is not a valid signed decimal value.\n", entry.c_str()); 1488 return false; 1489 } else if (!llvm::isIntN(item_byte_size * 8, sval64)) { 1490 result.AppendErrorWithFormat( 1491 "Value %" PRIi64 " is too large or small to fit in a %" PRIu64 1492 " byte signed integer value.\n", 1493 sval64, (uint64_t)item_byte_size); 1494 return false; 1495 } 1496 buffer.PutMaxHex64(sval64, item_byte_size); 1497 break; 1498 1499 case eFormatUnsigned: 1500 1501 if (entry.ref().getAsInteger(0, uval64)) { 1502 result.AppendErrorWithFormat( 1503 "'%s' is not a valid unsigned decimal string value.\n", 1504 entry.c_str()); 1505 return false; 1506 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) { 1507 result.AppendErrorWithFormat("Value %" PRIu64 1508 " is too large to fit in a %" PRIu64 1509 " byte unsigned integer value.\n", 1510 uval64, (uint64_t)item_byte_size); 1511 return false; 1512 } 1513 buffer.PutMaxHex64(uval64, item_byte_size); 1514 break; 1515 1516 case eFormatOctal: 1517 if (entry.ref().getAsInteger(8, uval64)) { 1518 result.AppendErrorWithFormat( 1519 "'%s' is not a valid octal string value.\n", entry.c_str()); 1520 return false; 1521 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) { 1522 result.AppendErrorWithFormat("Value %" PRIo64 1523 " is too large to fit in a %" PRIu64 1524 " byte unsigned integer value.\n", 1525 uval64, (uint64_t)item_byte_size); 1526 return false; 1527 } 1528 buffer.PutMaxHex64(uval64, item_byte_size); 1529 break; 1530 } 1531 } 1532 1533 if (!buffer.GetString().empty()) { 1534 Status error; 1535 if (process->WriteMemory(addr, buffer.GetString().data(), 1536 buffer.GetString().size(), 1537 error) == buffer.GetString().size()) 1538 return true; 1539 else { 1540 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 1541 " failed: %s.\n", 1542 addr, error.AsCString()); 1543 return false; 1544 } 1545 } 1546 return true; 1547 } 1548 1549 OptionGroupOptions m_option_group; 1550 OptionGroupFormat m_format_options; 1551 OptionGroupWriteMemory m_memory_options; 1552 }; 1553 1554 // Get malloc/free history of a memory address. 1555 class CommandObjectMemoryHistory : public CommandObjectParsed { 1556 public: 1557 CommandObjectMemoryHistory(CommandInterpreter &interpreter) 1558 : CommandObjectParsed(interpreter, "memory history", 1559 "Print recorded stack traces for " 1560 "allocation/deallocation events " 1561 "associated with an address.", 1562 nullptr, 1563 eCommandRequiresTarget | eCommandRequiresProcess | 1564 eCommandProcessMustBePaused | 1565 eCommandProcessMustBeLaunched) { 1566 CommandArgumentEntry arg1; 1567 CommandArgumentData addr_arg; 1568 1569 // Define the first (and only) variant of this arg. 1570 addr_arg.arg_type = eArgTypeAddress; 1571 addr_arg.arg_repetition = eArgRepeatPlain; 1572 1573 // There is only one variant this argument could be; put it into the 1574 // argument entry. 1575 arg1.push_back(addr_arg); 1576 1577 // Push the data for the first argument into the m_arguments vector. 1578 m_arguments.push_back(arg1); 1579 } 1580 1581 ~CommandObjectMemoryHistory() override = default; 1582 1583 const char *GetRepeatCommand(Args ¤t_command_args, 1584 uint32_t index) override { 1585 return m_cmd_name.c_str(); 1586 } 1587 1588 protected: 1589 bool DoExecute(Args &command, CommandReturnObject &result) override { 1590 const size_t argc = command.GetArgumentCount(); 1591 1592 if (argc == 0 || argc > 1) { 1593 result.AppendErrorWithFormat("%s takes an address expression", 1594 m_cmd_name.c_str()); 1595 return false; 1596 } 1597 1598 Status error; 1599 lldb::addr_t addr = OptionArgParser::ToAddress( 1600 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error); 1601 1602 if (addr == LLDB_INVALID_ADDRESS) { 1603 result.AppendError("invalid address expression"); 1604 result.AppendError(error.AsCString()); 1605 return false; 1606 } 1607 1608 Stream *output_stream = &result.GetOutputStream(); 1609 1610 const ProcessSP &process_sp = m_exe_ctx.GetProcessSP(); 1611 const MemoryHistorySP &memory_history = 1612 MemoryHistory::FindPlugin(process_sp); 1613 1614 if (!memory_history) { 1615 result.AppendError("no available memory history provider"); 1616 return false; 1617 } 1618 1619 HistoryThreads thread_list = memory_history->GetHistoryThreads(addr); 1620 1621 const bool stop_format = false; 1622 for (auto thread : thread_list) { 1623 thread->GetStatus(*output_stream, 0, UINT32_MAX, 0, stop_format); 1624 } 1625 1626 result.SetStatus(eReturnStatusSuccessFinishResult); 1627 1628 return true; 1629 } 1630 }; 1631 1632 // CommandObjectMemoryRegion 1633 #pragma mark CommandObjectMemoryRegion 1634 1635 class CommandObjectMemoryRegion : public CommandObjectParsed { 1636 public: 1637 CommandObjectMemoryRegion(CommandInterpreter &interpreter) 1638 : CommandObjectParsed(interpreter, "memory region", 1639 "Get information on the memory region containing " 1640 "an address in the current target process.", 1641 "memory region ADDR", 1642 eCommandRequiresProcess | eCommandTryTargetAPILock | 1643 eCommandProcessMustBeLaunched), 1644 m_prev_end_addr(LLDB_INVALID_ADDRESS) {} 1645 1646 ~CommandObjectMemoryRegion() override = default; 1647 1648 protected: 1649 bool DoExecute(Args &command, CommandReturnObject &result) override { 1650 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1651 if (!process_sp) { 1652 m_prev_end_addr = LLDB_INVALID_ADDRESS; 1653 result.AppendError("invalid process"); 1654 return false; 1655 } 1656 1657 Status error; 1658 lldb::addr_t load_addr = m_prev_end_addr; 1659 m_prev_end_addr = LLDB_INVALID_ADDRESS; 1660 1661 const size_t argc = command.GetArgumentCount(); 1662 if (argc > 1 || (argc == 0 && load_addr == LLDB_INVALID_ADDRESS)) { 1663 result.AppendErrorWithFormat("'%s' takes one argument:\nUsage: %s\n", 1664 m_cmd_name.c_str(), m_cmd_syntax.c_str()); 1665 return false; 1666 } 1667 1668 if (argc == 1) { 1669 auto load_addr_str = command[0].ref(); 1670 load_addr = OptionArgParser::ToAddress(&m_exe_ctx, load_addr_str, 1671 LLDB_INVALID_ADDRESS, &error); 1672 if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) { 1673 result.AppendErrorWithFormat("invalid address argument \"%s\": %s\n", 1674 command[0].c_str(), error.AsCString()); 1675 return false; 1676 } 1677 } 1678 1679 lldb_private::MemoryRegionInfo range_info; 1680 error = process_sp->GetMemoryRegionInfo(load_addr, range_info); 1681 if (error.Success()) { 1682 lldb_private::Address addr; 1683 ConstString name = range_info.GetName(); 1684 ConstString section_name; 1685 if (process_sp->GetTarget().ResolveLoadAddress(load_addr, addr)) { 1686 SectionSP section_sp(addr.GetSection()); 1687 if (section_sp) { 1688 // Got the top most section, not the deepest section 1689 while (section_sp->GetParent()) 1690 section_sp = section_sp->GetParent(); 1691 section_name = section_sp->GetName(); 1692 } 1693 } 1694 1695 result.AppendMessageWithFormatv( 1696 "[{0:x16}-{1:x16}) {2:r}{3:w}{4:x}{5}{6}{7}{8}", 1697 range_info.GetRange().GetRangeBase(), 1698 range_info.GetRange().GetRangeEnd(), range_info.GetReadable(), 1699 range_info.GetWritable(), range_info.GetExecutable(), name ? " " : "", 1700 name, section_name ? " " : "", section_name); 1701 MemoryRegionInfo::OptionalBool memory_tagged = 1702 range_info.GetMemoryTagged(); 1703 if (memory_tagged == MemoryRegionInfo::OptionalBool::eYes) 1704 result.AppendMessage("memory tagging: enabled"); 1705 1706 const llvm::Optional<std::vector<addr_t>> &dirty_page_list = 1707 range_info.GetDirtyPageList(); 1708 if (dirty_page_list.hasValue()) { 1709 const size_t page_count = dirty_page_list.getValue().size(); 1710 result.AppendMessageWithFormat( 1711 "Modified memory (dirty) page list provided, %zu entries.\n", 1712 page_count); 1713 if (page_count > 0) { 1714 bool print_comma = false; 1715 result.AppendMessageWithFormat("Dirty pages: "); 1716 for (size_t i = 0; i < page_count; i++) { 1717 if (print_comma) 1718 result.AppendMessageWithFormat(", "); 1719 else 1720 print_comma = true; 1721 result.AppendMessageWithFormat("0x%" PRIx64, 1722 dirty_page_list.getValue()[i]); 1723 } 1724 result.AppendMessageWithFormat(".\n"); 1725 } 1726 } 1727 1728 m_prev_end_addr = range_info.GetRange().GetRangeEnd(); 1729 result.SetStatus(eReturnStatusSuccessFinishResult); 1730 return true; 1731 } 1732 1733 result.AppendErrorWithFormat("%s\n", error.AsCString()); 1734 return false; 1735 } 1736 1737 const char *GetRepeatCommand(Args ¤t_command_args, 1738 uint32_t index) override { 1739 // If we repeat this command, repeat it without any arguments so we can 1740 // show the next memory range 1741 return m_cmd_name.c_str(); 1742 } 1743 1744 lldb::addr_t m_prev_end_addr; 1745 }; 1746 1747 // CommandObjectMemory 1748 1749 CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter) 1750 : CommandObjectMultiword( 1751 interpreter, "memory", 1752 "Commands for operating on memory in the current target process.", 1753 "memory <subcommand> [<subcommand-options>]") { 1754 LoadSubCommand("find", 1755 CommandObjectSP(new CommandObjectMemoryFind(interpreter))); 1756 LoadSubCommand("read", 1757 CommandObjectSP(new CommandObjectMemoryRead(interpreter))); 1758 LoadSubCommand("write", 1759 CommandObjectSP(new CommandObjectMemoryWrite(interpreter))); 1760 LoadSubCommand("history", 1761 CommandObjectSP(new CommandObjectMemoryHistory(interpreter))); 1762 LoadSubCommand("region", 1763 CommandObjectSP(new CommandObjectMemoryRegion(interpreter))); 1764 LoadSubCommand("tag", 1765 CommandObjectSP(new CommandObjectMemoryTag(interpreter))); 1766 } 1767 1768 CommandObjectMemory::~CommandObjectMemory() = default; 1769