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/DataBufferHeap.h" 21 #include "lldb/Core/DataExtractor.h" 22 #include "lldb/Core/Debugger.h" 23 #include "lldb/Core/Module.h" 24 #include "lldb/Core/Section.h" 25 #include "lldb/Core/StreamString.h" 26 #include "lldb/Core/ValueObjectMemory.h" 27 #include "lldb/DataFormatters/ValueObjectPrinter.h" 28 #include "lldb/Host/StringConvert.h" 29 #include "lldb/Interpreter/Args.h" 30 #include "lldb/Interpreter/CommandInterpreter.h" 31 #include "lldb/Interpreter/CommandReturnObject.h" 32 #include "lldb/Interpreter/OptionGroupFormat.h" 33 #include "lldb/Interpreter/OptionGroupOutputFile.h" 34 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h" 35 #include "lldb/Interpreter/OptionValueString.h" 36 #include "lldb/Interpreter/Options.h" 37 #include "lldb/Symbol/ClangASTContext.h" 38 #include "lldb/Symbol/SymbolFile.h" 39 #include "lldb/Symbol/TypeList.h" 40 #include "lldb/Target/MemoryHistory.h" 41 #include "lldb/Target/MemoryRegionInfo.h" 42 #include "lldb/Target/Process.h" 43 #include "lldb/Target/StackFrame.h" 44 #include "lldb/Target/Thread.h" 45 46 #include "lldb/lldb-private.h" 47 48 using namespace lldb; 49 using namespace lldb_private; 50 51 static OptionDefinition g_option_table[] = { 52 // clang-format off 53 {LLDB_OPT_SET_1, false, "num-per-line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNumberPerLine, "The number of items per line to display." }, 54 {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 " 55 "uses the format, size, count and number per line settings." }, 56 {LLDB_OPT_SET_3, true , "type", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "The name of a type to view memory as." }, 57 {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." }, 58 {LLDB_OPT_SET_1 | 59 LLDB_OPT_SET_2 | 60 LLDB_OPT_SET_3, false, "force", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Necessary if reading over target.max-memory-read-size bytes." }, 61 // clang-format on 62 }; 63 64 class OptionGroupReadMemory : public OptionGroup { 65 public: 66 OptionGroupReadMemory() 67 : m_num_per_line(1, 1), m_output_as_binary(false), m_view_as_type(), 68 m_offset(0, 0) {} 69 70 ~OptionGroupReadMemory() override = default; 71 72 uint32_t GetNumDefinitions() override { 73 return sizeof(g_option_table) / sizeof(OptionDefinition); 74 } 75 76 const OptionDefinition *GetDefinitions() override { return g_option_table; } 77 78 Error SetOptionValue(uint32_t option_idx, const char *option_arg, 79 ExecutionContext *execution_context) override { 80 Error error; 81 const int short_option = g_option_table[option_idx].short_option; 82 83 switch (short_option) { 84 case 'l': 85 error = m_num_per_line.SetValueFromString(option_arg); 86 if (m_num_per_line.GetCurrentValue() == 0) 87 error.SetErrorStringWithFormat( 88 "invalid value for --num-per-line option '%s'", option_arg); 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_arg); 97 break; 98 99 case 'r': 100 m_force = true; 101 break; 102 103 case 'E': 104 error = m_offset.SetValueFromString(option_arg); 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 Error FinalizeSettings(Target *target, OptionGroupFormat &format_options) { 124 Error 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 Error 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.GetArgumentAtIndex(0), 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 = 605 Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(1), 606 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 Error 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().c_str(), 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.GetString().c_str()); 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 = 867 data.Dump(output_stream, 0, format, item_byte_size, item_count, 868 num_per_line / target->GetArchitecture().GetDataByteSize(), 869 addr, 0, 0, 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 uint32_t GetNumDefinitions() override { 910 return sizeof(g_memory_find_option_table) / sizeof(OptionDefinition); 911 } 912 913 const OptionDefinition *GetDefinitions() override { 914 return g_memory_find_option_table; 915 } 916 917 Error SetOptionValue(uint32_t option_idx, const char *option_arg, 918 ExecutionContext *execution_context) override { 919 Error error; 920 const int short_option = 921 g_memory_find_option_table[option_idx].short_option; 922 923 switch (short_option) { 924 case 'e': 925 m_expr.SetValueFromString(option_arg); 926 break; 927 928 case 's': 929 m_string.SetValueFromString(option_arg); 930 break; 931 932 case 'c': 933 if (m_count.SetValueFromString(option_arg).Fail()) 934 error.SetErrorString("unrecognized value for count"); 935 break; 936 937 case 'o': 938 if (m_offset.SetValueFromString(option_arg).Fail()) 939 error.SetErrorString("unrecognized value for dump-offset"); 940 break; 941 942 default: 943 error.SetErrorStringWithFormat("unrecognized short option '%c'", 944 short_option); 945 break; 946 } 947 return error; 948 } 949 950 void OptionParsingStarting(ExecutionContext *execution_context) override { 951 m_expr.Clear(); 952 m_string.Clear(); 953 m_count.Clear(); 954 } 955 956 OptionValueString m_expr; 957 OptionValueString m_string; 958 OptionValueUInt64 m_count; 959 OptionValueUInt64 m_offset; 960 }; 961 962 CommandObjectMemoryFind(CommandInterpreter &interpreter) 963 : CommandObjectParsed( 964 interpreter, "memory find", 965 "Find a value in the memory of the current target process.", 966 nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched), 967 m_option_group(), m_memory_options() { 968 CommandArgumentEntry arg1; 969 CommandArgumentEntry arg2; 970 CommandArgumentData addr_arg; 971 CommandArgumentData value_arg; 972 973 // Define the first (and only) variant of this arg. 974 addr_arg.arg_type = eArgTypeAddressOrExpression; 975 addr_arg.arg_repetition = eArgRepeatPlain; 976 977 // There is only one variant this argument could be; put it into the 978 // argument entry. 979 arg1.push_back(addr_arg); 980 981 // Define the first (and only) variant of this arg. 982 value_arg.arg_type = eArgTypeAddressOrExpression; 983 value_arg.arg_repetition = eArgRepeatPlain; 984 985 // There is only one variant this argument could be; put it into the 986 // argument entry. 987 arg2.push_back(value_arg); 988 989 // Push the data for the first argument into the m_arguments vector. 990 m_arguments.push_back(arg1); 991 m_arguments.push_back(arg2); 992 993 m_option_group.Append(&m_memory_options); 994 m_option_group.Finalize(); 995 } 996 997 ~CommandObjectMemoryFind() override = default; 998 999 Options *GetOptions() override { return &m_option_group; } 1000 1001 protected: 1002 class ProcessMemoryIterator { 1003 public: 1004 ProcessMemoryIterator(ProcessSP process_sp, lldb::addr_t base) 1005 : m_process_sp(process_sp), m_base_addr(base), m_is_valid(true) { 1006 lldbassert(process_sp.get() != nullptr); 1007 } 1008 1009 bool IsValid() { return m_is_valid; } 1010 1011 uint8_t operator[](lldb::addr_t offset) { 1012 if (!IsValid()) 1013 return 0; 1014 1015 uint8_t retval = 0; 1016 Error error; 1017 if (0 == 1018 m_process_sp->ReadMemory(m_base_addr + offset, &retval, 1, error)) { 1019 m_is_valid = false; 1020 return 0; 1021 } 1022 1023 return retval; 1024 } 1025 1026 private: 1027 ProcessSP m_process_sp; 1028 lldb::addr_t m_base_addr; 1029 bool m_is_valid; 1030 }; 1031 bool DoExecute(Args &command, CommandReturnObject &result) override { 1032 // No need to check "process" for validity as eCommandRequiresProcess 1033 // ensures it is valid 1034 Process *process = m_exe_ctx.GetProcessPtr(); 1035 1036 const size_t argc = command.GetArgumentCount(); 1037 1038 if (argc != 2) { 1039 result.AppendError("two addresses needed for memory find"); 1040 return false; 1041 } 1042 1043 Error error; 1044 lldb::addr_t low_addr = 1045 Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(0), 1046 LLDB_INVALID_ADDRESS, &error); 1047 if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) { 1048 result.AppendError("invalid low address"); 1049 return false; 1050 } 1051 lldb::addr_t high_addr = 1052 Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(1), 1053 LLDB_INVALID_ADDRESS, &error); 1054 if (high_addr == LLDB_INVALID_ADDRESS || error.Fail()) { 1055 result.AppendError("invalid high address"); 1056 return false; 1057 } 1058 1059 if (high_addr <= low_addr) { 1060 result.AppendError( 1061 "starting address must be smaller than ending address"); 1062 return false; 1063 } 1064 1065 lldb::addr_t found_location = LLDB_INVALID_ADDRESS; 1066 1067 DataBufferHeap buffer; 1068 1069 if (m_memory_options.m_string.OptionWasSet()) 1070 buffer.CopyData(m_memory_options.m_string.GetStringValue(), 1071 strlen(m_memory_options.m_string.GetStringValue())); 1072 else if (m_memory_options.m_expr.OptionWasSet()) { 1073 StackFrame *frame = m_exe_ctx.GetFramePtr(); 1074 ValueObjectSP result_sp; 1075 if ((eExpressionCompleted == 1076 process->GetTarget().EvaluateExpression( 1077 m_memory_options.m_expr.GetStringValue(), frame, result_sp)) && 1078 result_sp) { 1079 uint64_t value = result_sp->GetValueAsUnsigned(0); 1080 switch (result_sp->GetCompilerType().GetByteSize(nullptr)) { 1081 case 1: { 1082 uint8_t byte = (uint8_t)value; 1083 buffer.CopyData(&byte, 1); 1084 } break; 1085 case 2: { 1086 uint16_t word = (uint16_t)value; 1087 buffer.CopyData(&word, 2); 1088 } break; 1089 case 4: { 1090 uint32_t lword = (uint32_t)value; 1091 buffer.CopyData(&lword, 4); 1092 } break; 1093 case 8: { 1094 buffer.CopyData(&value, 8); 1095 } break; 1096 case 3: 1097 case 5: 1098 case 6: 1099 case 7: 1100 result.AppendError("unknown type. pass a string instead"); 1101 return false; 1102 default: 1103 result.AppendError( 1104 "result size larger than 8 bytes. pass a string instead"); 1105 return false; 1106 } 1107 } else { 1108 result.AppendError( 1109 "expression evaluation failed. pass a string instead"); 1110 return false; 1111 } 1112 } else { 1113 result.AppendError( 1114 "please pass either a block of text, or an expression to evaluate."); 1115 return false; 1116 } 1117 1118 size_t count = m_memory_options.m_count.GetCurrentValue(); 1119 found_location = low_addr; 1120 bool ever_found = false; 1121 while (count) { 1122 found_location = FastSearch(found_location, high_addr, buffer.GetBytes(), 1123 buffer.GetByteSize()); 1124 if (found_location == LLDB_INVALID_ADDRESS) { 1125 if (!ever_found) { 1126 result.AppendMessage("data not found within the range.\n"); 1127 result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult); 1128 } else 1129 result.AppendMessage("no more matches within the range.\n"); 1130 break; 1131 } 1132 result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n", 1133 found_location); 1134 1135 DataBufferHeap dumpbuffer(32, 0); 1136 process->ReadMemory( 1137 found_location + m_memory_options.m_offset.GetCurrentValue(), 1138 dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error); 1139 if (!error.Fail()) { 1140 DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), 1141 process->GetByteOrder(), 1142 process->GetAddressByteSize()); 1143 data.Dump(&result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1, 1144 dumpbuffer.GetByteSize(), 16, 1145 found_location + m_memory_options.m_offset.GetCurrentValue(), 1146 0, 0); 1147 result.GetOutputStream().EOL(); 1148 } 1149 1150 --count; 1151 found_location++; 1152 ever_found = true; 1153 } 1154 1155 result.SetStatus(lldb::eReturnStatusSuccessFinishResult); 1156 return true; 1157 } 1158 1159 lldb::addr_t FastSearch(lldb::addr_t low, lldb::addr_t high, uint8_t *buffer, 1160 size_t buffer_size) { 1161 const size_t region_size = high - low; 1162 1163 if (region_size < buffer_size) 1164 return LLDB_INVALID_ADDRESS; 1165 1166 std::vector<size_t> bad_char_heuristic(256, buffer_size); 1167 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1168 ProcessMemoryIterator iterator(process_sp, low); 1169 1170 for (size_t idx = 0; idx < buffer_size - 1; idx++) { 1171 decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx]; 1172 bad_char_heuristic[bcu_idx] = buffer_size - idx - 1; 1173 } 1174 for (size_t s = 0; s <= (region_size - buffer_size);) { 1175 int64_t j = buffer_size - 1; 1176 while (j >= 0 && buffer[j] == iterator[s + j]) 1177 j--; 1178 if (j < 0) 1179 return low + s; 1180 else 1181 s += bad_char_heuristic[iterator[s + buffer_size - 1]]; 1182 } 1183 1184 return LLDB_INVALID_ADDRESS; 1185 } 1186 1187 OptionGroupOptions m_option_group; 1188 OptionGroupFindMemory m_memory_options; 1189 }; 1190 1191 OptionDefinition g_memory_write_option_table[] = { 1192 // clang-format off 1193 {LLDB_OPT_SET_1, true, "infile", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Write memory using the contents of a file."}, 1194 {LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "Start writing bytes from an offset within the input file."}, 1195 // clang-format on 1196 }; 1197 1198 //---------------------------------------------------------------------- 1199 // Write memory to the inferior process 1200 //---------------------------------------------------------------------- 1201 class CommandObjectMemoryWrite : public CommandObjectParsed { 1202 public: 1203 class OptionGroupWriteMemory : public OptionGroup { 1204 public: 1205 OptionGroupWriteMemory() : OptionGroup() {} 1206 1207 ~OptionGroupWriteMemory() override = default; 1208 1209 uint32_t GetNumDefinitions() override { 1210 return sizeof(g_memory_write_option_table) / sizeof(OptionDefinition); 1211 } 1212 1213 const OptionDefinition *GetDefinitions() override { 1214 return g_memory_write_option_table; 1215 } 1216 1217 Error SetOptionValue(uint32_t option_idx, const char *option_arg, 1218 ExecutionContext *execution_context) override { 1219 Error error; 1220 const int short_option = 1221 g_memory_write_option_table[option_idx].short_option; 1222 1223 switch (short_option) { 1224 case 'i': 1225 m_infile.SetFile(option_arg, true); 1226 if (!m_infile.Exists()) { 1227 m_infile.Clear(); 1228 error.SetErrorStringWithFormat("input file does not exist: '%s'", 1229 option_arg); 1230 } 1231 break; 1232 1233 case 'o': { 1234 bool success; 1235 m_infile_offset = StringConvert::ToUInt64(option_arg, 0, 0, &success); 1236 if (!success) { 1237 error.SetErrorStringWithFormat("invalid offset string '%s'", 1238 option_arg); 1239 } 1240 } break; 1241 1242 default: 1243 error.SetErrorStringWithFormat("unrecognized short option '%c'", 1244 short_option); 1245 break; 1246 } 1247 return error; 1248 } 1249 1250 void OptionParsingStarting(ExecutionContext *execution_context) override { 1251 m_infile.Clear(); 1252 m_infile_offset = 0; 1253 } 1254 1255 FileSpec m_infile; 1256 off_t m_infile_offset; 1257 }; 1258 1259 CommandObjectMemoryWrite(CommandInterpreter &interpreter) 1260 : CommandObjectParsed( 1261 interpreter, "memory write", 1262 "Write to the memory of the current target process.", nullptr, 1263 eCommandRequiresProcess | eCommandProcessMustBeLaunched), 1264 m_option_group(), m_format_options(eFormatBytes, 1, UINT64_MAX), 1265 m_memory_options() { 1266 CommandArgumentEntry arg1; 1267 CommandArgumentEntry arg2; 1268 CommandArgumentData addr_arg; 1269 CommandArgumentData value_arg; 1270 1271 // Define the first (and only) variant of this arg. 1272 addr_arg.arg_type = eArgTypeAddress; 1273 addr_arg.arg_repetition = eArgRepeatPlain; 1274 1275 // There is only one variant this argument could be; put it into the 1276 // argument entry. 1277 arg1.push_back(addr_arg); 1278 1279 // Define the first (and only) variant of this arg. 1280 value_arg.arg_type = eArgTypeValue; 1281 value_arg.arg_repetition = eArgRepeatPlus; 1282 1283 // There is only one variant this argument could be; put it into the 1284 // argument entry. 1285 arg2.push_back(value_arg); 1286 1287 // Push the data for the first argument into the m_arguments vector. 1288 m_arguments.push_back(arg1); 1289 m_arguments.push_back(arg2); 1290 1291 m_option_group.Append(&m_format_options, 1292 OptionGroupFormat::OPTION_GROUP_FORMAT, 1293 LLDB_OPT_SET_1); 1294 m_option_group.Append(&m_format_options, 1295 OptionGroupFormat::OPTION_GROUP_SIZE, 1296 LLDB_OPT_SET_1 | LLDB_OPT_SET_2); 1297 m_option_group.Append(&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2); 1298 m_option_group.Finalize(); 1299 } 1300 1301 ~CommandObjectMemoryWrite() override = default; 1302 1303 Options *GetOptions() override { return &m_option_group; } 1304 1305 bool UIntValueIsValidForSize(uint64_t uval64, size_t total_byte_size) { 1306 if (total_byte_size > 8) 1307 return false; 1308 1309 if (total_byte_size == 8) 1310 return true; 1311 1312 const uint64_t max = ((uint64_t)1 << (uint64_t)(total_byte_size * 8)) - 1; 1313 return uval64 <= max; 1314 } 1315 1316 bool SIntValueIsValidForSize(int64_t sval64, size_t total_byte_size) { 1317 if (total_byte_size > 8) 1318 return false; 1319 1320 if (total_byte_size == 8) 1321 return true; 1322 1323 const int64_t max = ((int64_t)1 << (uint64_t)(total_byte_size * 8 - 1)) - 1; 1324 const int64_t min = ~(max); 1325 return min <= sval64 && sval64 <= max; 1326 } 1327 1328 protected: 1329 bool DoExecute(Args &command, CommandReturnObject &result) override { 1330 // No need to check "process" for validity as eCommandRequiresProcess 1331 // ensures it is valid 1332 Process *process = m_exe_ctx.GetProcessPtr(); 1333 1334 const size_t argc = command.GetArgumentCount(); 1335 1336 if (m_memory_options.m_infile) { 1337 if (argc < 1) { 1338 result.AppendErrorWithFormat( 1339 "%s takes a destination address when writing file contents.\n", 1340 m_cmd_name.c_str()); 1341 result.SetStatus(eReturnStatusFailed); 1342 return false; 1343 } 1344 } else if (argc < 2) { 1345 result.AppendErrorWithFormat( 1346 "%s takes a destination address and at least one value.\n", 1347 m_cmd_name.c_str()); 1348 result.SetStatus(eReturnStatusFailed); 1349 return false; 1350 } 1351 1352 StreamString buffer( 1353 Stream::eBinary, 1354 process->GetTarget().GetArchitecture().GetAddressByteSize(), 1355 process->GetTarget().GetArchitecture().GetByteOrder()); 1356 1357 OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue(); 1358 size_t item_byte_size = byte_size_value.GetCurrentValue(); 1359 1360 Error error; 1361 lldb::addr_t addr = 1362 Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(0), 1363 LLDB_INVALID_ADDRESS, &error); 1364 1365 if (addr == LLDB_INVALID_ADDRESS) { 1366 result.AppendError("invalid address expression\n"); 1367 result.AppendError(error.AsCString()); 1368 result.SetStatus(eReturnStatusFailed); 1369 return false; 1370 } 1371 1372 if (m_memory_options.m_infile) { 1373 size_t length = SIZE_MAX; 1374 if (item_byte_size > 1) 1375 length = item_byte_size; 1376 lldb::DataBufferSP data_sp(m_memory_options.m_infile.ReadFileContents( 1377 m_memory_options.m_infile_offset, length)); 1378 if (data_sp) { 1379 length = data_sp->GetByteSize(); 1380 if (length > 0) { 1381 Error error; 1382 size_t bytes_written = 1383 process->WriteMemory(addr, data_sp->GetBytes(), length, error); 1384 1385 if (bytes_written == length) { 1386 // All bytes written 1387 result.GetOutputStream().Printf( 1388 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n", 1389 (uint64_t)bytes_written, addr); 1390 result.SetStatus(eReturnStatusSuccessFinishResult); 1391 } else if (bytes_written > 0) { 1392 // Some byte written 1393 result.GetOutputStream().Printf( 1394 "%" PRIu64 " bytes of %" PRIu64 1395 " requested were written to 0x%" PRIx64 "\n", 1396 (uint64_t)bytes_written, (uint64_t)length, addr); 1397 result.SetStatus(eReturnStatusSuccessFinishResult); 1398 } else { 1399 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 1400 " failed: %s.\n", 1401 addr, error.AsCString()); 1402 result.SetStatus(eReturnStatusFailed); 1403 } 1404 } 1405 } else { 1406 result.AppendErrorWithFormat("Unable to read contents of file.\n"); 1407 result.SetStatus(eReturnStatusFailed); 1408 } 1409 return result.Succeeded(); 1410 } else if (item_byte_size == 0) { 1411 if (m_format_options.GetFormat() == eFormatPointer) 1412 item_byte_size = buffer.GetAddressByteSize(); 1413 else 1414 item_byte_size = 1; 1415 } 1416 1417 command.Shift(); // shift off the address argument 1418 uint64_t uval64; 1419 int64_t sval64; 1420 bool success = false; 1421 const size_t num_value_args = command.GetArgumentCount(); 1422 for (size_t i = 0; i < num_value_args; ++i) { 1423 const char *value_str = command.GetArgumentAtIndex(i); 1424 1425 switch (m_format_options.GetFormat()) { 1426 case kNumFormats: 1427 case eFormatFloat: // TODO: add support for floats soon 1428 case eFormatCharPrintable: 1429 case eFormatBytesWithASCII: 1430 case eFormatComplex: 1431 case eFormatEnum: 1432 case eFormatUnicode16: 1433 case eFormatUnicode32: 1434 case eFormatVectorOfChar: 1435 case eFormatVectorOfSInt8: 1436 case eFormatVectorOfUInt8: 1437 case eFormatVectorOfSInt16: 1438 case eFormatVectorOfUInt16: 1439 case eFormatVectorOfSInt32: 1440 case eFormatVectorOfUInt32: 1441 case eFormatVectorOfSInt64: 1442 case eFormatVectorOfUInt64: 1443 case eFormatVectorOfFloat16: 1444 case eFormatVectorOfFloat32: 1445 case eFormatVectorOfFloat64: 1446 case eFormatVectorOfUInt128: 1447 case eFormatOSType: 1448 case eFormatComplexInteger: 1449 case eFormatAddressInfo: 1450 case eFormatHexFloat: 1451 case eFormatInstruction: 1452 case eFormatVoid: 1453 result.AppendError("unsupported format for writing memory"); 1454 result.SetStatus(eReturnStatusFailed); 1455 return false; 1456 1457 case eFormatDefault: 1458 case eFormatBytes: 1459 case eFormatHex: 1460 case eFormatHexUppercase: 1461 case eFormatPointer: 1462 // Decode hex bytes 1463 uval64 = StringConvert::ToUInt64(value_str, UINT64_MAX, 16, &success); 1464 if (!success) { 1465 result.AppendErrorWithFormat( 1466 "'%s' is not a valid hex string value.\n", value_str); 1467 result.SetStatus(eReturnStatusFailed); 1468 return false; 1469 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { 1470 result.AppendErrorWithFormat("Value 0x%" PRIx64 1471 " is too large to fit in a %" PRIu64 1472 " byte unsigned integer value.\n", 1473 uval64, (uint64_t)item_byte_size); 1474 result.SetStatus(eReturnStatusFailed); 1475 return false; 1476 } 1477 buffer.PutMaxHex64(uval64, item_byte_size); 1478 break; 1479 1480 case eFormatBoolean: 1481 uval64 = Args::StringToBoolean(value_str, false, &success); 1482 if (!success) { 1483 result.AppendErrorWithFormat( 1484 "'%s' is not a valid boolean string value.\n", value_str); 1485 result.SetStatus(eReturnStatusFailed); 1486 return false; 1487 } 1488 buffer.PutMaxHex64(uval64, item_byte_size); 1489 break; 1490 1491 case eFormatBinary: 1492 uval64 = StringConvert::ToUInt64(value_str, UINT64_MAX, 2, &success); 1493 if (!success) { 1494 result.AppendErrorWithFormat( 1495 "'%s' is not a valid binary string value.\n", value_str); 1496 result.SetStatus(eReturnStatusFailed); 1497 return false; 1498 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { 1499 result.AppendErrorWithFormat("Value 0x%" PRIx64 1500 " is too large to fit in a %" PRIu64 1501 " byte unsigned integer value.\n", 1502 uval64, (uint64_t)item_byte_size); 1503 result.SetStatus(eReturnStatusFailed); 1504 return false; 1505 } 1506 buffer.PutMaxHex64(uval64, item_byte_size); 1507 break; 1508 1509 case eFormatCharArray: 1510 case eFormatChar: 1511 case eFormatCString: 1512 if (value_str[0]) { 1513 size_t len = strlen(value_str); 1514 // Include the NULL for C strings... 1515 if (m_format_options.GetFormat() == eFormatCString) 1516 ++len; 1517 Error error; 1518 if (process->WriteMemory(addr, value_str, len, error) == len) { 1519 addr += len; 1520 } else { 1521 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 1522 " failed: %s.\n", 1523 addr, error.AsCString()); 1524 result.SetStatus(eReturnStatusFailed); 1525 return false; 1526 } 1527 } 1528 break; 1529 1530 case eFormatDecimal: 1531 sval64 = StringConvert::ToSInt64(value_str, INT64_MAX, 0, &success); 1532 if (!success) { 1533 result.AppendErrorWithFormat( 1534 "'%s' is not a valid signed decimal value.\n", value_str); 1535 result.SetStatus(eReturnStatusFailed); 1536 return false; 1537 } else if (!SIntValueIsValidForSize(sval64, item_byte_size)) { 1538 result.AppendErrorWithFormat( 1539 "Value %" PRIi64 " is too large or small to fit in a %" PRIu64 1540 " byte signed integer value.\n", 1541 sval64, (uint64_t)item_byte_size); 1542 result.SetStatus(eReturnStatusFailed); 1543 return false; 1544 } 1545 buffer.PutMaxHex64(sval64, item_byte_size); 1546 break; 1547 1548 case eFormatUnsigned: 1549 uval64 = StringConvert::ToUInt64(value_str, UINT64_MAX, 0, &success); 1550 if (!success) { 1551 result.AppendErrorWithFormat( 1552 "'%s' is not a valid unsigned decimal string value.\n", 1553 value_str); 1554 result.SetStatus(eReturnStatusFailed); 1555 return false; 1556 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { 1557 result.AppendErrorWithFormat("Value %" PRIu64 1558 " is too large to fit in a %" PRIu64 1559 " byte unsigned integer value.\n", 1560 uval64, (uint64_t)item_byte_size); 1561 result.SetStatus(eReturnStatusFailed); 1562 return false; 1563 } 1564 buffer.PutMaxHex64(uval64, item_byte_size); 1565 break; 1566 1567 case eFormatOctal: 1568 uval64 = StringConvert::ToUInt64(value_str, UINT64_MAX, 8, &success); 1569 if (!success) { 1570 result.AppendErrorWithFormat( 1571 "'%s' is not a valid octal string value.\n", value_str); 1572 result.SetStatus(eReturnStatusFailed); 1573 return false; 1574 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) { 1575 result.AppendErrorWithFormat("Value %" PRIo64 1576 " is too large to fit in a %" PRIu64 1577 " byte unsigned integer value.\n", 1578 uval64, (uint64_t)item_byte_size); 1579 result.SetStatus(eReturnStatusFailed); 1580 return false; 1581 } 1582 buffer.PutMaxHex64(uval64, item_byte_size); 1583 break; 1584 } 1585 } 1586 1587 if (!buffer.GetString().empty()) { 1588 Error error; 1589 if (process->WriteMemory(addr, buffer.GetString().c_str(), 1590 buffer.GetString().size(), 1591 error) == buffer.GetString().size()) 1592 return true; 1593 else { 1594 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64 1595 " failed: %s.\n", 1596 addr, error.AsCString()); 1597 result.SetStatus(eReturnStatusFailed); 1598 return false; 1599 } 1600 } 1601 return true; 1602 } 1603 1604 OptionGroupOptions m_option_group; 1605 OptionGroupFormat m_format_options; 1606 OptionGroupWriteMemory m_memory_options; 1607 }; 1608 1609 //---------------------------------------------------------------------- 1610 // Get malloc/free history of a memory address. 1611 //---------------------------------------------------------------------- 1612 class CommandObjectMemoryHistory : public CommandObjectParsed { 1613 public: 1614 CommandObjectMemoryHistory(CommandInterpreter &interpreter) 1615 : CommandObjectParsed( 1616 interpreter, "memory history", "Print recorded stack traces for " 1617 "allocation/deallocation events " 1618 "associated with an address.", 1619 nullptr, 1620 eCommandRequiresTarget | eCommandRequiresProcess | 1621 eCommandProcessMustBePaused | eCommandProcessMustBeLaunched) { 1622 CommandArgumentEntry arg1; 1623 CommandArgumentData addr_arg; 1624 1625 // Define the first (and only) variant of this arg. 1626 addr_arg.arg_type = eArgTypeAddress; 1627 addr_arg.arg_repetition = eArgRepeatPlain; 1628 1629 // There is only one variant this argument could be; put it into the 1630 // argument entry. 1631 arg1.push_back(addr_arg); 1632 1633 // Push the data for the first argument into the m_arguments vector. 1634 m_arguments.push_back(arg1); 1635 } 1636 1637 ~CommandObjectMemoryHistory() override = default; 1638 1639 const char *GetRepeatCommand(Args ¤t_command_args, 1640 uint32_t index) override { 1641 return m_cmd_name.c_str(); 1642 } 1643 1644 protected: 1645 bool DoExecute(Args &command, CommandReturnObject &result) override { 1646 const size_t argc = command.GetArgumentCount(); 1647 1648 if (argc == 0 || argc > 1) { 1649 result.AppendErrorWithFormat("%s takes an address expression", 1650 m_cmd_name.c_str()); 1651 result.SetStatus(eReturnStatusFailed); 1652 return false; 1653 } 1654 1655 Error error; 1656 lldb::addr_t addr = 1657 Args::StringToAddress(&m_exe_ctx, command.GetArgumentAtIndex(0), 1658 LLDB_INVALID_ADDRESS, &error); 1659 1660 if (addr == LLDB_INVALID_ADDRESS) { 1661 result.AppendError("invalid address expression"); 1662 result.AppendError(error.AsCString()); 1663 result.SetStatus(eReturnStatusFailed); 1664 return false; 1665 } 1666 1667 Stream *output_stream = &result.GetOutputStream(); 1668 1669 const ProcessSP &process_sp = m_exe_ctx.GetProcessSP(); 1670 const MemoryHistorySP &memory_history = 1671 MemoryHistory::FindPlugin(process_sp); 1672 1673 if (!memory_history) { 1674 result.AppendError("no available memory history provider"); 1675 result.SetStatus(eReturnStatusFailed); 1676 return false; 1677 } 1678 1679 HistoryThreads thread_list = memory_history->GetHistoryThreads(addr); 1680 1681 for (auto thread : thread_list) { 1682 thread->GetStatus(*output_stream, 0, UINT32_MAX, 0); 1683 } 1684 1685 result.SetStatus(eReturnStatusSuccessFinishResult); 1686 1687 return true; 1688 } 1689 }; 1690 1691 //------------------------------------------------------------------------- 1692 // CommandObjectMemoryRegion 1693 //------------------------------------------------------------------------- 1694 #pragma mark CommandObjectMemoryRegion 1695 1696 class CommandObjectMemoryRegion : public CommandObjectParsed { 1697 public: 1698 CommandObjectMemoryRegion(CommandInterpreter &interpreter) 1699 : CommandObjectParsed(interpreter, "memory region", 1700 "Get information on the memory region containing " 1701 "an address in the current target process.", 1702 "memory region ADDR", 1703 eCommandRequiresProcess | eCommandTryTargetAPILock | 1704 eCommandProcessMustBeLaunched), 1705 m_prev_end_addr(LLDB_INVALID_ADDRESS) {} 1706 1707 ~CommandObjectMemoryRegion() override = default; 1708 1709 protected: 1710 bool DoExecute(Args &command, CommandReturnObject &result) override { 1711 ProcessSP process_sp = m_exe_ctx.GetProcessSP(); 1712 if (process_sp) { 1713 Error error; 1714 lldb::addr_t load_addr = m_prev_end_addr; 1715 m_prev_end_addr = LLDB_INVALID_ADDRESS; 1716 1717 const size_t argc = command.GetArgumentCount(); 1718 if (argc > 1 || (argc == 0 && load_addr == LLDB_INVALID_ADDRESS)) { 1719 result.AppendErrorWithFormat("'%s' takes one argument:\nUsage: %s\n", 1720 m_cmd_name.c_str(), m_cmd_syntax.c_str()); 1721 result.SetStatus(eReturnStatusFailed); 1722 } else { 1723 const char *load_addr_cstr = command.GetArgumentAtIndex(0); 1724 if (command.GetArgumentCount() == 1) { 1725 load_addr = Args::StringToAddress(&m_exe_ctx, load_addr_cstr, 1726 LLDB_INVALID_ADDRESS, &error); 1727 if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) { 1728 result.AppendErrorWithFormat( 1729 "invalid address argument \"%s\": %s\n", load_addr_cstr, 1730 error.AsCString()); 1731 result.SetStatus(eReturnStatusFailed); 1732 } 1733 } 1734 1735 lldb_private::MemoryRegionInfo range_info; 1736 error = process_sp->GetMemoryRegionInfo(load_addr, range_info); 1737 if (error.Success()) { 1738 lldb_private::Address addr; 1739 ConstString section_name; 1740 if (process_sp->GetTarget().ResolveLoadAddress(load_addr, addr)) { 1741 SectionSP section_sp(addr.GetSection()); 1742 if (section_sp) { 1743 // Got the top most section, not the deepest section 1744 while (section_sp->GetParent()) 1745 section_sp = section_sp->GetParent(); 1746 section_name = section_sp->GetName(); 1747 } 1748 } 1749 result.AppendMessageWithFormat( 1750 "[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") %c%c%c%s%s\n", 1751 range_info.GetRange().GetRangeBase(), 1752 range_info.GetRange().GetRangeEnd(), 1753 range_info.GetReadable() ? 'r' : '-', 1754 range_info.GetWritable() ? 'w' : '-', 1755 range_info.GetExecutable() ? 'x' : '-', section_name ? " " : "", 1756 section_name ? section_name.AsCString() : ""); 1757 m_prev_end_addr = range_info.GetRange().GetRangeEnd(); 1758 result.SetStatus(eReturnStatusSuccessFinishResult); 1759 } else { 1760 result.SetStatus(eReturnStatusFailed); 1761 result.AppendErrorWithFormat("%s\n", error.AsCString()); 1762 } 1763 } 1764 } else { 1765 m_prev_end_addr = LLDB_INVALID_ADDRESS; 1766 result.AppendError("invalid process"); 1767 result.SetStatus(eReturnStatusFailed); 1768 } 1769 return result.Succeeded(); 1770 } 1771 1772 const char *GetRepeatCommand(Args ¤t_command_args, 1773 uint32_t index) override { 1774 // If we repeat this command, repeat it without any arguments so we can 1775 // show the next memory range 1776 return m_cmd_name.c_str(); 1777 } 1778 1779 lldb::addr_t m_prev_end_addr; 1780 }; 1781 1782 //------------------------------------------------------------------------- 1783 // CommandObjectMemory 1784 //------------------------------------------------------------------------- 1785 1786 CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter) 1787 : CommandObjectMultiword( 1788 interpreter, "memory", 1789 "Commands for operating on memory in the current target process.", 1790 "memory <subcommand> [<subcommand-options>]") { 1791 LoadSubCommand("find", 1792 CommandObjectSP(new CommandObjectMemoryFind(interpreter))); 1793 LoadSubCommand("read", 1794 CommandObjectSP(new CommandObjectMemoryRead(interpreter))); 1795 LoadSubCommand("write", 1796 CommandObjectSP(new CommandObjectMemoryWrite(interpreter))); 1797 LoadSubCommand("history", 1798 CommandObjectSP(new CommandObjectMemoryHistory(interpreter))); 1799 LoadSubCommand("region", 1800 CommandObjectSP(new CommandObjectMemoryRegion(interpreter))); 1801 } 1802 1803 CommandObjectMemory::~CommandObjectMemory() = default; 1804