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