1 //===-- CommandObjectMemory.cpp -------------------------------------------===//
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 "CommandObjectMemoryTag.h"
11 #include "lldb/Core/DumpDataExtractor.h"
12 #include "lldb/Core/Section.h"
13 #include "lldb/Core/ValueObjectMemory.h"
14 #include "lldb/Expression/ExpressionVariable.h"
15 #include "lldb/Host/OptionParser.h"
16 #include "lldb/Interpreter/CommandOptionArgumentTable.h"
17 #include "lldb/Interpreter/CommandReturnObject.h"
18 #include "lldb/Interpreter/OptionArgParser.h"
19 #include "lldb/Interpreter/OptionGroupFormat.h"
20 #include "lldb/Interpreter/OptionGroupMemoryTag.h"
21 #include "lldb/Interpreter/OptionGroupOutputFile.h"
22 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
23 #include "lldb/Interpreter/OptionValueLanguage.h"
24 #include "lldb/Interpreter/OptionValueString.h"
25 #include "lldb/Interpreter/Options.h"
26 #include "lldb/Symbol/SymbolFile.h"
27 #include "lldb/Symbol/TypeList.h"
28 #include "lldb/Target/ABI.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/StreamString.h"
39 #include "llvm/Support/MathExtras.h"
45 using namespace lldb_private
;
47 #define LLDB_OPTIONS_memory_read
48 #include "CommandOptions.inc"
50 class OptionGroupReadMemory
: public OptionGroup
{
52 OptionGroupReadMemory()
53 : m_num_per_line(1, 1), m_offset(0, 0),
54 m_language_for_type(eLanguageTypeUnknown
) {}
56 ~OptionGroupReadMemory() override
= default;
58 llvm::ArrayRef
<OptionDefinition
> GetDefinitions() override
{
59 return llvm::ArrayRef(g_memory_read_options
);
62 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_value
,
63 ExecutionContext
*execution_context
) override
{
65 const int short_option
= g_memory_read_options
[option_idx
].short_option
;
67 switch (short_option
) {
69 error
= m_num_per_line
.SetValueFromString(option_value
);
70 if (m_num_per_line
.GetCurrentValue() == 0)
71 error
.SetErrorStringWithFormat(
72 "invalid value for --num-per-line option '%s'",
73 option_value
.str().c_str());
77 m_output_as_binary
= true;
81 error
= m_view_as_type
.SetValueFromString(option_value
);
89 error
= m_language_for_type
.SetValueFromString(option_value
);
93 error
= m_offset
.SetValueFromString(option_value
);
97 llvm_unreachable("Unimplemented option");
102 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
103 m_num_per_line
.Clear();
104 m_output_as_binary
= false;
105 m_view_as_type
.Clear();
108 m_language_for_type
.Clear();
111 Status
FinalizeSettings(Target
*target
, OptionGroupFormat
&format_options
) {
113 OptionValueUInt64
&byte_size_value
= format_options
.GetByteSizeValue();
114 OptionValueUInt64
&count_value
= format_options
.GetCountValue();
115 const bool byte_size_option_set
= byte_size_value
.OptionWasSet();
116 const bool num_per_line_option_set
= m_num_per_line
.OptionWasSet();
117 const bool count_option_set
= format_options
.GetCountValue().OptionWasSet();
119 switch (format_options
.GetFormat()) {
124 if (!byte_size_option_set
)
126 if (!num_per_line_option_set
)
128 if (!count_option_set
)
129 format_options
.GetCountValue() = 8;
135 case eFormatInstruction
:
136 if (count_option_set
)
137 byte_size_value
= target
->GetArchitecture().GetMaximumOpcodeByteSize();
141 case eFormatAddressInfo
:
142 if (!byte_size_option_set
)
143 byte_size_value
= target
->GetArchitecture().GetAddressByteSize();
145 if (!count_option_set
)
146 format_options
.GetCountValue() = 8;
150 byte_size_value
= target
->GetArchitecture().GetAddressByteSize();
151 if (!num_per_line_option_set
)
153 if (!count_option_set
)
154 format_options
.GetCountValue() = 8;
162 case eFormatUnicode8
:
163 case eFormatUnicode16
:
164 case eFormatUnicode32
:
165 case eFormatUnsigned
:
166 case eFormatHexFloat
:
167 if (!byte_size_option_set
)
169 if (!num_per_line_option_set
)
171 if (!count_option_set
)
172 format_options
.GetCountValue() = 8;
176 case eFormatBytesWithASCII
:
177 if (byte_size_option_set
) {
178 if (byte_size_value
> 1)
179 error
.SetErrorStringWithFormat(
180 "display format (bytes/bytes with ASCII) conflicts with the "
181 "specified byte size %" PRIu64
"\n"
182 "\tconsider using a different display format or don't specify "
184 byte_size_value
.GetCurrentValue());
187 if (!num_per_line_option_set
)
189 if (!count_option_set
)
190 format_options
.GetCountValue() = 32;
193 case eFormatCharArray
:
195 case eFormatCharPrintable
:
196 if (!byte_size_option_set
)
198 if (!num_per_line_option_set
)
200 if (!count_option_set
)
201 format_options
.GetCountValue() = 64;
205 if (!byte_size_option_set
)
207 if (!num_per_line_option_set
)
209 if (!count_option_set
)
210 format_options
.GetCountValue() = 8;
213 case eFormatComplexInteger
:
214 if (!byte_size_option_set
)
216 if (!num_per_line_option_set
)
218 if (!count_option_set
)
219 format_options
.GetCountValue() = 8;
223 if (!byte_size_option_set
)
225 if (!num_per_line_option_set
) {
226 switch (byte_size_value
) {
242 if (!count_option_set
)
246 case eFormatVectorOfChar
:
247 case eFormatVectorOfSInt8
:
248 case eFormatVectorOfUInt8
:
249 case eFormatVectorOfSInt16
:
250 case eFormatVectorOfUInt16
:
251 case eFormatVectorOfSInt32
:
252 case eFormatVectorOfUInt32
:
253 case eFormatVectorOfSInt64
:
254 case eFormatVectorOfUInt64
:
255 case eFormatVectorOfFloat16
:
256 case eFormatVectorOfFloat32
:
257 case eFormatVectorOfFloat64
:
258 case eFormatVectorOfUInt128
:
259 if (!byte_size_option_set
)
260 byte_size_value
= 128;
261 if (!num_per_line_option_set
)
263 if (!count_option_set
)
270 bool AnyOptionWasSet() const {
271 return m_num_per_line
.OptionWasSet() || m_output_as_binary
||
272 m_view_as_type
.OptionWasSet() || m_offset
.OptionWasSet() ||
273 m_language_for_type
.OptionWasSet();
276 OptionValueUInt64 m_num_per_line
;
277 bool m_output_as_binary
= false;
278 OptionValueString m_view_as_type
;
279 bool m_force
= false;
280 OptionValueUInt64 m_offset
;
281 OptionValueLanguage m_language_for_type
;
284 // Read memory from the inferior process
285 class CommandObjectMemoryRead
: public CommandObjectParsed
{
287 CommandObjectMemoryRead(CommandInterpreter
&interpreter
)
288 : CommandObjectParsed(
289 interpreter
, "memory read",
290 "Read from the memory of the current target process.", nullptr,
291 eCommandRequiresTarget
| eCommandProcessMustBePaused
),
292 m_format_options(eFormatBytesWithASCII
, 1, 8),
293 m_memory_tag_options(/*note_binary=*/true),
294 m_prev_format_options(eFormatBytesWithASCII
, 1, 8) {
295 CommandArgumentEntry arg1
;
296 CommandArgumentEntry arg2
;
297 CommandArgumentData start_addr_arg
;
298 CommandArgumentData end_addr_arg
;
300 // Define the first (and only) variant of this arg.
301 start_addr_arg
.arg_type
= eArgTypeAddressOrExpression
;
302 start_addr_arg
.arg_repetition
= eArgRepeatPlain
;
304 // There is only one variant this argument could be; put it into the
306 arg1
.push_back(start_addr_arg
);
308 // Define the first (and only) variant of this arg.
309 end_addr_arg
.arg_type
= eArgTypeAddressOrExpression
;
310 end_addr_arg
.arg_repetition
= eArgRepeatOptional
;
312 // There is only one variant this argument could be; put it into the
314 arg2
.push_back(end_addr_arg
);
316 // Push the data for the first argument into the m_arguments vector.
317 m_arguments
.push_back(arg1
);
318 m_arguments
.push_back(arg2
);
320 // Add the "--format" and "--count" options to group 1 and 3
321 m_option_group
.Append(&m_format_options
,
322 OptionGroupFormat::OPTION_GROUP_FORMAT
|
323 OptionGroupFormat::OPTION_GROUP_COUNT
,
324 LLDB_OPT_SET_1
| LLDB_OPT_SET_2
| LLDB_OPT_SET_3
);
325 m_option_group
.Append(&m_format_options
,
326 OptionGroupFormat::OPTION_GROUP_GDB_FMT
,
327 LLDB_OPT_SET_1
| LLDB_OPT_SET_3
);
328 // Add the "--size" option to group 1 and 2
329 m_option_group
.Append(&m_format_options
,
330 OptionGroupFormat::OPTION_GROUP_SIZE
,
331 LLDB_OPT_SET_1
| LLDB_OPT_SET_2
);
332 m_option_group
.Append(&m_memory_options
);
333 m_option_group
.Append(&m_outfile_options
, LLDB_OPT_SET_ALL
,
334 LLDB_OPT_SET_1
| LLDB_OPT_SET_2
| LLDB_OPT_SET_3
);
335 m_option_group
.Append(&m_varobj_options
, LLDB_OPT_SET_ALL
, LLDB_OPT_SET_3
);
336 m_option_group
.Append(&m_memory_tag_options
, LLDB_OPT_SET_ALL
,
338 m_option_group
.Finalize();
341 ~CommandObjectMemoryRead() override
= default;
343 Options
*GetOptions() override
{ return &m_option_group
; }
345 std::optional
<std::string
> GetRepeatCommand(Args
¤t_command_args
,
346 uint32_t index
) override
{
351 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
352 // No need to check "target" for validity as eCommandRequiresTarget ensures
354 Target
*target
= m_exe_ctx
.GetTargetPtr();
356 const size_t argc
= command
.GetArgumentCount();
358 if ((argc
== 0 && m_next_addr
== LLDB_INVALID_ADDRESS
) || argc
> 2) {
359 result
.AppendErrorWithFormat("%s takes a start address expression with "
360 "an optional end address expression.\n",
362 result
.AppendWarning("Expressions should be quoted if they contain "
363 "spaces or other special characters.");
367 CompilerType compiler_type
;
370 const char *view_as_type_cstr
=
371 m_memory_options
.m_view_as_type
.GetCurrentValue();
372 if (view_as_type_cstr
&& view_as_type_cstr
[0]) {
373 // We are viewing memory as a type
375 const bool exact_match
= false;
377 uint32_t reference_count
= 0;
378 uint32_t pointer_count
= 0;
381 #define ALL_KEYWORDS \
383 KEYWORD("volatile") \
384 KEYWORD("restrict") \
389 #define KEYWORD(s) s,
390 static const char *g_keywords
[] = {ALL_KEYWORDS
};
393 #define KEYWORD(s) (sizeof(s) - 1),
394 static const int g_keyword_lengths
[] = {ALL_KEYWORDS
};
399 static size_t g_num_keywords
= sizeof(g_keywords
) / sizeof(const char *);
400 std::string
type_str(view_as_type_cstr
);
402 // Remove all instances of g_keywords that are followed by spaces
403 for (size_t i
= 0; i
< g_num_keywords
; ++i
) {
404 const char *keyword
= g_keywords
[i
];
405 int keyword_len
= g_keyword_lengths
[i
];
408 while ((idx
= type_str
.find(keyword
, idx
)) != std::string::npos
) {
409 if (type_str
[idx
+ keyword_len
] == ' ' ||
410 type_str
[idx
+ keyword_len
] == '\t') {
411 type_str
.erase(idx
, keyword_len
+ 1);
418 bool done
= type_str
.empty();
420 idx
= type_str
.find_first_not_of(" \t");
421 if (idx
> 0 && idx
!= std::string::npos
)
422 type_str
.erase(0, idx
);
424 // Strip trailing spaces
425 if (type_str
.empty())
428 switch (type_str
[type_str
.size() - 1]) {
434 type_str
.erase(type_str
.size() - 1);
438 if (reference_count
== 0) {
440 type_str
.erase(type_str
.size() - 1);
442 result
.AppendErrorWithFormat("invalid type string: '%s'\n",
455 llvm::DenseSet
<lldb_private::SymbolFile
*> searched_symbol_files
;
456 ConstString
lookup_type_name(type_str
.c_str());
457 StackFrame
*frame
= m_exe_ctx
.GetFramePtr();
458 ModuleSP search_first
;
460 search_first
= frame
->GetSymbolContext(eSymbolContextModule
).module_sp
;
462 target
->GetImages().FindTypes(search_first
.get(), lookup_type_name
,
463 exact_match
, 1, searched_symbol_files
,
466 if (type_list
.GetSize() == 0 && lookup_type_name
.GetCString()) {
467 LanguageType language_for_type
=
468 m_memory_options
.m_language_for_type
.GetCurrentValue();
469 std::set
<LanguageType
> languages_to_check
;
470 if (language_for_type
!= eLanguageTypeUnknown
) {
471 languages_to_check
.insert(language_for_type
);
473 languages_to_check
= Language::GetSupportedLanguages();
476 std::set
<CompilerType
> user_defined_types
;
477 for (auto lang
: languages_to_check
) {
478 if (auto *persistent_vars
=
479 target
->GetPersistentExpressionStateForLanguage(lang
)) {
480 if (std::optional
<CompilerType
> type
=
481 persistent_vars
->GetCompilerTypeFromPersistentDecl(
483 user_defined_types
.emplace(*type
);
488 if (user_defined_types
.size() > 1) {
489 result
.AppendErrorWithFormat(
490 "Mutiple types found matching raw type '%s', please disambiguate "
491 "by specifying the language with -x",
492 lookup_type_name
.GetCString());
496 if (user_defined_types
.size() == 1) {
497 compiler_type
= *user_defined_types
.begin();
501 if (!compiler_type
.IsValid()) {
502 if (type_list
.GetSize() == 0) {
503 result
.AppendErrorWithFormat("unable to find any types that match "
504 "the raw type '%s' for full type '%s'\n",
505 lookup_type_name
.GetCString(),
509 TypeSP
type_sp(type_list
.GetTypeAtIndex(0));
510 compiler_type
= type_sp
->GetFullCompilerType();
514 while (pointer_count
> 0) {
515 CompilerType pointer_type
= compiler_type
.GetPointerType();
516 if (pointer_type
.IsValid())
517 compiler_type
= pointer_type
;
519 result
.AppendError("unable make a pointer type\n");
525 std::optional
<uint64_t> size
= compiler_type
.GetByteSize(nullptr);
527 result
.AppendErrorWithFormat(
528 "unable to get the byte size of the type '%s'\n",
532 m_format_options
.GetByteSizeValue() = *size
;
534 if (!m_format_options
.GetCountValue().OptionWasSet())
535 m_format_options
.GetCountValue() = 1;
537 error
= m_memory_options
.FinalizeSettings(target
, m_format_options
);
540 // Look for invalid combinations of settings
542 result
.AppendError(error
.AsCString());
547 size_t total_byte_size
= 0;
549 // Use the last address and byte size and all options as they were if no
550 // options have been set
552 total_byte_size
= m_prev_byte_size
;
553 compiler_type
= m_prev_compiler_type
;
554 if (!m_format_options
.AnyOptionWasSet() &&
555 !m_memory_options
.AnyOptionWasSet() &&
556 !m_outfile_options
.AnyOptionWasSet() &&
557 !m_varobj_options
.AnyOptionWasSet() &&
558 !m_memory_tag_options
.AnyOptionWasSet()) {
559 m_format_options
= m_prev_format_options
;
560 m_memory_options
= m_prev_memory_options
;
561 m_outfile_options
= m_prev_outfile_options
;
562 m_varobj_options
= m_prev_varobj_options
;
563 m_memory_tag_options
= m_prev_memory_tag_options
;
567 size_t item_count
= m_format_options
.GetCountValue().GetCurrentValue();
569 // TODO For non-8-bit byte addressable architectures this needs to be
570 // revisited to fully support all lldb's range of formatting options.
571 // Furthermore code memory reads (for those architectures) will not be
572 // correctly formatted even w/o formatting options.
573 size_t item_byte_size
=
574 target
->GetArchitecture().GetDataByteSize() > 1
575 ? target
->GetArchitecture().GetDataByteSize()
576 : m_format_options
.GetByteSizeValue().GetCurrentValue();
578 const size_t num_per_line
=
579 m_memory_options
.m_num_per_line
.GetCurrentValue();
581 if (total_byte_size
== 0) {
582 total_byte_size
= item_count
* item_byte_size
;
583 if (total_byte_size
== 0)
584 total_byte_size
= 32;
588 addr
= OptionArgParser::ToAddress(&m_exe_ctx
, command
[0].ref(),
589 LLDB_INVALID_ADDRESS
, &error
);
591 if (addr
== LLDB_INVALID_ADDRESS
) {
592 result
.AppendError("invalid start address expression.");
593 result
.AppendError(error
.AsCString());
598 lldb::addr_t end_addr
= OptionArgParser::ToAddress(
599 &m_exe_ctx
, command
[1].ref(), LLDB_INVALID_ADDRESS
, nullptr);
601 if (end_addr
== LLDB_INVALID_ADDRESS
) {
602 result
.AppendError("invalid end address expression.");
603 result
.AppendError(error
.AsCString());
605 } else if (end_addr
<= addr
) {
606 result
.AppendErrorWithFormat(
607 "end address (0x%" PRIx64
608 ") must be greater than the start address (0x%" PRIx64
").\n",
611 } else if (m_format_options
.GetCountValue().OptionWasSet()) {
612 result
.AppendErrorWithFormat(
613 "specify either the end address (0x%" PRIx64
614 ") or the count (--count %" PRIu64
"), not both.\n",
615 end_addr
, (uint64_t)item_count
);
619 total_byte_size
= end_addr
- addr
;
620 item_count
= total_byte_size
/ item_byte_size
;
623 uint32_t max_unforced_size
= target
->GetMaximumMemReadSize();
625 if (total_byte_size
> max_unforced_size
&& !m_memory_options
.m_force
) {
626 result
.AppendErrorWithFormat(
627 "Normally, \'memory read\' will not read over %" PRIu32
630 result
.AppendErrorWithFormat(
631 "Please use --force to override this restriction just once.\n");
632 result
.AppendErrorWithFormat("or set target.max-memory-read-size if you "
633 "will often need a larger limit.\n");
637 WritableDataBufferSP data_sp
;
638 size_t bytes_read
= 0;
639 if (compiler_type
.GetOpaqueQualType()) {
640 // Make sure we don't display our type as ASCII bytes like the default
642 if (!m_format_options
.GetFormatValue().OptionWasSet())
643 m_format_options
.GetFormatValue().SetCurrentValue(eFormatDefault
);
645 std::optional
<uint64_t> size
= compiler_type
.GetByteSize(nullptr);
647 result
.AppendError("can't get size of type");
650 bytes_read
= *size
* m_format_options
.GetCountValue().GetCurrentValue();
653 addr
= addr
+ (*size
* m_memory_options
.m_offset
.GetCurrentValue());
654 } else if (m_format_options
.GetFormatValue().GetCurrentValue() !=
656 data_sp
= std::make_shared
<DataBufferHeap
>(total_byte_size
, '\0');
657 if (data_sp
->GetBytes() == nullptr) {
658 result
.AppendErrorWithFormat(
659 "can't allocate 0x%" PRIx32
660 " bytes for the memory read buffer, specify a smaller size to read",
661 (uint32_t)total_byte_size
);
665 Address
address(addr
, nullptr);
666 bytes_read
= target
->ReadMemory(address
, data_sp
->GetBytes(),
667 data_sp
->GetByteSize(), error
, true);
668 if (bytes_read
== 0) {
669 const char *error_cstr
= error
.AsCString();
670 if (error_cstr
&& error_cstr
[0]) {
671 result
.AppendError(error_cstr
);
673 result
.AppendErrorWithFormat(
674 "failed to read memory from 0x%" PRIx64
".\n", addr
);
679 if (bytes_read
< total_byte_size
)
680 result
.AppendWarningWithFormat(
681 "Not all bytes (%" PRIu64
"/%" PRIu64
682 ") were able to be read from 0x%" PRIx64
".\n",
683 (uint64_t)bytes_read
, (uint64_t)total_byte_size
, addr
);
685 // we treat c-strings as a special case because they do not have a fixed
687 if (m_format_options
.GetByteSizeValue().OptionWasSet() &&
688 !m_format_options
.HasGDBFormat())
689 item_byte_size
= m_format_options
.GetByteSizeValue().GetCurrentValue();
691 item_byte_size
= target
->GetMaximumSizeOfStringSummary();
692 if (!m_format_options
.GetCountValue().OptionWasSet())
694 data_sp
= std::make_shared
<DataBufferHeap
>(
695 (item_byte_size
+ 1) * item_count
,
696 '\0'); // account for NULLs as necessary
697 if (data_sp
->GetBytes() == nullptr) {
698 result
.AppendErrorWithFormat(
699 "can't allocate 0x%" PRIx64
700 " bytes for the memory read buffer, specify a smaller size to read",
701 (uint64_t)((item_byte_size
+ 1) * item_count
));
704 uint8_t *data_ptr
= data_sp
->GetBytes();
705 auto data_addr
= addr
;
706 auto count
= item_count
;
708 bool break_on_no_NULL
= false;
709 while (item_count
< count
) {
711 buffer
.resize(item_byte_size
+ 1, 0);
713 size_t read
= target
->ReadCStringFromMemory(data_addr
, &buffer
[0],
714 item_byte_size
+ 1, error
);
716 result
.AppendErrorWithFormat(
717 "failed to read memory from 0x%" PRIx64
".\n", addr
);
721 if (item_byte_size
== read
) {
722 result
.AppendWarningWithFormat(
723 "unable to find a NULL terminated string at 0x%" PRIx64
724 ". Consider increasing the maximum read length.\n",
727 break_on_no_NULL
= true;
729 ++read
; // account for final NULL byte
731 memcpy(data_ptr
, &buffer
[0], read
);
735 item_count
++; // if we break early we know we only read item_count
738 if (break_on_no_NULL
)
742 std::make_shared
<DataBufferHeap
>(data_sp
->GetBytes(), bytes_read
+ 1);
745 m_next_addr
= addr
+ bytes_read
;
746 m_prev_byte_size
= bytes_read
;
747 m_prev_format_options
= m_format_options
;
748 m_prev_memory_options
= m_memory_options
;
749 m_prev_outfile_options
= m_outfile_options
;
750 m_prev_varobj_options
= m_varobj_options
;
751 m_prev_memory_tag_options
= m_memory_tag_options
;
752 m_prev_compiler_type
= compiler_type
;
754 std::unique_ptr
<Stream
> output_stream_storage
;
755 Stream
*output_stream_p
= nullptr;
756 const FileSpec
&outfile_spec
=
757 m_outfile_options
.GetFile().GetCurrentValue();
759 std::string path
= outfile_spec
.GetPath();
762 File::OpenOptions open_options
=
763 File::eOpenOptionWriteOnly
| File::eOpenOptionCanCreate
;
764 const bool append
= m_outfile_options
.GetAppend().GetCurrentValue();
766 append
? File::eOpenOptionAppend
: File::eOpenOptionTruncate
;
768 auto outfile
= FileSystem::Instance().Open(outfile_spec
, open_options
);
771 auto outfile_stream_up
=
772 std::make_unique
<StreamFile
>(std::move(outfile
.get()));
773 if (m_memory_options
.m_output_as_binary
) {
774 const size_t bytes_written
=
775 outfile_stream_up
->Write(data_sp
->GetBytes(), bytes_read
);
776 if (bytes_written
> 0) {
777 result
.GetOutputStream().Printf(
778 "%zi bytes %s to '%s'\n", bytes_written
,
779 append
? "appended" : "written", path
.c_str());
782 result
.AppendErrorWithFormat("Failed to write %" PRIu64
784 (uint64_t)bytes_read
, path
.c_str());
788 // We are going to write ASCII to the file just point the
789 // output_stream to our outfile_stream...
790 output_stream_storage
= std::move(outfile_stream_up
);
791 output_stream_p
= output_stream_storage
.get();
794 result
.AppendErrorWithFormat("Failed to open file '%s' for %s:\n",
795 path
.c_str(), append
? "append" : "write");
797 result
.AppendError(llvm::toString(outfile
.takeError()));
801 output_stream_p
= &result
.GetOutputStream();
804 ExecutionContextScope
*exe_scope
= m_exe_ctx
.GetBestExecutionContextScope();
805 if (compiler_type
.GetOpaqueQualType()) {
806 for (uint32_t i
= 0; i
< item_count
; ++i
) {
807 addr_t item_addr
= addr
+ (i
* item_byte_size
);
808 Address
address(item_addr
);
809 StreamString name_strm
;
810 name_strm
.Printf("0x%" PRIx64
, item_addr
);
811 ValueObjectSP
valobj_sp(ValueObjectMemory::Create(
812 exe_scope
, name_strm
.GetString(), address
, compiler_type
));
814 Format format
= m_format_options
.GetFormat();
815 if (format
!= eFormatDefault
)
816 valobj_sp
->SetFormat(format
);
818 DumpValueObjectOptions
options(m_varobj_options
.GetAsDumpOptions(
819 eLanguageRuntimeDescriptionDisplayVerbosityFull
, format
));
821 valobj_sp
->Dump(*output_stream_p
, options
);
823 result
.AppendErrorWithFormat(
824 "failed to create a value object for: (%s) %s\n",
825 view_as_type_cstr
, name_strm
.GetData());
832 result
.SetStatus(eReturnStatusSuccessFinishResult
);
833 DataExtractor
data(data_sp
, target
->GetArchitecture().GetByteOrder(),
834 target
->GetArchitecture().GetAddressByteSize(),
835 target
->GetArchitecture().GetDataByteSize());
837 Format format
= m_format_options
.GetFormat();
838 if (((format
== eFormatChar
) || (format
== eFormatCharPrintable
)) &&
839 (item_byte_size
!= 1)) {
840 // if a count was not passed, or it is 1
841 if (!m_format_options
.GetCountValue().OptionWasSet() || item_count
== 1) {
842 // this turns requests such as
843 // memory read -fc -s10 -c1 *charPtrPtr
844 // which make no sense (what is a char of size 10?) into a request for
845 // fetching 10 chars of size 1 from the same memory location
846 format
= eFormatCharArray
;
847 item_count
= item_byte_size
;
850 // here we passed a count, and it was not 1 so we have a byte_size and
851 // a count we could well multiply those, but instead let's just fail
852 result
.AppendErrorWithFormat(
853 "reading memory as characters of size %" PRIu64
" is not supported",
854 (uint64_t)item_byte_size
);
859 assert(output_stream_p
);
860 size_t bytes_dumped
= DumpDataExtractor(
861 data
, output_stream_p
, 0, format
, item_byte_size
, item_count
,
862 num_per_line
/ target
->GetArchitecture().GetDataByteSize(), addr
, 0, 0,
863 exe_scope
, m_memory_tag_options
.GetShowTags().GetCurrentValue());
864 m_next_addr
= addr
+ bytes_dumped
;
865 output_stream_p
->EOL();
868 OptionGroupOptions m_option_group
;
869 OptionGroupFormat m_format_options
;
870 OptionGroupReadMemory m_memory_options
;
871 OptionGroupOutputFile m_outfile_options
;
872 OptionGroupValueObjectDisplay m_varobj_options
;
873 OptionGroupMemoryTag m_memory_tag_options
;
874 lldb::addr_t m_next_addr
= LLDB_INVALID_ADDRESS
;
875 lldb::addr_t m_prev_byte_size
= 0;
876 OptionGroupFormat m_prev_format_options
;
877 OptionGroupReadMemory m_prev_memory_options
;
878 OptionGroupOutputFile m_prev_outfile_options
;
879 OptionGroupValueObjectDisplay m_prev_varobj_options
;
880 OptionGroupMemoryTag m_prev_memory_tag_options
;
881 CompilerType m_prev_compiler_type
;
884 #define LLDB_OPTIONS_memory_find
885 #include "CommandOptions.inc"
887 // Find the specified data in memory
888 class CommandObjectMemoryFind
: public CommandObjectParsed
{
890 class OptionGroupFindMemory
: public OptionGroup
{
892 OptionGroupFindMemory() : m_count(1), m_offset(0) {}
894 ~OptionGroupFindMemory() override
= default;
896 llvm::ArrayRef
<OptionDefinition
> GetDefinitions() override
{
897 return llvm::ArrayRef(g_memory_find_options
);
900 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_value
,
901 ExecutionContext
*execution_context
) override
{
903 const int short_option
= g_memory_find_options
[option_idx
].short_option
;
905 switch (short_option
) {
907 m_expr
.SetValueFromString(option_value
);
911 m_string
.SetValueFromString(option_value
);
915 if (m_count
.SetValueFromString(option_value
).Fail())
916 error
.SetErrorString("unrecognized value for count");
920 if (m_offset
.SetValueFromString(option_value
).Fail())
921 error
.SetErrorString("unrecognized value for dump-offset");
925 llvm_unreachable("Unimplemented option");
930 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
936 OptionValueString m_expr
;
937 OptionValueString m_string
;
938 OptionValueUInt64 m_count
;
939 OptionValueUInt64 m_offset
;
942 CommandObjectMemoryFind(CommandInterpreter
&interpreter
)
943 : CommandObjectParsed(
944 interpreter
, "memory find",
945 "Find a value in the memory of the current target process.",
946 nullptr, eCommandRequiresProcess
| eCommandProcessMustBeLaunched
) {
947 CommandArgumentEntry arg1
;
948 CommandArgumentEntry arg2
;
949 CommandArgumentData addr_arg
;
950 CommandArgumentData value_arg
;
952 // Define the first (and only) variant of this arg.
953 addr_arg
.arg_type
= eArgTypeAddressOrExpression
;
954 addr_arg
.arg_repetition
= eArgRepeatPlain
;
956 // There is only one variant this argument could be; put it into the
958 arg1
.push_back(addr_arg
);
960 // Define the first (and only) variant of this arg.
961 value_arg
.arg_type
= eArgTypeAddressOrExpression
;
962 value_arg
.arg_repetition
= eArgRepeatPlain
;
964 // There is only one variant this argument could be; put it into the
966 arg2
.push_back(value_arg
);
968 // Push the data for the first argument into the m_arguments vector.
969 m_arguments
.push_back(arg1
);
970 m_arguments
.push_back(arg2
);
972 m_option_group
.Append(&m_memory_options
);
973 m_option_group
.Append(&m_memory_tag_options
, LLDB_OPT_SET_ALL
,
975 m_option_group
.Finalize();
978 ~CommandObjectMemoryFind() override
= default;
980 Options
*GetOptions() override
{ return &m_option_group
; }
983 class ProcessMemoryIterator
{
985 ProcessMemoryIterator(ProcessSP process_sp
, lldb::addr_t base
)
986 : m_process_sp(process_sp
), m_base_addr(base
) {
987 lldbassert(process_sp
.get() != nullptr);
990 bool IsValid() { return m_is_valid
; }
992 uint8_t operator[](lldb::addr_t offset
) {
999 m_process_sp
->ReadMemory(m_base_addr
+ offset
, &retval
, 1, error
)) {
1008 ProcessSP m_process_sp
;
1009 lldb::addr_t m_base_addr
;
1010 bool m_is_valid
= true;
1012 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
1013 // No need to check "process" for validity as eCommandRequiresProcess
1014 // ensures it is valid
1015 Process
*process
= m_exe_ctx
.GetProcessPtr();
1017 const size_t argc
= command
.GetArgumentCount();
1020 result
.AppendError("two addresses needed for memory find");
1025 lldb::addr_t low_addr
= OptionArgParser::ToAddress(
1026 &m_exe_ctx
, command
[0].ref(), LLDB_INVALID_ADDRESS
, &error
);
1027 if (low_addr
== LLDB_INVALID_ADDRESS
|| error
.Fail()) {
1028 result
.AppendError("invalid low address");
1031 lldb::addr_t high_addr
= OptionArgParser::ToAddress(
1032 &m_exe_ctx
, command
[1].ref(), LLDB_INVALID_ADDRESS
, &error
);
1033 if (high_addr
== LLDB_INVALID_ADDRESS
|| error
.Fail()) {
1034 result
.AppendError("invalid high address");
1038 if (high_addr
<= low_addr
) {
1040 "starting address must be smaller than ending address");
1044 lldb::addr_t found_location
= LLDB_INVALID_ADDRESS
;
1046 DataBufferHeap buffer
;
1048 if (m_memory_options
.m_string
.OptionWasSet()) {
1049 llvm::StringRef str
=
1050 m_memory_options
.m_string
.GetValueAs
<llvm::StringRef
>().value_or("");
1052 result
.AppendError("search string must have non-zero length.");
1055 buffer
.CopyData(str
);
1056 } else if (m_memory_options
.m_expr
.OptionWasSet()) {
1057 StackFrame
*frame
= m_exe_ctx
.GetFramePtr();
1058 ValueObjectSP result_sp
;
1059 if ((eExpressionCompleted
==
1060 process
->GetTarget().EvaluateExpression(
1061 m_memory_options
.m_expr
.GetValueAs
<llvm::StringRef
>().value_or(
1063 frame
, result_sp
)) &&
1065 uint64_t value
= result_sp
->GetValueAsUnsigned(0);
1066 std::optional
<uint64_t> size
=
1067 result_sp
->GetCompilerType().GetByteSize(nullptr);
1072 uint8_t byte
= (uint8_t)value
;
1073 buffer
.CopyData(&byte
, 1);
1076 uint16_t word
= (uint16_t)value
;
1077 buffer
.CopyData(&word
, 2);
1080 uint32_t lword
= (uint32_t)value
;
1081 buffer
.CopyData(&lword
, 4);
1084 buffer
.CopyData(&value
, 8);
1090 result
.AppendError("unknown type. pass a string instead");
1094 "result size larger than 8 bytes. pass a string instead");
1099 "expression evaluation failed. pass a string instead");
1104 "please pass either a block of text, or an expression to evaluate.");
1108 size_t count
= m_memory_options
.m_count
.GetCurrentValue();
1109 found_location
= low_addr
;
1110 bool ever_found
= false;
1112 found_location
= FastSearch(found_location
, high_addr
, buffer
.GetBytes(),
1113 buffer
.GetByteSize());
1114 if (found_location
== LLDB_INVALID_ADDRESS
) {
1116 result
.AppendMessage("data not found within the range.\n");
1117 result
.SetStatus(lldb::eReturnStatusSuccessFinishNoResult
);
1119 result
.AppendMessage("no more matches within the range.\n");
1122 result
.AppendMessageWithFormat("data found at location: 0x%" PRIx64
"\n",
1125 DataBufferHeap
dumpbuffer(32, 0);
1126 process
->ReadMemory(
1127 found_location
+ m_memory_options
.m_offset
.GetCurrentValue(),
1128 dumpbuffer
.GetBytes(), dumpbuffer
.GetByteSize(), error
);
1129 if (!error
.Fail()) {
1130 DataExtractor
data(dumpbuffer
.GetBytes(), dumpbuffer
.GetByteSize(),
1131 process
->GetByteOrder(),
1132 process
->GetAddressByteSize());
1134 data
, &result
.GetOutputStream(), 0, lldb::eFormatBytesWithASCII
, 1,
1135 dumpbuffer
.GetByteSize(), 16,
1136 found_location
+ m_memory_options
.m_offset
.GetCurrentValue(), 0, 0,
1137 m_exe_ctx
.GetBestExecutionContextScope(),
1138 m_memory_tag_options
.GetShowTags().GetCurrentValue());
1139 result
.GetOutputStream().EOL();
1147 result
.SetStatus(lldb::eReturnStatusSuccessFinishResult
);
1150 lldb::addr_t
FastSearch(lldb::addr_t low
, lldb::addr_t high
, uint8_t *buffer
,
1151 size_t buffer_size
) {
1152 const size_t region_size
= high
- low
;
1154 if (region_size
< buffer_size
)
1155 return LLDB_INVALID_ADDRESS
;
1157 std::vector
<size_t> bad_char_heuristic(256, buffer_size
);
1158 ProcessSP process_sp
= m_exe_ctx
.GetProcessSP();
1159 ProcessMemoryIterator
iterator(process_sp
, low
);
1161 for (size_t idx
= 0; idx
< buffer_size
- 1; idx
++) {
1162 decltype(bad_char_heuristic
)::size_type bcu_idx
= buffer
[idx
];
1163 bad_char_heuristic
[bcu_idx
] = buffer_size
- idx
- 1;
1165 for (size_t s
= 0; s
<= (region_size
- buffer_size
);) {
1166 int64_t j
= buffer_size
- 1;
1167 while (j
>= 0 && buffer
[j
] == iterator
[s
+ j
])
1172 s
+= bad_char_heuristic
[iterator
[s
+ buffer_size
- 1]];
1175 return LLDB_INVALID_ADDRESS
;
1178 OptionGroupOptions m_option_group
;
1179 OptionGroupFindMemory m_memory_options
;
1180 OptionGroupMemoryTag m_memory_tag_options
;
1183 #define LLDB_OPTIONS_memory_write
1184 #include "CommandOptions.inc"
1186 // Write memory to the inferior process
1187 class CommandObjectMemoryWrite
: public CommandObjectParsed
{
1189 class OptionGroupWriteMemory
: public OptionGroup
{
1191 OptionGroupWriteMemory() = default;
1193 ~OptionGroupWriteMemory() override
= default;
1195 llvm::ArrayRef
<OptionDefinition
> GetDefinitions() override
{
1196 return llvm::ArrayRef(g_memory_write_options
);
1199 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_value
,
1200 ExecutionContext
*execution_context
) override
{
1202 const int short_option
= g_memory_write_options
[option_idx
].short_option
;
1204 switch (short_option
) {
1206 m_infile
.SetFile(option_value
, FileSpec::Style::native
);
1207 FileSystem::Instance().Resolve(m_infile
);
1208 if (!FileSystem::Instance().Exists(m_infile
)) {
1210 error
.SetErrorStringWithFormat("input file does not exist: '%s'",
1211 option_value
.str().c_str());
1216 if (option_value
.getAsInteger(0, m_infile_offset
)) {
1217 m_infile_offset
= 0;
1218 error
.SetErrorStringWithFormat("invalid offset string '%s'",
1219 option_value
.str().c_str());
1224 llvm_unreachable("Unimplemented option");
1229 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
1231 m_infile_offset
= 0;
1235 off_t m_infile_offset
;
1238 CommandObjectMemoryWrite(CommandInterpreter
&interpreter
)
1239 : CommandObjectParsed(
1240 interpreter
, "memory write",
1241 "Write to the memory of the current target process.", nullptr,
1242 eCommandRequiresProcess
| eCommandProcessMustBeLaunched
),
1244 eFormatBytes
, 1, UINT64_MAX
,
1247 "The format to use for each of the value to be written."),
1248 std::make_tuple(eArgTypeByteSize
,
1249 "The size in bytes to write from input file or "
1251 CommandArgumentEntry arg1
;
1252 CommandArgumentEntry arg2
;
1253 CommandArgumentData addr_arg
;
1254 CommandArgumentData value_arg
;
1256 // Define the first (and only) variant of this arg.
1257 addr_arg
.arg_type
= eArgTypeAddress
;
1258 addr_arg
.arg_repetition
= eArgRepeatPlain
;
1260 // There is only one variant this argument could be; put it into the
1262 arg1
.push_back(addr_arg
);
1264 // Define the first (and only) variant of this arg.
1265 value_arg
.arg_type
= eArgTypeValue
;
1266 value_arg
.arg_repetition
= eArgRepeatPlus
;
1267 value_arg
.arg_opt_set_association
= LLDB_OPT_SET_1
;
1269 // There is only one variant this argument could be; put it into the
1271 arg2
.push_back(value_arg
);
1273 // Push the data for the first argument into the m_arguments vector.
1274 m_arguments
.push_back(arg1
);
1275 m_arguments
.push_back(arg2
);
1277 m_option_group
.Append(&m_format_options
,
1278 OptionGroupFormat::OPTION_GROUP_FORMAT
,
1280 m_option_group
.Append(&m_format_options
,
1281 OptionGroupFormat::OPTION_GROUP_SIZE
,
1282 LLDB_OPT_SET_1
| LLDB_OPT_SET_2
);
1283 m_option_group
.Append(&m_memory_options
, LLDB_OPT_SET_ALL
, LLDB_OPT_SET_2
);
1284 m_option_group
.Finalize();
1287 ~CommandObjectMemoryWrite() override
= default;
1289 Options
*GetOptions() override
{ return &m_option_group
; }
1292 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
1293 // No need to check "process" for validity as eCommandRequiresProcess
1294 // ensures it is valid
1295 Process
*process
= m_exe_ctx
.GetProcessPtr();
1297 const size_t argc
= command
.GetArgumentCount();
1299 if (m_memory_options
.m_infile
) {
1301 result
.AppendErrorWithFormat(
1302 "%s takes a destination address when writing file contents.\n",
1303 m_cmd_name
.c_str());
1307 result
.AppendErrorWithFormat(
1308 "%s takes only a destination address when writing file contents.\n",
1309 m_cmd_name
.c_str());
1312 } else if (argc
< 2) {
1313 result
.AppendErrorWithFormat(
1314 "%s takes a destination address and at least one value.\n",
1315 m_cmd_name
.c_str());
1319 StreamString
buffer(
1321 process
->GetTarget().GetArchitecture().GetAddressByteSize(),
1322 process
->GetTarget().GetArchitecture().GetByteOrder());
1324 OptionValueUInt64
&byte_size_value
= m_format_options
.GetByteSizeValue();
1325 size_t item_byte_size
= byte_size_value
.GetCurrentValue();
1328 lldb::addr_t addr
= OptionArgParser::ToAddress(
1329 &m_exe_ctx
, command
[0].ref(), LLDB_INVALID_ADDRESS
, &error
);
1331 if (addr
== LLDB_INVALID_ADDRESS
) {
1332 result
.AppendError("invalid address expression\n");
1333 result
.AppendError(error
.AsCString());
1337 if (m_memory_options
.m_infile
) {
1338 size_t length
= SIZE_MAX
;
1339 if (item_byte_size
> 1)
1340 length
= item_byte_size
;
1341 auto data_sp
= FileSystem::Instance().CreateDataBuffer(
1342 m_memory_options
.m_infile
.GetPath(), length
,
1343 m_memory_options
.m_infile_offset
);
1345 length
= data_sp
->GetByteSize();
1348 size_t bytes_written
=
1349 process
->WriteMemory(addr
, data_sp
->GetBytes(), length
, error
);
1351 if (bytes_written
== length
) {
1352 // All bytes written
1353 result
.GetOutputStream().Printf(
1354 "%" PRIu64
" bytes were written to 0x%" PRIx64
"\n",
1355 (uint64_t)bytes_written
, addr
);
1356 result
.SetStatus(eReturnStatusSuccessFinishResult
);
1357 } else if (bytes_written
> 0) {
1358 // Some byte written
1359 result
.GetOutputStream().Printf(
1360 "%" PRIu64
" bytes of %" PRIu64
1361 " requested were written to 0x%" PRIx64
"\n",
1362 (uint64_t)bytes_written
, (uint64_t)length
, addr
);
1363 result
.SetStatus(eReturnStatusSuccessFinishResult
);
1365 result
.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1367 addr
, error
.AsCString());
1371 result
.AppendErrorWithFormat("Unable to read contents of file.\n");
1374 } else if (item_byte_size
== 0) {
1375 if (m_format_options
.GetFormat() == eFormatPointer
)
1376 item_byte_size
= buffer
.GetAddressByteSize();
1381 command
.Shift(); // shift off the address argument
1384 bool success
= false;
1385 for (auto &entry
: command
) {
1386 switch (m_format_options
.GetFormat()) {
1388 case eFormatFloat
: // TODO: add support for floats soon
1389 case eFormatCharPrintable
:
1390 case eFormatBytesWithASCII
:
1391 case eFormatComplex
:
1393 case eFormatUnicode8
:
1394 case eFormatUnicode16
:
1395 case eFormatUnicode32
:
1396 case eFormatVectorOfChar
:
1397 case eFormatVectorOfSInt8
:
1398 case eFormatVectorOfUInt8
:
1399 case eFormatVectorOfSInt16
:
1400 case eFormatVectorOfUInt16
:
1401 case eFormatVectorOfSInt32
:
1402 case eFormatVectorOfUInt32
:
1403 case eFormatVectorOfSInt64
:
1404 case eFormatVectorOfUInt64
:
1405 case eFormatVectorOfFloat16
:
1406 case eFormatVectorOfFloat32
:
1407 case eFormatVectorOfFloat64
:
1408 case eFormatVectorOfUInt128
:
1410 case eFormatComplexInteger
:
1411 case eFormatAddressInfo
:
1412 case eFormatHexFloat
:
1413 case eFormatInstruction
:
1415 result
.AppendError("unsupported format for writing memory");
1418 case eFormatDefault
:
1421 case eFormatHexUppercase
:
1422 case eFormatPointer
: {
1424 // Be careful, getAsInteger with a radix of 16 rejects "0xab" so we
1425 // have to special case that:
1426 bool success
= false;
1427 if (entry
.ref().startswith("0x"))
1428 success
= !entry
.ref().getAsInteger(0, uval64
);
1430 success
= !entry
.ref().getAsInteger(16, uval64
);
1432 result
.AppendErrorWithFormat(
1433 "'%s' is not a valid hex string value.\n", entry
.c_str());
1435 } else if (!llvm::isUIntN(item_byte_size
* 8, uval64
)) {
1436 result
.AppendErrorWithFormat("Value 0x%" PRIx64
1437 " is too large to fit in a %" PRIu64
1438 " byte unsigned integer value.\n",
1439 uval64
, (uint64_t)item_byte_size
);
1442 buffer
.PutMaxHex64(uval64
, item_byte_size
);
1445 case eFormatBoolean
:
1446 uval64
= OptionArgParser::ToBoolean(entry
.ref(), false, &success
);
1448 result
.AppendErrorWithFormat(
1449 "'%s' is not a valid boolean string value.\n", entry
.c_str());
1452 buffer
.PutMaxHex64(uval64
, item_byte_size
);
1456 if (entry
.ref().getAsInteger(2, uval64
)) {
1457 result
.AppendErrorWithFormat(
1458 "'%s' is not a valid binary string value.\n", entry
.c_str());
1460 } else if (!llvm::isUIntN(item_byte_size
* 8, uval64
)) {
1461 result
.AppendErrorWithFormat("Value 0x%" PRIx64
1462 " is too large to fit in a %" PRIu64
1463 " byte unsigned integer value.\n",
1464 uval64
, (uint64_t)item_byte_size
);
1467 buffer
.PutMaxHex64(uval64
, item_byte_size
);
1470 case eFormatCharArray
:
1472 case eFormatCString
: {
1473 if (entry
.ref().empty())
1476 size_t len
= entry
.ref().size();
1477 // Include the NULL for C strings...
1478 if (m_format_options
.GetFormat() == eFormatCString
)
1481 if (process
->WriteMemory(addr
, entry
.c_str(), len
, error
) == len
) {
1484 result
.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1486 addr
, error
.AsCString());
1491 case eFormatDecimal
:
1492 if (entry
.ref().getAsInteger(0, sval64
)) {
1493 result
.AppendErrorWithFormat(
1494 "'%s' is not a valid signed decimal value.\n", entry
.c_str());
1496 } else if (!llvm::isIntN(item_byte_size
* 8, sval64
)) {
1497 result
.AppendErrorWithFormat(
1498 "Value %" PRIi64
" is too large or small to fit in a %" PRIu64
1499 " byte signed integer value.\n",
1500 sval64
, (uint64_t)item_byte_size
);
1503 buffer
.PutMaxHex64(sval64
, item_byte_size
);
1506 case eFormatUnsigned
:
1508 if (entry
.ref().getAsInteger(0, uval64
)) {
1509 result
.AppendErrorWithFormat(
1510 "'%s' is not a valid unsigned decimal string value.\n",
1513 } else if (!llvm::isUIntN(item_byte_size
* 8, uval64
)) {
1514 result
.AppendErrorWithFormat("Value %" PRIu64
1515 " is too large to fit in a %" PRIu64
1516 " byte unsigned integer value.\n",
1517 uval64
, (uint64_t)item_byte_size
);
1520 buffer
.PutMaxHex64(uval64
, item_byte_size
);
1524 if (entry
.ref().getAsInteger(8, uval64
)) {
1525 result
.AppendErrorWithFormat(
1526 "'%s' is not a valid octal string value.\n", entry
.c_str());
1528 } else if (!llvm::isUIntN(item_byte_size
* 8, uval64
)) {
1529 result
.AppendErrorWithFormat("Value %" PRIo64
1530 " is too large to fit in a %" PRIu64
1531 " byte unsigned integer value.\n",
1532 uval64
, (uint64_t)item_byte_size
);
1535 buffer
.PutMaxHex64(uval64
, item_byte_size
);
1540 if (!buffer
.GetString().empty()) {
1542 const char *buffer_data
= buffer
.GetString().data();
1543 const size_t buffer_size
= buffer
.GetString().size();
1544 const size_t write_size
=
1545 process
->WriteMemory(addr
, buffer_data
, buffer_size
, error
);
1547 if (write_size
!= buffer_size
) {
1548 result
.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1550 addr
, error
.AsCString());
1556 OptionGroupOptions m_option_group
;
1557 OptionGroupFormat m_format_options
;
1558 OptionGroupWriteMemory m_memory_options
;
1561 // Get malloc/free history of a memory address.
1562 class CommandObjectMemoryHistory
: public CommandObjectParsed
{
1564 CommandObjectMemoryHistory(CommandInterpreter
&interpreter
)
1565 : CommandObjectParsed(interpreter
, "memory history",
1566 "Print recorded stack traces for "
1567 "allocation/deallocation events "
1568 "associated with an address.",
1570 eCommandRequiresTarget
| eCommandRequiresProcess
|
1571 eCommandProcessMustBePaused
|
1572 eCommandProcessMustBeLaunched
) {
1573 CommandArgumentEntry arg1
;
1574 CommandArgumentData addr_arg
;
1576 // Define the first (and only) variant of this arg.
1577 addr_arg
.arg_type
= eArgTypeAddress
;
1578 addr_arg
.arg_repetition
= eArgRepeatPlain
;
1580 // There is only one variant this argument could be; put it into the
1582 arg1
.push_back(addr_arg
);
1584 // Push the data for the first argument into the m_arguments vector.
1585 m_arguments
.push_back(arg1
);
1588 ~CommandObjectMemoryHistory() override
= default;
1590 std::optional
<std::string
> GetRepeatCommand(Args
¤t_command_args
,
1591 uint32_t index
) override
{
1596 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
1597 const size_t argc
= command
.GetArgumentCount();
1599 if (argc
== 0 || argc
> 1) {
1600 result
.AppendErrorWithFormat("%s takes an address expression",
1601 m_cmd_name
.c_str());
1606 lldb::addr_t addr
= OptionArgParser::ToAddress(
1607 &m_exe_ctx
, command
[0].ref(), LLDB_INVALID_ADDRESS
, &error
);
1609 if (addr
== LLDB_INVALID_ADDRESS
) {
1610 result
.AppendError("invalid address expression");
1611 result
.AppendError(error
.AsCString());
1615 Stream
*output_stream
= &result
.GetOutputStream();
1617 const ProcessSP
&process_sp
= m_exe_ctx
.GetProcessSP();
1618 const MemoryHistorySP
&memory_history
=
1619 MemoryHistory::FindPlugin(process_sp
);
1621 if (!memory_history
) {
1622 result
.AppendError("no available memory history provider");
1626 HistoryThreads thread_list
= memory_history
->GetHistoryThreads(addr
);
1628 const bool stop_format
= false;
1629 for (auto thread
: thread_list
) {
1630 thread
->GetStatus(*output_stream
, 0, UINT32_MAX
, 0, stop_format
);
1633 result
.SetStatus(eReturnStatusSuccessFinishResult
);
1637 // CommandObjectMemoryRegion
1638 #pragma mark CommandObjectMemoryRegion
1640 #define LLDB_OPTIONS_memory_region
1641 #include "CommandOptions.inc"
1643 class CommandObjectMemoryRegion
: public CommandObjectParsed
{
1645 class OptionGroupMemoryRegion
: public OptionGroup
{
1647 OptionGroupMemoryRegion() : m_all(false, false) {}
1649 ~OptionGroupMemoryRegion() override
= default;
1651 llvm::ArrayRef
<OptionDefinition
> GetDefinitions() override
{
1652 return llvm::ArrayRef(g_memory_region_options
);
1655 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_value
,
1656 ExecutionContext
*execution_context
) override
{
1658 const int short_option
= g_memory_region_options
[option_idx
].short_option
;
1660 switch (short_option
) {
1662 m_all
.SetCurrentValue(true);
1663 m_all
.SetOptionWasSet();
1666 llvm_unreachable("Unimplemented option");
1672 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
1676 OptionValueBoolean m_all
;
1679 CommandObjectMemoryRegion(CommandInterpreter
&interpreter
)
1680 : CommandObjectParsed(interpreter
, "memory region",
1681 "Get information on the memory region containing "
1682 "an address in the current target process.",
1683 "memory region <address-expression> (or --all)",
1684 eCommandRequiresProcess
| eCommandTryTargetAPILock
|
1685 eCommandProcessMustBeLaunched
) {
1686 // Address in option set 1.
1687 m_arguments
.push_back(CommandArgumentEntry
{CommandArgumentData(
1688 eArgTypeAddressOrExpression
, eArgRepeatPlain
, LLDB_OPT_SET_1
)});
1689 // "--all" will go in option set 2.
1690 m_option_group
.Append(&m_memory_region_options
);
1691 m_option_group
.Finalize();
1694 ~CommandObjectMemoryRegion() override
= default;
1696 Options
*GetOptions() override
{ return &m_option_group
; }
1699 void DumpRegion(CommandReturnObject
&result
, Target
&target
,
1700 const MemoryRegionInfo
&range_info
, lldb::addr_t load_addr
) {
1701 lldb_private::Address addr
;
1702 ConstString section_name
;
1703 if (target
.ResolveLoadAddress(load_addr
, addr
)) {
1704 SectionSP
section_sp(addr
.GetSection());
1706 // Got the top most section, not the deepest section
1707 while (section_sp
->GetParent())
1708 section_sp
= section_sp
->GetParent();
1709 section_name
= section_sp
->GetName();
1713 ConstString name
= range_info
.GetName();
1714 result
.AppendMessageWithFormatv(
1715 "[{0:x16}-{1:x16}) {2:r}{3:w}{4:x}{5}{6}{7}{8}",
1716 range_info
.GetRange().GetRangeBase(),
1717 range_info
.GetRange().GetRangeEnd(), range_info
.GetReadable(),
1718 range_info
.GetWritable(), range_info
.GetExecutable(), name
? " " : "",
1719 name
, section_name
? " " : "", section_name
);
1720 MemoryRegionInfo::OptionalBool memory_tagged
= range_info
.GetMemoryTagged();
1721 if (memory_tagged
== MemoryRegionInfo::OptionalBool::eYes
)
1722 result
.AppendMessage("memory tagging: enabled");
1724 const std::optional
<std::vector
<addr_t
>> &dirty_page_list
=
1725 range_info
.GetDirtyPageList();
1726 if (dirty_page_list
) {
1727 const size_t page_count
= dirty_page_list
->size();
1728 result
.AppendMessageWithFormat(
1729 "Modified memory (dirty) page list provided, %zu entries.\n",
1731 if (page_count
> 0) {
1732 bool print_comma
= false;
1733 result
.AppendMessageWithFormat("Dirty pages: ");
1734 for (size_t i
= 0; i
< page_count
; i
++) {
1736 result
.AppendMessageWithFormat(", ");
1739 result
.AppendMessageWithFormat("0x%" PRIx64
, (*dirty_page_list
)[i
]);
1741 result
.AppendMessageWithFormat(".\n");
1746 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
1747 ProcessSP process_sp
= m_exe_ctx
.GetProcessSP();
1749 m_prev_end_addr
= LLDB_INVALID_ADDRESS
;
1750 result
.AppendError("invalid process");
1755 lldb::addr_t load_addr
= m_prev_end_addr
;
1756 m_prev_end_addr
= LLDB_INVALID_ADDRESS
;
1758 const size_t argc
= command
.GetArgumentCount();
1759 const lldb::ABISP
&abi
= process_sp
->GetABI();
1762 if (m_memory_region_options
.m_all
) {
1764 "The \"--all\" option cannot be used when an address "
1765 "argument is given");
1769 auto load_addr_str
= command
[0].ref();
1770 load_addr
= OptionArgParser::ToAddress(&m_exe_ctx
, load_addr_str
,
1771 LLDB_INVALID_ADDRESS
, &error
);
1772 if (error
.Fail() || load_addr
== LLDB_INVALID_ADDRESS
) {
1773 result
.AppendErrorWithFormat("invalid address argument \"%s\": %s\n",
1774 command
[0].c_str(), error
.AsCString());
1777 } else if (argc
> 1 ||
1778 // When we're repeating the command, the previous end address is
1779 // used for load_addr. If that was 0xF...F then we must have
1780 // reached the end of memory.
1781 (argc
== 0 && !m_memory_region_options
.m_all
&&
1782 load_addr
== LLDB_INVALID_ADDRESS
) ||
1783 // If the target has non-address bits (tags, limited virtual
1784 // address size, etc.), the end of mappable memory will be lower
1785 // than that. So if we find any non-address bit set, we must be
1786 // at the end of the mappable range.
1787 (abi
&& (abi
->FixAnyAddress(load_addr
) != load_addr
))) {
1788 result
.AppendErrorWithFormat(
1789 "'%s' takes one argument or \"--all\" option:\nUsage: %s\n",
1790 m_cmd_name
.c_str(), m_cmd_syntax
.c_str());
1794 // It is important that we track the address used to request the region as
1795 // this will give the correct section name in the case that regions overlap.
1796 // On Windows we get mutliple regions that start at the same place but are
1797 // different sizes and refer to different sections.
1798 std::vector
<std::pair
<lldb_private::MemoryRegionInfo
, lldb::addr_t
>>
1800 if (m_memory_region_options
.m_all
) {
1801 // We don't use GetMemoryRegions here because it doesn't include unmapped
1802 // areas like repeating the command would. So instead, emulate doing that.
1803 lldb::addr_t addr
= 0;
1804 while (error
.Success() && addr
!= LLDB_INVALID_ADDRESS
&&
1805 // When there are non-address bits the last range will not extend
1806 // to LLDB_INVALID_ADDRESS but to the max virtual address.
1807 // This prevents us looping forever if that is the case.
1808 (!abi
|| (abi
->FixAnyAddress(addr
) == addr
))) {
1809 lldb_private::MemoryRegionInfo region_info
;
1810 error
= process_sp
->GetMemoryRegionInfo(addr
, region_info
);
1812 if (error
.Success()) {
1813 region_list
.push_back({region_info
, addr
});
1814 addr
= region_info
.GetRange().GetRangeEnd();
1818 lldb_private::MemoryRegionInfo region_info
;
1819 error
= process_sp
->GetMemoryRegionInfo(load_addr
, region_info
);
1820 if (error
.Success())
1821 region_list
.push_back({region_info
, load_addr
});
1824 if (error
.Success()) {
1825 for (std::pair
<MemoryRegionInfo
, addr_t
> &range
: region_list
) {
1826 DumpRegion(result
, process_sp
->GetTarget(), range
.first
, range
.second
);
1827 m_prev_end_addr
= range
.first
.GetRange().GetRangeEnd();
1830 result
.SetStatus(eReturnStatusSuccessFinishResult
);
1834 result
.AppendErrorWithFormat("%s\n", error
.AsCString());
1837 std::optional
<std::string
> GetRepeatCommand(Args
¤t_command_args
,
1838 uint32_t index
) override
{
1839 // If we repeat this command, repeat it without any arguments so we can
1840 // show the next memory range
1844 lldb::addr_t m_prev_end_addr
= LLDB_INVALID_ADDRESS
;
1846 OptionGroupOptions m_option_group
;
1847 OptionGroupMemoryRegion m_memory_region_options
;
1850 // CommandObjectMemory
1852 CommandObjectMemory::CommandObjectMemory(CommandInterpreter
&interpreter
)
1853 : CommandObjectMultiword(
1854 interpreter
, "memory",
1855 "Commands for operating on memory in the current target process.",
1856 "memory <subcommand> [<subcommand-options>]") {
1857 LoadSubCommand("find",
1858 CommandObjectSP(new CommandObjectMemoryFind(interpreter
)));
1859 LoadSubCommand("read",
1860 CommandObjectSP(new CommandObjectMemoryRead(interpreter
)));
1861 LoadSubCommand("write",
1862 CommandObjectSP(new CommandObjectMemoryWrite(interpreter
)));
1863 LoadSubCommand("history",
1864 CommandObjectSP(new CommandObjectMemoryHistory(interpreter
)));
1865 LoadSubCommand("region",
1866 CommandObjectSP(new CommandObjectMemoryRegion(interpreter
)));
1867 LoadSubCommand("tag",
1868 CommandObjectSP(new CommandObjectMemoryTag(interpreter
)));
1871 CommandObjectMemory::~CommandObjectMemory() = default;