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