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