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