1 //===-- CommandObjectMemory.cpp ---------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "CommandObjectMemory.h"
10 #include "lldb/Core/Debugger.h"
11 #include "lldb/Core/DumpDataExtractor.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/Section.h"
14 #include "lldb/Core/ValueObjectMemory.h"
15 #include "lldb/DataFormatters/ValueObjectPrinter.h"
16 #include "lldb/Expression/ExpressionVariable.h"
17 #include "lldb/Host/OptionParser.h"
18 #include "lldb/Interpreter/CommandInterpreter.h"
19 #include "lldb/Interpreter/CommandReturnObject.h"
20 #include "lldb/Interpreter/OptionArgParser.h"
21 #include "lldb/Interpreter/OptionGroupFormat.h"
22 #include "lldb/Interpreter/OptionGroupOutputFile.h"
23 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
24 #include "lldb/Interpreter/OptionValueLanguage.h"
25 #include "lldb/Interpreter/OptionValueString.h"
26 #include "lldb/Interpreter/Options.h"
27 #include "lldb/Symbol/SymbolFile.h"
28 #include "lldb/Symbol/TypeList.h"
29 #include "lldb/Target/Language.h"
30 #include "lldb/Target/MemoryHistory.h"
31 #include "lldb/Target/MemoryRegionInfo.h"
32 #include "lldb/Target/Process.h"
33 #include "lldb/Target/StackFrame.h"
34 #include "lldb/Target/Target.h"
35 #include "lldb/Target/Thread.h"
36 #include "lldb/Utility/Args.h"
37 #include "lldb/Utility/DataBufferHeap.h"
38 #include "lldb/Utility/DataBufferLLVM.h"
39 #include "lldb/Utility/StreamString.h"
41 #include "lldb/lldb-private.h"
47 using namespace lldb_private;
49 static constexpr OptionDefinition g_read_memory_options[] = {
51 {LLDB_OPT_SET_1, false, "num-per-line", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNumberPerLine, "The number of items per line to display." },
52 {LLDB_OPT_SET_2, false, "binary", 'b', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "If true, memory will be saved as binary. If false, the memory is saved save as an ASCII dump that "
53 "uses the format, size, count and number per line settings." },
55 LLDB_OPT_SET_4, true , "type", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "The name of a type to view memory as." },
56 {LLDB_OPT_SET_4, false, "language", 'x', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeLanguage, "The language of the type to view memory as."},
57 {LLDB_OPT_SET_3, false, "offset", 'E', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCount, "How many elements of the specified type to skip before starting to display data." },
60 LLDB_OPT_SET_3, false, "force", 'r', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Necessary if reading over target.max-memory-read-size bytes." },
64 class OptionGroupReadMemory : public OptionGroup {
66 OptionGroupReadMemory()
67 : m_num_per_line(1, 1), m_output_as_binary(false), m_view_as_type(),
68 m_offset(0, 0), m_language_for_type(eLanguageTypeUnknown) {}
70 ~OptionGroupReadMemory() override = default;
72 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
73 return llvm::makeArrayRef(g_read_memory_options);
76 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
77 ExecutionContext *execution_context) override {
79 const int short_option = g_read_memory_options[option_idx].short_option;
81 switch (short_option) {
83 error = m_num_per_line.SetValueFromString(option_value);
84 if (m_num_per_line.GetCurrentValue() == 0)
85 error.SetErrorStringWithFormat(
86 "invalid value for --num-per-line option '%s'",
87 option_value.str().c_str());
91 m_output_as_binary = true;
95 error = m_view_as_type.SetValueFromString(option_value);
103 error = m_language_for_type.SetValueFromString(option_value);
107 error = m_offset.SetValueFromString(option_value);
111 error.SetErrorStringWithFormat("unrecognized short option '%c'",
118 void OptionParsingStarting(ExecutionContext *execution_context) override {
119 m_num_per_line.Clear();
120 m_output_as_binary = false;
121 m_view_as_type.Clear();
124 m_language_for_type.Clear();
127 Status FinalizeSettings(Target *target, OptionGroupFormat &format_options) {
129 OptionValueUInt64 &byte_size_value = format_options.GetByteSizeValue();
130 OptionValueUInt64 &count_value = format_options.GetCountValue();
131 const bool byte_size_option_set = byte_size_value.OptionWasSet();
132 const bool num_per_line_option_set = m_num_per_line.OptionWasSet();
133 const bool count_option_set = format_options.GetCountValue().OptionWasSet();
135 switch (format_options.GetFormat()) {
140 if (!byte_size_option_set)
142 if (!num_per_line_option_set)
144 if (!count_option_set)
145 format_options.GetCountValue() = 8;
151 case eFormatInstruction:
152 if (count_option_set)
153 byte_size_value = target->GetArchitecture().GetMaximumOpcodeByteSize();
157 case eFormatAddressInfo:
158 if (!byte_size_option_set)
159 byte_size_value = target->GetArchitecture().GetAddressByteSize();
161 if (!count_option_set)
162 format_options.GetCountValue() = 8;
166 byte_size_value = target->GetArchitecture().GetAddressByteSize();
167 if (!num_per_line_option_set)
169 if (!count_option_set)
170 format_options.GetCountValue() = 8;
178 case eFormatUnicode16:
179 case eFormatUnicode32:
180 case eFormatUnsigned:
181 case eFormatHexFloat:
182 if (!byte_size_option_set)
184 if (!num_per_line_option_set)
186 if (!count_option_set)
187 format_options.GetCountValue() = 8;
191 case eFormatBytesWithASCII:
192 if (byte_size_option_set) {
193 if (byte_size_value > 1)
194 error.SetErrorStringWithFormat(
195 "display format (bytes/bytes with ASCII) conflicts with the "
196 "specified byte size %" PRIu64 "\n"
197 "\tconsider using a different display format or don't specify "
199 byte_size_value.GetCurrentValue());
202 if (!num_per_line_option_set)
204 if (!count_option_set)
205 format_options.GetCountValue() = 32;
208 case eFormatCharArray:
210 case eFormatCharPrintable:
211 if (!byte_size_option_set)
213 if (!num_per_line_option_set)
215 if (!count_option_set)
216 format_options.GetCountValue() = 64;
220 if (!byte_size_option_set)
222 if (!num_per_line_option_set)
224 if (!count_option_set)
225 format_options.GetCountValue() = 8;
228 case eFormatComplexInteger:
229 if (!byte_size_option_set)
231 if (!num_per_line_option_set)
233 if (!count_option_set)
234 format_options.GetCountValue() = 8;
238 if (!byte_size_option_set)
240 if (!num_per_line_option_set) {
241 switch (byte_size_value) {
257 if (!count_option_set)
261 case eFormatVectorOfChar:
262 case eFormatVectorOfSInt8:
263 case eFormatVectorOfUInt8:
264 case eFormatVectorOfSInt16:
265 case eFormatVectorOfUInt16:
266 case eFormatVectorOfSInt32:
267 case eFormatVectorOfUInt32:
268 case eFormatVectorOfSInt64:
269 case eFormatVectorOfUInt64:
270 case eFormatVectorOfFloat16:
271 case eFormatVectorOfFloat32:
272 case eFormatVectorOfFloat64:
273 case eFormatVectorOfUInt128:
274 if (!byte_size_option_set)
275 byte_size_value = 128;
276 if (!num_per_line_option_set)
278 if (!count_option_set)
285 bool AnyOptionWasSet() const {
286 return m_num_per_line.OptionWasSet() || m_output_as_binary ||
287 m_view_as_type.OptionWasSet() || m_offset.OptionWasSet() ||
288 m_language_for_type.OptionWasSet();
291 OptionValueUInt64 m_num_per_line;
292 bool m_output_as_binary;
293 OptionValueString m_view_as_type;
295 OptionValueUInt64 m_offset;
296 OptionValueLanguage m_language_for_type;
299 // Read memory from the inferior process
300 class CommandObjectMemoryRead : public CommandObjectParsed {
302 CommandObjectMemoryRead(CommandInterpreter &interpreter)
303 : CommandObjectParsed(
304 interpreter, "memory read",
305 "Read from the memory of the current target process.", nullptr,
306 eCommandRequiresTarget | eCommandProcessMustBePaused),
307 m_option_group(), m_format_options(eFormatBytesWithASCII, 1, 8),
308 m_memory_options(), m_outfile_options(), m_varobj_options(),
309 m_next_addr(LLDB_INVALID_ADDRESS), m_prev_byte_size(0),
310 m_prev_format_options(eFormatBytesWithASCII, 1, 8),
311 m_prev_memory_options(), m_prev_outfile_options(),
312 m_prev_varobj_options() {
313 CommandArgumentEntry arg1;
314 CommandArgumentEntry arg2;
315 CommandArgumentData start_addr_arg;
316 CommandArgumentData end_addr_arg;
318 // Define the first (and only) variant of this arg.
319 start_addr_arg.arg_type = eArgTypeAddressOrExpression;
320 start_addr_arg.arg_repetition = eArgRepeatPlain;
322 // There is only one variant this argument could be; put it into the
324 arg1.push_back(start_addr_arg);
326 // Define the first (and only) variant of this arg.
327 end_addr_arg.arg_type = eArgTypeAddressOrExpression;
328 end_addr_arg.arg_repetition = eArgRepeatOptional;
330 // There is only one variant this argument could be; put it into the
332 arg2.push_back(end_addr_arg);
334 // Push the data for the first argument into the m_arguments vector.
335 m_arguments.push_back(arg1);
336 m_arguments.push_back(arg2);
338 // Add the "--format" and "--count" options to group 1 and 3
339 m_option_group.Append(&m_format_options,
340 OptionGroupFormat::OPTION_GROUP_FORMAT |
341 OptionGroupFormat::OPTION_GROUP_COUNT,
342 LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
343 m_option_group.Append(&m_format_options,
344 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
345 LLDB_OPT_SET_1 | LLDB_OPT_SET_3);
346 // Add the "--size" option to group 1 and 2
347 m_option_group.Append(&m_format_options,
348 OptionGroupFormat::OPTION_GROUP_SIZE,
349 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
350 m_option_group.Append(&m_memory_options);
351 m_option_group.Append(&m_outfile_options, LLDB_OPT_SET_ALL,
352 LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
353 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
354 m_option_group.Finalize();
357 ~CommandObjectMemoryRead() override = default;
359 Options *GetOptions() override { return &m_option_group; }
361 const char *GetRepeatCommand(Args ¤t_command_args,
362 uint32_t index) override {
363 return m_cmd_name.c_str();
367 bool DoExecute(Args &command, CommandReturnObject &result) override {
368 // No need to check "target" for validity as eCommandRequiresTarget ensures
370 Target *target = m_exe_ctx.GetTargetPtr();
372 const size_t argc = command.GetArgumentCount();
374 if ((argc == 0 && m_next_addr == LLDB_INVALID_ADDRESS) || argc > 2) {
375 result.AppendErrorWithFormat("%s takes a start address expression with "
376 "an optional end address expression.\n",
378 result.AppendRawWarning("Expressions should be quoted if they contain "
379 "spaces or other special characters.\n");
380 result.SetStatus(eReturnStatusFailed);
384 CompilerType compiler_type;
387 const char *view_as_type_cstr =
388 m_memory_options.m_view_as_type.GetCurrentValue();
389 if (view_as_type_cstr && view_as_type_cstr[0]) {
390 // We are viewing memory as a type
392 const bool exact_match = false;
394 uint32_t reference_count = 0;
395 uint32_t pointer_count = 0;
398 #define ALL_KEYWORDS \
400 KEYWORD("volatile") \
401 KEYWORD("restrict") \
406 #define KEYWORD(s) s,
407 static const char *g_keywords[] = {ALL_KEYWORDS};
410 #define KEYWORD(s) (sizeof(s) - 1),
411 static const int g_keyword_lengths[] = {ALL_KEYWORDS};
416 static size_t g_num_keywords = sizeof(g_keywords) / sizeof(const char *);
417 std::string type_str(view_as_type_cstr);
419 // Remove all instances of g_keywords that are followed by spaces
420 for (size_t i = 0; i < g_num_keywords; ++i) {
421 const char *keyword = g_keywords[i];
422 int keyword_len = g_keyword_lengths[i];
425 while ((idx = type_str.find(keyword, idx)) != std::string::npos) {
426 if (type_str[idx + keyword_len] == ' ' ||
427 type_str[idx + keyword_len] == '\t') {
428 type_str.erase(idx, keyword_len + 1);
435 bool done = type_str.empty();
437 idx = type_str.find_first_not_of(" \t");
438 if (idx > 0 && idx != std::string::npos)
439 type_str.erase(0, idx);
441 // Strip trailing spaces
442 if (type_str.empty())
445 switch (type_str[type_str.size() - 1]) {
451 type_str.erase(type_str.size() - 1);
455 if (reference_count == 0) {
457 type_str.erase(type_str.size() - 1);
459 result.AppendErrorWithFormat("invalid type string: '%s'\n",
461 result.SetStatus(eReturnStatusFailed);
473 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
474 ConstString lookup_type_name(type_str.c_str());
475 StackFrame *frame = m_exe_ctx.GetFramePtr();
476 ModuleSP search_first;
478 search_first = frame->GetSymbolContext(eSymbolContextModule).module_sp;
480 target->GetImages().FindTypes(search_first.get(), lookup_type_name,
481 exact_match, 1, searched_symbol_files,
484 if (type_list.GetSize() == 0 && lookup_type_name.GetCString()) {
485 LanguageType language_for_type =
486 m_memory_options.m_language_for_type.GetCurrentValue();
487 std::set<LanguageType> languages_to_check;
488 if (language_for_type != eLanguageTypeUnknown) {
489 languages_to_check.insert(language_for_type);
491 languages_to_check = Language::GetSupportedLanguages();
494 std::set<CompilerType> user_defined_types;
495 for (auto lang : languages_to_check) {
496 if (auto *persistent_vars =
497 target->GetPersistentExpressionStateForLanguage(lang)) {
498 if (llvm::Optional<CompilerType> type =
499 persistent_vars->GetCompilerTypeFromPersistentDecl(
501 user_defined_types.emplace(*type);
506 if (user_defined_types.size() > 1) {
507 result.AppendErrorWithFormat(
508 "Mutiple types found matching raw type '%s', please disambiguate "
509 "by specifying the language with -x",
510 lookup_type_name.GetCString());
511 result.SetStatus(eReturnStatusFailed);
515 if (user_defined_types.size() == 1) {
516 compiler_type = *user_defined_types.begin();
520 if (!compiler_type.IsValid()) {
521 if (type_list.GetSize() == 0) {
522 result.AppendErrorWithFormat("unable to find any types that match "
523 "the raw type '%s' for full type '%s'\n",
524 lookup_type_name.GetCString(),
526 result.SetStatus(eReturnStatusFailed);
529 TypeSP type_sp(type_list.GetTypeAtIndex(0));
530 compiler_type = type_sp->GetFullCompilerType();
534 while (pointer_count > 0) {
535 CompilerType pointer_type = compiler_type.GetPointerType();
536 if (pointer_type.IsValid())
537 compiler_type = pointer_type;
539 result.AppendError("unable make a pointer type\n");
540 result.SetStatus(eReturnStatusFailed);
546 llvm::Optional<uint64_t> size = compiler_type.GetByteSize(nullptr);
548 result.AppendErrorWithFormat(
549 "unable to get the byte size of the type '%s'\n",
551 result.SetStatus(eReturnStatusFailed);
554 m_format_options.GetByteSizeValue() = *size;
556 if (!m_format_options.GetCountValue().OptionWasSet())
557 m_format_options.GetCountValue() = 1;
559 error = m_memory_options.FinalizeSettings(target, m_format_options);
562 // Look for invalid combinations of settings
564 result.AppendError(error.AsCString());
565 result.SetStatus(eReturnStatusFailed);
570 size_t total_byte_size = 0;
572 // Use the last address and byte size and all options as they were if no
573 // options have been set
575 total_byte_size = m_prev_byte_size;
576 compiler_type = m_prev_compiler_type;
577 if (!m_format_options.AnyOptionWasSet() &&
578 !m_memory_options.AnyOptionWasSet() &&
579 !m_outfile_options.AnyOptionWasSet() &&
580 !m_varobj_options.AnyOptionWasSet()) {
581 m_format_options = m_prev_format_options;
582 m_memory_options = m_prev_memory_options;
583 m_outfile_options = m_prev_outfile_options;
584 m_varobj_options = m_prev_varobj_options;
588 size_t item_count = m_format_options.GetCountValue().GetCurrentValue();
590 // TODO For non-8-bit byte addressable architectures this needs to be
591 // revisited to fully support all lldb's range of formatting options.
592 // Furthermore code memory reads (for those architectures) will not be
593 // correctly formatted even w/o formatting options.
594 size_t item_byte_size =
595 target->GetArchitecture().GetDataByteSize() > 1
596 ? target->GetArchitecture().GetDataByteSize()
597 : m_format_options.GetByteSizeValue().GetCurrentValue();
599 const size_t num_per_line =
600 m_memory_options.m_num_per_line.GetCurrentValue();
602 if (total_byte_size == 0) {
603 total_byte_size = item_count * item_byte_size;
604 if (total_byte_size == 0)
605 total_byte_size = 32;
609 addr = OptionArgParser::ToAddress(&m_exe_ctx, command[0].ref,
610 LLDB_INVALID_ADDRESS, &error);
612 if (addr == LLDB_INVALID_ADDRESS) {
613 result.AppendError("invalid start address expression.");
614 result.AppendError(error.AsCString());
615 result.SetStatus(eReturnStatusFailed);
620 lldb::addr_t end_addr = OptionArgParser::ToAddress(
621 &m_exe_ctx, command[1].ref, LLDB_INVALID_ADDRESS, nullptr);
622 if (end_addr == LLDB_INVALID_ADDRESS) {
623 result.AppendError("invalid end address expression.");
624 result.AppendError(error.AsCString());
625 result.SetStatus(eReturnStatusFailed);
627 } else if (end_addr <= addr) {
628 result.AppendErrorWithFormat(
629 "end address (0x%" PRIx64
630 ") must be greater that the start address (0x%" PRIx64 ").\n",
632 result.SetStatus(eReturnStatusFailed);
634 } else if (m_format_options.GetCountValue().OptionWasSet()) {
635 result.AppendErrorWithFormat(
636 "specify either the end address (0x%" PRIx64
637 ") or the count (--count %" PRIu64 "), not both.\n",
638 end_addr, (uint64_t)item_count);
639 result.SetStatus(eReturnStatusFailed);
643 total_byte_size = end_addr - addr;
644 item_count = total_byte_size / item_byte_size;
647 uint32_t max_unforced_size = target->GetMaximumMemReadSize();
649 if (total_byte_size > max_unforced_size && !m_memory_options.m_force) {
650 result.AppendErrorWithFormat(
651 "Normally, \'memory read\' will not read over %" PRIu32
654 result.AppendErrorWithFormat(
655 "Please use --force to override this restriction just once.\n");
656 result.AppendErrorWithFormat("or set target.max-memory-read-size if you "
657 "will often need a larger limit.\n");
661 DataBufferSP data_sp;
662 size_t bytes_read = 0;
663 if (compiler_type.GetOpaqueQualType()) {
664 // Make sure we don't display our type as ASCII bytes like the default
666 if (!m_format_options.GetFormatValue().OptionWasSet())
667 m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault);
669 llvm::Optional<uint64_t> size = compiler_type.GetByteSize(nullptr);
671 result.AppendError("can't get size of type");
674 bytes_read = *size * m_format_options.GetCountValue().GetCurrentValue();
677 addr = addr + (*size * m_memory_options.m_offset.GetCurrentValue());
678 } else if (m_format_options.GetFormatValue().GetCurrentValue() !=
680 data_sp = std::make_shared<DataBufferHeap>(total_byte_size, '\0');
681 if (data_sp->GetBytes() == nullptr) {
682 result.AppendErrorWithFormat(
683 "can't allocate 0x%" PRIx32
684 " bytes for the memory read buffer, specify a smaller size to read",
685 (uint32_t)total_byte_size);
686 result.SetStatus(eReturnStatusFailed);
690 Address address(addr, nullptr);
691 bytes_read = target->ReadMemory(address, false, data_sp->GetBytes(),
692 data_sp->GetByteSize(), error);
693 if (bytes_read == 0) {
694 const char *error_cstr = error.AsCString();
695 if (error_cstr && error_cstr[0]) {
696 result.AppendError(error_cstr);
698 result.AppendErrorWithFormat(
699 "failed to read memory from 0x%" PRIx64 ".\n", addr);
701 result.SetStatus(eReturnStatusFailed);
705 if (bytes_read < total_byte_size)
706 result.AppendWarningWithFormat(
707 "Not all bytes (%" PRIu64 "/%" PRIu64
708 ") were able to be read from 0x%" PRIx64 ".\n",
709 (uint64_t)bytes_read, (uint64_t)total_byte_size, addr);
711 // we treat c-strings as a special case because they do not have a fixed
713 if (m_format_options.GetByteSizeValue().OptionWasSet() &&
714 !m_format_options.HasGDBFormat())
715 item_byte_size = m_format_options.GetByteSizeValue().GetCurrentValue();
717 item_byte_size = target->GetMaximumSizeOfStringSummary();
718 if (!m_format_options.GetCountValue().OptionWasSet())
720 data_sp = std::make_shared<DataBufferHeap>(
721 (item_byte_size + 1) * item_count,
722 '\0'); // account for NULLs as necessary
723 if (data_sp->GetBytes() == nullptr) {
724 result.AppendErrorWithFormat(
725 "can't allocate 0x%" PRIx64
726 " bytes for the memory read buffer, specify a smaller size to read",
727 (uint64_t)((item_byte_size + 1) * item_count));
728 result.SetStatus(eReturnStatusFailed);
731 uint8_t *data_ptr = data_sp->GetBytes();
732 auto data_addr = addr;
733 auto count = item_count;
735 bool break_on_no_NULL = false;
736 while (item_count < count) {
738 buffer.resize(item_byte_size + 1, 0);
740 size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0],
741 item_byte_size + 1, error);
743 result.AppendErrorWithFormat(
744 "failed to read memory from 0x%" PRIx64 ".\n", addr);
745 result.SetStatus(eReturnStatusFailed);
749 if (item_byte_size == read) {
750 result.AppendWarningWithFormat(
751 "unable to find a NULL terminated string at 0x%" PRIx64
752 ".Consider increasing the maximum read length.\n",
755 break_on_no_NULL = true;
757 ++read; // account for final NULL byte
759 memcpy(data_ptr, &buffer[0], read);
763 item_count++; // if we break early we know we only read item_count
766 if (break_on_no_NULL)
770 std::make_shared<DataBufferHeap>(data_sp->GetBytes(), bytes_read + 1);
773 m_next_addr = addr + bytes_read;
774 m_prev_byte_size = bytes_read;
775 m_prev_format_options = m_format_options;
776 m_prev_memory_options = m_memory_options;
777 m_prev_outfile_options = m_outfile_options;
778 m_prev_varobj_options = m_varobj_options;
779 m_prev_compiler_type = compiler_type;
781 StreamFile outfile_stream;
782 Stream *output_stream = nullptr;
783 const FileSpec &outfile_spec =
784 m_outfile_options.GetFile().GetCurrentValue();
786 std::string path = outfile_spec.GetPath();
789 uint32_t open_options =
790 File::eOpenOptionWrite | File::eOpenOptionCanCreate;
791 const bool append = m_outfile_options.GetAppend().GetCurrentValue();
793 open_options |= File::eOpenOptionAppend;
795 Status error = FileSystem::Instance().Open(outfile_stream.GetFile(),
796 outfile_spec, open_options);
797 if (error.Success()) {
798 if (m_memory_options.m_output_as_binary) {
799 const size_t bytes_written =
800 outfile_stream.Write(data_sp->GetBytes(), bytes_read);
801 if (bytes_written > 0) {
802 result.GetOutputStream().Printf(
803 "%zi bytes %s to '%s'\n", bytes_written,
804 append ? "appended" : "written", path.c_str());
807 result.AppendErrorWithFormat("Failed to write %" PRIu64
809 (uint64_t)bytes_read, path.c_str());
810 result.SetStatus(eReturnStatusFailed);
814 // We are going to write ASCII to the file just point the
815 // output_stream to our outfile_stream...
816 output_stream = &outfile_stream;
819 result.AppendErrorWithFormat("Failed to open file '%s' for %s.\n",
820 path.c_str(), append ? "append" : "write");
821 result.SetStatus(eReturnStatusFailed);
825 output_stream = &result.GetOutputStream();
828 ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
829 if (compiler_type.GetOpaqueQualType()) {
830 for (uint32_t i = 0; i < item_count; ++i) {
831 addr_t item_addr = addr + (i * item_byte_size);
832 Address address(item_addr);
833 StreamString name_strm;
834 name_strm.Printf("0x%" PRIx64, item_addr);
835 ValueObjectSP valobj_sp(ValueObjectMemory::Create(
836 exe_scope, name_strm.GetString(), address, compiler_type));
838 Format format = m_format_options.GetFormat();
839 if (format != eFormatDefault)
840 valobj_sp->SetFormat(format);
842 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
843 eLanguageRuntimeDescriptionDisplayVerbosityFull, format));
845 valobj_sp->Dump(*output_stream, options);
847 result.AppendErrorWithFormat(
848 "failed to create a value object for: (%s) %s\n",
849 view_as_type_cstr, name_strm.GetData());
850 result.SetStatus(eReturnStatusFailed);
857 result.SetStatus(eReturnStatusSuccessFinishResult);
858 DataExtractor data(data_sp, target->GetArchitecture().GetByteOrder(),
859 target->GetArchitecture().GetAddressByteSize(),
860 target->GetArchitecture().GetDataByteSize());
862 Format format = m_format_options.GetFormat();
863 if (((format == eFormatChar) || (format == eFormatCharPrintable)) &&
864 (item_byte_size != 1)) {
865 // if a count was not passed, or it is 1
866 if (!m_format_options.GetCountValue().OptionWasSet() || item_count == 1) {
867 // this turns requests such as
868 // memory read -fc -s10 -c1 *charPtrPtr
869 // which make no sense (what is a char of size 10?) into a request for
870 // fetching 10 chars of size 1 from the same memory location
871 format = eFormatCharArray;
872 item_count = item_byte_size;
875 // here we passed a count, and it was not 1 so we have a byte_size and
876 // a count we could well multiply those, but instead let's just fail
877 result.AppendErrorWithFormat(
878 "reading memory as characters of size %" PRIu64 " is not supported",
879 (uint64_t)item_byte_size);
880 result.SetStatus(eReturnStatusFailed);
885 assert(output_stream);
886 size_t bytes_dumped = DumpDataExtractor(
887 data, output_stream, 0, format, item_byte_size, item_count,
888 num_per_line / target->GetArchitecture().GetDataByteSize(), addr, 0, 0,
890 m_next_addr = addr + bytes_dumped;
891 output_stream->EOL();
895 OptionGroupOptions m_option_group;
896 OptionGroupFormat m_format_options;
897 OptionGroupReadMemory m_memory_options;
898 OptionGroupOutputFile m_outfile_options;
899 OptionGroupValueObjectDisplay m_varobj_options;
900 lldb::addr_t m_next_addr;
901 lldb::addr_t m_prev_byte_size;
902 OptionGroupFormat m_prev_format_options;
903 OptionGroupReadMemory m_prev_memory_options;
904 OptionGroupOutputFile m_prev_outfile_options;
905 OptionGroupValueObjectDisplay m_prev_varobj_options;
906 CompilerType m_prev_compiler_type;
909 static constexpr OptionDefinition g_memory_find_option_table[] = {
911 {LLDB_OPT_SET_1, true, "expression", 'e', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeExpression, "Evaluate an expression to obtain a byte pattern."},
912 {LLDB_OPT_SET_2, true, "string", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "Use text to find a byte pattern."},
913 {LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCount, "How many times to perform the search."},
914 {LLDB_OPT_SET_ALL, false, "dump-offset", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOffset, "When dumping memory for a match, an offset from the match location to start dumping from."},
918 // Find the specified data in memory
919 class CommandObjectMemoryFind : public CommandObjectParsed {
921 class OptionGroupFindMemory : public OptionGroup {
923 OptionGroupFindMemory() : OptionGroup(), m_count(1), m_offset(0) {}
925 ~OptionGroupFindMemory() override = default;
927 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
928 return llvm::makeArrayRef(g_memory_find_option_table);
931 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
932 ExecutionContext *execution_context) override {
934 const int short_option =
935 g_memory_find_option_table[option_idx].short_option;
937 switch (short_option) {
939 m_expr.SetValueFromString(option_value);
943 m_string.SetValueFromString(option_value);
947 if (m_count.SetValueFromString(option_value).Fail())
948 error.SetErrorString("unrecognized value for count");
952 if (m_offset.SetValueFromString(option_value).Fail())
953 error.SetErrorString("unrecognized value for dump-offset");
957 error.SetErrorStringWithFormat("unrecognized short option '%c'",
964 void OptionParsingStarting(ExecutionContext *execution_context) override {
970 OptionValueString m_expr;
971 OptionValueString m_string;
972 OptionValueUInt64 m_count;
973 OptionValueUInt64 m_offset;
976 CommandObjectMemoryFind(CommandInterpreter &interpreter)
977 : CommandObjectParsed(
978 interpreter, "memory find",
979 "Find a value in the memory of the current target process.",
980 nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched),
981 m_option_group(), m_memory_options() {
982 CommandArgumentEntry arg1;
983 CommandArgumentEntry arg2;
984 CommandArgumentData addr_arg;
985 CommandArgumentData value_arg;
987 // Define the first (and only) variant of this arg.
988 addr_arg.arg_type = eArgTypeAddressOrExpression;
989 addr_arg.arg_repetition = eArgRepeatPlain;
991 // There is only one variant this argument could be; put it into the
993 arg1.push_back(addr_arg);
995 // Define the first (and only) variant of this arg.
996 value_arg.arg_type = eArgTypeAddressOrExpression;
997 value_arg.arg_repetition = eArgRepeatPlain;
999 // There is only one variant this argument could be; put it into the
1001 arg2.push_back(value_arg);
1003 // Push the data for the first argument into the m_arguments vector.
1004 m_arguments.push_back(arg1);
1005 m_arguments.push_back(arg2);
1007 m_option_group.Append(&m_memory_options);
1008 m_option_group.Finalize();
1011 ~CommandObjectMemoryFind() override = default;
1013 Options *GetOptions() override { return &m_option_group; }
1016 class ProcessMemoryIterator {
1018 ProcessMemoryIterator(ProcessSP process_sp, lldb::addr_t base)
1019 : m_process_sp(process_sp), m_base_addr(base), m_is_valid(true) {
1020 lldbassert(process_sp.get() != nullptr);
1023 bool IsValid() { return m_is_valid; }
1025 uint8_t operator[](lldb::addr_t offset) {
1032 m_process_sp->ReadMemory(m_base_addr + offset, &retval, 1, error)) {
1041 ProcessSP m_process_sp;
1042 lldb::addr_t m_base_addr;
1045 bool DoExecute(Args &command, CommandReturnObject &result) override {
1046 // No need to check "process" for validity as eCommandRequiresProcess
1047 // ensures it is valid
1048 Process *process = m_exe_ctx.GetProcessPtr();
1050 const size_t argc = command.GetArgumentCount();
1053 result.AppendError("two addresses needed for memory find");
1058 lldb::addr_t low_addr = OptionArgParser::ToAddress(
1059 &m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error);
1060 if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1061 result.AppendError("invalid low address");
1064 lldb::addr_t high_addr = OptionArgParser::ToAddress(
1065 &m_exe_ctx, command[1].ref, LLDB_INVALID_ADDRESS, &error);
1066 if (high_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1067 result.AppendError("invalid high address");
1071 if (high_addr <= low_addr) {
1073 "starting address must be smaller than ending address");
1077 lldb::addr_t found_location = LLDB_INVALID_ADDRESS;
1079 DataBufferHeap buffer;
1081 if (m_memory_options.m_string.OptionWasSet())
1082 buffer.CopyData(m_memory_options.m_string.GetStringValue());
1083 else if (m_memory_options.m_expr.OptionWasSet()) {
1084 StackFrame *frame = m_exe_ctx.GetFramePtr();
1085 ValueObjectSP result_sp;
1086 if ((eExpressionCompleted ==
1087 process->GetTarget().EvaluateExpression(
1088 m_memory_options.m_expr.GetStringValue(), frame, result_sp)) &&
1090 uint64_t value = result_sp->GetValueAsUnsigned(0);
1091 llvm::Optional<uint64_t> size =
1092 result_sp->GetCompilerType().GetByteSize(nullptr);
1097 uint8_t byte = (uint8_t)value;
1098 buffer.CopyData(&byte, 1);
1101 uint16_t word = (uint16_t)value;
1102 buffer.CopyData(&word, 2);
1105 uint32_t lword = (uint32_t)value;
1106 buffer.CopyData(&lword, 4);
1109 buffer.CopyData(&value, 8);
1115 result.AppendError("unknown type. pass a string instead");
1119 "result size larger than 8 bytes. pass a string instead");
1124 "expression evaluation failed. pass a string instead");
1129 "please pass either a block of text, or an expression to evaluate.");
1133 size_t count = m_memory_options.m_count.GetCurrentValue();
1134 found_location = low_addr;
1135 bool ever_found = false;
1137 found_location = FastSearch(found_location, high_addr, buffer.GetBytes(),
1138 buffer.GetByteSize());
1139 if (found_location == LLDB_INVALID_ADDRESS) {
1141 result.AppendMessage("data not found within the range.\n");
1142 result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
1144 result.AppendMessage("no more matches within the range.\n");
1147 result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n",
1150 DataBufferHeap dumpbuffer(32, 0);
1151 process->ReadMemory(
1152 found_location + m_memory_options.m_offset.GetCurrentValue(),
1153 dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error);
1154 if (!error.Fail()) {
1155 DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(),
1156 process->GetByteOrder(),
1157 process->GetAddressByteSize());
1159 data, &result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1,
1160 dumpbuffer.GetByteSize(), 16,
1161 found_location + m_memory_options.m_offset.GetCurrentValue(), 0, 0);
1162 result.GetOutputStream().EOL();
1170 result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
1174 lldb::addr_t FastSearch(lldb::addr_t low, lldb::addr_t high, uint8_t *buffer,
1175 size_t buffer_size) {
1176 const size_t region_size = high - low;
1178 if (region_size < buffer_size)
1179 return LLDB_INVALID_ADDRESS;
1181 std::vector<size_t> bad_char_heuristic(256, buffer_size);
1182 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1183 ProcessMemoryIterator iterator(process_sp, low);
1185 for (size_t idx = 0; idx < buffer_size - 1; idx++) {
1186 decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx];
1187 bad_char_heuristic[bcu_idx] = buffer_size - idx - 1;
1189 for (size_t s = 0; s <= (region_size - buffer_size);) {
1190 int64_t j = buffer_size - 1;
1191 while (j >= 0 && buffer[j] == iterator[s + j])
1196 s += bad_char_heuristic[iterator[s + buffer_size - 1]];
1199 return LLDB_INVALID_ADDRESS;
1202 OptionGroupOptions m_option_group;
1203 OptionGroupFindMemory m_memory_options;
1206 static constexpr OptionDefinition g_memory_write_option_table[] = {
1208 {LLDB_OPT_SET_1, true, "infile", 'i', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeFilename, "Write memory using the contents of a file."},
1209 {LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOffset, "Start writing bytes from an offset within the input file."},
1213 // Write memory to the inferior process
1214 class CommandObjectMemoryWrite : public CommandObjectParsed {
1216 class OptionGroupWriteMemory : public OptionGroup {
1218 OptionGroupWriteMemory() : OptionGroup() {}
1220 ~OptionGroupWriteMemory() override = default;
1222 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1223 return llvm::makeArrayRef(g_memory_write_option_table);
1226 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1227 ExecutionContext *execution_context) override {
1229 const int short_option =
1230 g_memory_write_option_table[option_idx].short_option;
1232 switch (short_option) {
1234 m_infile.SetFile(option_value, FileSpec::Style::native);
1235 FileSystem::Instance().Resolve(m_infile);
1236 if (!FileSystem::Instance().Exists(m_infile)) {
1238 error.SetErrorStringWithFormat("input file does not exist: '%s'",
1239 option_value.str().c_str());
1244 if (option_value.getAsInteger(0, m_infile_offset)) {
1245 m_infile_offset = 0;
1246 error.SetErrorStringWithFormat("invalid offset string '%s'",
1247 option_value.str().c_str());
1252 error.SetErrorStringWithFormat("unrecognized short option '%c'",
1259 void OptionParsingStarting(ExecutionContext *execution_context) override {
1261 m_infile_offset = 0;
1265 off_t m_infile_offset;
1268 CommandObjectMemoryWrite(CommandInterpreter &interpreter)
1269 : CommandObjectParsed(
1270 interpreter, "memory write",
1271 "Write to the memory of the current target process.", nullptr,
1272 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
1273 m_option_group(), m_format_options(eFormatBytes, 1, UINT64_MAX),
1274 m_memory_options() {
1275 CommandArgumentEntry arg1;
1276 CommandArgumentEntry arg2;
1277 CommandArgumentData addr_arg;
1278 CommandArgumentData value_arg;
1280 // Define the first (and only) variant of this arg.
1281 addr_arg.arg_type = eArgTypeAddress;
1282 addr_arg.arg_repetition = eArgRepeatPlain;
1284 // There is only one variant this argument could be; put it into the
1286 arg1.push_back(addr_arg);
1288 // Define the first (and only) variant of this arg.
1289 value_arg.arg_type = eArgTypeValue;
1290 value_arg.arg_repetition = eArgRepeatPlus;
1292 // There is only one variant this argument could be; put it into the
1294 arg2.push_back(value_arg);
1296 // Push the data for the first argument into the m_arguments vector.
1297 m_arguments.push_back(arg1);
1298 m_arguments.push_back(arg2);
1300 m_option_group.Append(&m_format_options,
1301 OptionGroupFormat::OPTION_GROUP_FORMAT,
1303 m_option_group.Append(&m_format_options,
1304 OptionGroupFormat::OPTION_GROUP_SIZE,
1305 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
1306 m_option_group.Append(&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2);
1307 m_option_group.Finalize();
1310 ~CommandObjectMemoryWrite() override = default;
1312 Options *GetOptions() override { return &m_option_group; }
1314 bool UIntValueIsValidForSize(uint64_t uval64, size_t total_byte_size) {
1315 if (total_byte_size > 8)
1318 if (total_byte_size == 8)
1321 const uint64_t max = ((uint64_t)1 << (uint64_t)(total_byte_size * 8)) - 1;
1322 return uval64 <= max;
1325 bool SIntValueIsValidForSize(int64_t sval64, size_t total_byte_size) {
1326 if (total_byte_size > 8)
1329 if (total_byte_size == 8)
1332 const int64_t max = ((int64_t)1 << (uint64_t)(total_byte_size * 8 - 1)) - 1;
1333 const int64_t min = ~(max);
1334 return min <= sval64 && sval64 <= max;
1338 bool DoExecute(Args &command, CommandReturnObject &result) override {
1339 // No need to check "process" for validity as eCommandRequiresProcess
1340 // ensures it is valid
1341 Process *process = m_exe_ctx.GetProcessPtr();
1343 const size_t argc = command.GetArgumentCount();
1345 if (m_memory_options.m_infile) {
1347 result.AppendErrorWithFormat(
1348 "%s takes a destination address when writing file contents.\n",
1349 m_cmd_name.c_str());
1350 result.SetStatus(eReturnStatusFailed);
1353 } else if (argc < 2) {
1354 result.AppendErrorWithFormat(
1355 "%s takes a destination address and at least one value.\n",
1356 m_cmd_name.c_str());
1357 result.SetStatus(eReturnStatusFailed);
1361 StreamString buffer(
1363 process->GetTarget().GetArchitecture().GetAddressByteSize(),
1364 process->GetTarget().GetArchitecture().GetByteOrder());
1366 OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue();
1367 size_t item_byte_size = byte_size_value.GetCurrentValue();
1370 lldb::addr_t addr = OptionArgParser::ToAddress(
1371 &m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error);
1373 if (addr == LLDB_INVALID_ADDRESS) {
1374 result.AppendError("invalid address expression\n");
1375 result.AppendError(error.AsCString());
1376 result.SetStatus(eReturnStatusFailed);
1380 if (m_memory_options.m_infile) {
1381 size_t length = SIZE_MAX;
1382 if (item_byte_size > 1)
1383 length = item_byte_size;
1384 auto data_sp = FileSystem::Instance().CreateDataBuffer(
1385 m_memory_options.m_infile.GetPath(), length,
1386 m_memory_options.m_infile_offset);
1388 length = data_sp->GetByteSize();
1391 size_t bytes_written =
1392 process->WriteMemory(addr, data_sp->GetBytes(), length, error);
1394 if (bytes_written == length) {
1395 // All bytes written
1396 result.GetOutputStream().Printf(
1397 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n",
1398 (uint64_t)bytes_written, addr);
1399 result.SetStatus(eReturnStatusSuccessFinishResult);
1400 } else if (bytes_written > 0) {
1401 // Some byte written
1402 result.GetOutputStream().Printf(
1403 "%" PRIu64 " bytes of %" PRIu64
1404 " requested were written to 0x%" PRIx64 "\n",
1405 (uint64_t)bytes_written, (uint64_t)length, addr);
1406 result.SetStatus(eReturnStatusSuccessFinishResult);
1408 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1410 addr, error.AsCString());
1411 result.SetStatus(eReturnStatusFailed);
1415 result.AppendErrorWithFormat("Unable to read contents of file.\n");
1416 result.SetStatus(eReturnStatusFailed);
1418 return result.Succeeded();
1419 } else if (item_byte_size == 0) {
1420 if (m_format_options.GetFormat() == eFormatPointer)
1421 item_byte_size = buffer.GetAddressByteSize();
1426 command.Shift(); // shift off the address argument
1429 bool success = false;
1430 for (auto &entry : command) {
1431 switch (m_format_options.GetFormat()) {
1433 case eFormatFloat: // TODO: add support for floats soon
1434 case eFormatCharPrintable:
1435 case eFormatBytesWithASCII:
1436 case eFormatComplex:
1438 case eFormatUnicode16:
1439 case eFormatUnicode32:
1440 case eFormatVectorOfChar:
1441 case eFormatVectorOfSInt8:
1442 case eFormatVectorOfUInt8:
1443 case eFormatVectorOfSInt16:
1444 case eFormatVectorOfUInt16:
1445 case eFormatVectorOfSInt32:
1446 case eFormatVectorOfUInt32:
1447 case eFormatVectorOfSInt64:
1448 case eFormatVectorOfUInt64:
1449 case eFormatVectorOfFloat16:
1450 case eFormatVectorOfFloat32:
1451 case eFormatVectorOfFloat64:
1452 case eFormatVectorOfUInt128:
1454 case eFormatComplexInteger:
1455 case eFormatAddressInfo:
1456 case eFormatHexFloat:
1457 case eFormatInstruction:
1459 result.AppendError("unsupported format for writing memory");
1460 result.SetStatus(eReturnStatusFailed);
1463 case eFormatDefault:
1466 case eFormatHexUppercase:
1467 case eFormatPointer:
1470 // Be careful, getAsInteger with a radix of 16 rejects "0xab" so we
1471 // have to special case that:
1472 bool success = false;
1473 if (entry.ref.startswith("0x"))
1474 success = !entry.ref.getAsInteger(0, uval64);
1476 success = !entry.ref.getAsInteger(16, uval64);
1478 result.AppendErrorWithFormat(
1479 "'%s' is not a valid hex string value.\n", entry.c_str());
1480 result.SetStatus(eReturnStatusFailed);
1482 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1483 result.AppendErrorWithFormat("Value 0x%" PRIx64
1484 " is too large to fit in a %" PRIu64
1485 " byte unsigned integer value.\n",
1486 uval64, (uint64_t)item_byte_size);
1487 result.SetStatus(eReturnStatusFailed);
1490 buffer.PutMaxHex64(uval64, item_byte_size);
1493 case eFormatBoolean:
1494 uval64 = OptionArgParser::ToBoolean(entry.ref, false, &success);
1496 result.AppendErrorWithFormat(
1497 "'%s' is not a valid boolean string value.\n", entry.c_str());
1498 result.SetStatus(eReturnStatusFailed);
1501 buffer.PutMaxHex64(uval64, item_byte_size);
1505 if (entry.ref.getAsInteger(2, uval64)) {
1506 result.AppendErrorWithFormat(
1507 "'%s' is not a valid binary string value.\n", entry.c_str());
1508 result.SetStatus(eReturnStatusFailed);
1510 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1511 result.AppendErrorWithFormat("Value 0x%" PRIx64
1512 " is too large to fit in a %" PRIu64
1513 " byte unsigned integer value.\n",
1514 uval64, (uint64_t)item_byte_size);
1515 result.SetStatus(eReturnStatusFailed);
1518 buffer.PutMaxHex64(uval64, item_byte_size);
1521 case eFormatCharArray:
1523 case eFormatCString: {
1524 if (entry.ref.empty())
1527 size_t len = entry.ref.size();
1528 // Include the NULL for C strings...
1529 if (m_format_options.GetFormat() == eFormatCString)
1532 if (process->WriteMemory(addr, entry.c_str(), len, error) == len) {
1535 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1537 addr, error.AsCString());
1538 result.SetStatus(eReturnStatusFailed);
1543 case eFormatDecimal:
1544 if (entry.ref.getAsInteger(0, sval64)) {
1545 result.AppendErrorWithFormat(
1546 "'%s' is not a valid signed decimal value.\n", entry.c_str());
1547 result.SetStatus(eReturnStatusFailed);
1549 } else if (!SIntValueIsValidForSize(sval64, item_byte_size)) {
1550 result.AppendErrorWithFormat(
1551 "Value %" PRIi64 " is too large or small to fit in a %" PRIu64
1552 " byte signed integer value.\n",
1553 sval64, (uint64_t)item_byte_size);
1554 result.SetStatus(eReturnStatusFailed);
1557 buffer.PutMaxHex64(sval64, item_byte_size);
1560 case eFormatUnsigned:
1562 if (!entry.ref.getAsInteger(0, uval64)) {
1563 result.AppendErrorWithFormat(
1564 "'%s' is not a valid unsigned decimal string value.\n",
1566 result.SetStatus(eReturnStatusFailed);
1568 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1569 result.AppendErrorWithFormat("Value %" PRIu64
1570 " is too large to fit in a %" PRIu64
1571 " byte unsigned integer value.\n",
1572 uval64, (uint64_t)item_byte_size);
1573 result.SetStatus(eReturnStatusFailed);
1576 buffer.PutMaxHex64(uval64, item_byte_size);
1580 if (entry.ref.getAsInteger(8, uval64)) {
1581 result.AppendErrorWithFormat(
1582 "'%s' is not a valid octal string value.\n", entry.c_str());
1583 result.SetStatus(eReturnStatusFailed);
1585 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1586 result.AppendErrorWithFormat("Value %" PRIo64
1587 " is too large to fit in a %" PRIu64
1588 " byte unsigned integer value.\n",
1589 uval64, (uint64_t)item_byte_size);
1590 result.SetStatus(eReturnStatusFailed);
1593 buffer.PutMaxHex64(uval64, item_byte_size);
1598 if (!buffer.GetString().empty()) {
1600 if (process->WriteMemory(addr, buffer.GetString().data(),
1601 buffer.GetString().size(),
1602 error) == buffer.GetString().size())
1605 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1607 addr, error.AsCString());
1608 result.SetStatus(eReturnStatusFailed);
1615 OptionGroupOptions m_option_group;
1616 OptionGroupFormat m_format_options;
1617 OptionGroupWriteMemory m_memory_options;
1620 // Get malloc/free history of a memory address.
1621 class CommandObjectMemoryHistory : public CommandObjectParsed {
1623 CommandObjectMemoryHistory(CommandInterpreter &interpreter)
1624 : CommandObjectParsed(
1625 interpreter, "memory history", "Print recorded stack traces for "
1626 "allocation/deallocation events "
1627 "associated with an address.",
1629 eCommandRequiresTarget | eCommandRequiresProcess |
1630 eCommandProcessMustBePaused | eCommandProcessMustBeLaunched) {
1631 CommandArgumentEntry arg1;
1632 CommandArgumentData addr_arg;
1634 // Define the first (and only) variant of this arg.
1635 addr_arg.arg_type = eArgTypeAddress;
1636 addr_arg.arg_repetition = eArgRepeatPlain;
1638 // There is only one variant this argument could be; put it into the
1640 arg1.push_back(addr_arg);
1642 // Push the data for the first argument into the m_arguments vector.
1643 m_arguments.push_back(arg1);
1646 ~CommandObjectMemoryHistory() override = default;
1648 const char *GetRepeatCommand(Args ¤t_command_args,
1649 uint32_t index) override {
1650 return m_cmd_name.c_str();
1654 bool DoExecute(Args &command, CommandReturnObject &result) override {
1655 const size_t argc = command.GetArgumentCount();
1657 if (argc == 0 || argc > 1) {
1658 result.AppendErrorWithFormat("%s takes an address expression",
1659 m_cmd_name.c_str());
1660 result.SetStatus(eReturnStatusFailed);
1665 lldb::addr_t addr = OptionArgParser::ToAddress(
1666 &m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error);
1668 if (addr == LLDB_INVALID_ADDRESS) {
1669 result.AppendError("invalid address expression");
1670 result.AppendError(error.AsCString());
1671 result.SetStatus(eReturnStatusFailed);
1675 Stream *output_stream = &result.GetOutputStream();
1677 const ProcessSP &process_sp = m_exe_ctx.GetProcessSP();
1678 const MemoryHistorySP &memory_history =
1679 MemoryHistory::FindPlugin(process_sp);
1681 if (!memory_history) {
1682 result.AppendError("no available memory history provider");
1683 result.SetStatus(eReturnStatusFailed);
1687 HistoryThreads thread_list = memory_history->GetHistoryThreads(addr);
1689 const bool stop_format = false;
1690 for (auto thread : thread_list) {
1691 thread->GetStatus(*output_stream, 0, UINT32_MAX, 0, stop_format);
1694 result.SetStatus(eReturnStatusSuccessFinishResult);
1700 // CommandObjectMemoryRegion
1701 #pragma mark CommandObjectMemoryRegion
1703 class CommandObjectMemoryRegion : public CommandObjectParsed {
1705 CommandObjectMemoryRegion(CommandInterpreter &interpreter)
1706 : CommandObjectParsed(interpreter, "memory region",
1707 "Get information on the memory region containing "
1708 "an address in the current target process.",
1709 "memory region ADDR",
1710 eCommandRequiresProcess | eCommandTryTargetAPILock |
1711 eCommandProcessMustBeLaunched),
1712 m_prev_end_addr(LLDB_INVALID_ADDRESS) {}
1714 ~CommandObjectMemoryRegion() override = default;
1717 bool DoExecute(Args &command, CommandReturnObject &result) override {
1718 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1721 lldb::addr_t load_addr = m_prev_end_addr;
1722 m_prev_end_addr = LLDB_INVALID_ADDRESS;
1724 const size_t argc = command.GetArgumentCount();
1725 if (argc > 1 || (argc == 0 && load_addr == LLDB_INVALID_ADDRESS)) {
1726 result.AppendErrorWithFormat("'%s' takes one argument:\nUsage: %s\n",
1727 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1728 result.SetStatus(eReturnStatusFailed);
1730 if (command.GetArgumentCount() == 1) {
1731 auto load_addr_str = command[0].ref;
1732 load_addr = OptionArgParser::ToAddress(&m_exe_ctx, load_addr_str,
1733 LLDB_INVALID_ADDRESS, &error);
1734 if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) {
1735 result.AppendErrorWithFormat(
1736 "invalid address argument \"%s\": %s\n", command[0].c_str(),
1738 result.SetStatus(eReturnStatusFailed);
1742 lldb_private::MemoryRegionInfo range_info;
1743 error = process_sp->GetMemoryRegionInfo(load_addr, range_info);
1744 if (error.Success()) {
1745 lldb_private::Address addr;
1746 ConstString name = range_info.GetName();
1747 ConstString section_name;
1748 if (process_sp->GetTarget().ResolveLoadAddress(load_addr, addr)) {
1749 SectionSP section_sp(addr.GetSection());
1751 // Got the top most section, not the deepest section
1752 while (section_sp->GetParent())
1753 section_sp = section_sp->GetParent();
1754 section_name = section_sp->GetName();
1757 result.AppendMessageWithFormat(
1758 "[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") %c%c%c%s%s%s%s\n",
1759 range_info.GetRange().GetRangeBase(),
1760 range_info.GetRange().GetRangeEnd(),
1761 range_info.GetReadable() ? 'r' : '-',
1762 range_info.GetWritable() ? 'w' : '-',
1763 range_info.GetExecutable() ? 'x' : '-',
1764 name ? " " : "", name.AsCString(""),
1765 section_name ? " " : "", section_name.AsCString(""));
1766 m_prev_end_addr = range_info.GetRange().GetRangeEnd();
1767 result.SetStatus(eReturnStatusSuccessFinishResult);
1769 result.SetStatus(eReturnStatusFailed);
1770 result.AppendErrorWithFormat("%s\n", error.AsCString());
1774 m_prev_end_addr = LLDB_INVALID_ADDRESS;
1775 result.AppendError("invalid process");
1776 result.SetStatus(eReturnStatusFailed);
1778 return result.Succeeded();
1781 const char *GetRepeatCommand(Args ¤t_command_args,
1782 uint32_t index) override {
1783 // If we repeat this command, repeat it without any arguments so we can
1784 // show the next memory range
1785 return m_cmd_name.c_str();
1788 lldb::addr_t m_prev_end_addr;
1791 // CommandObjectMemory
1793 CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter)
1794 : CommandObjectMultiword(
1795 interpreter, "memory",
1796 "Commands for operating on memory in the current target process.",
1797 "memory <subcommand> [<subcommand-options>]") {
1798 LoadSubCommand("find",
1799 CommandObjectSP(new CommandObjectMemoryFind(interpreter)));
1800 LoadSubCommand("read",
1801 CommandObjectSP(new CommandObjectMemoryRead(interpreter)));
1802 LoadSubCommand("write",
1803 CommandObjectSP(new CommandObjectMemoryWrite(interpreter)));
1804 LoadSubCommand("history",
1805 CommandObjectSP(new CommandObjectMemoryHistory(interpreter)));
1806 LoadSubCommand("region",
1807 CommandObjectSP(new CommandObjectMemoryRegion(interpreter)));
1810 CommandObjectMemory::~CommandObjectMemory() = default;