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